Develop membership distribution system based on Laravel
Recently, a new membership system was added to Sitesauce’s existing basis, and I wrote this article on the specific implementation details.
Notes: I'm going to build this program from scratch so that no matter what stage you're at, you can read the article. Of course, if you are already very familiar with Laravel, you can do this on a platform like Rewardful, which will save a lot of time.
In order to clarify the concept, in the following text, the inviter is replaced by superior, and the invitee is replaced by subordinate
First, we need to clarify our needs: First, users can share link invitations through the program For friend registration, the invitees can register through the link to bind the invitation relationship. Secondly, when the subordinate consumes, the superior can get the corresponding commission.
Now we have to determine how to implement registration. I originally planned to use Fathom's method. As long as the user is directed to a specific page, the user will be marked as a special referral page. After the user completes the registration, the relationship will be bound. But in the end, Rewardful’s approach was adopted, by adding the parameter ?via=miguel to the link to build the recommendation page.
Okay, now let us create our registration page. On the registration page, the program will match the superior through the link parameter via. The code is simple, if via exists then store it in a cookie for 30 days, since we have several different subdomains that need this, we add it under the main domain so that all subdomains can use the cookie. The specific code is as follows:
import Cookies from 'js-cookie' const via = new URL(location.href).searchParams.get('via') if (via) { Cookies.set('sitesauce_affiliate', via, { expires: 30, domain: '.sitesauce.app', secure: true, sameSite: 'lax' }) }
The advantage of this is that when a member does not register through this sharing, but registers by himself afterwards, you can clearly know that the member came through the recommendation of that superior. I want to go one step further and display some slogans and superior information when a new member registers, so that the user clearly knows that this is a referral link from a member (friend), thereby making the registration success rate higher, so I added a prompt Pop-ups. The effect is as follows:
If we want to achieve the above effect, now we need not only the upper-level tags, but also the upper-level detailed information, so we need an API that will match and provide the upper-level detailed information through via.
import axios from 'axios' import Cookies from 'js-cookie' const via = new URL(location.href).searchParams.get('via') if (via) { axios.post(`https://app.sitesauce.app/api/affiliate/${encodeURIcomponent(this.via)}`).then(response => { Cookies.set('sitesauce_affiliate', response.data, { expires: 30, domain: '.sitesauce.app', secure: true, sameSite: 'lax' }) }).catch(error => { if (!error.response || error.response.status !== 404) return console.log('Something went wrong') console.log('Affiliate does not exist. Register for our referral program here: https://app.sitesauce.app/affiliate') }) }
You can see encodeURIComponent in the URL, its role is to protect us from Path Traversal vulnerability. When we send a request to /api/referral/:via, if someone maliciously changes the link parameters, like this: ?via=../../logout, the user may log out after clicking. Of course, this may have no impact. But it is inevitable that there will be other operations that will bring unexpected effects.
Since Sitesauce uses Alpine in some places, we modified the pop-up window into an Alpine component based on this, which has better scalability. I would like to thank Ryan for giving me valuable advice when my conversion was not working properly.
<div x-data="{ ...component() } x-cloak x-init="init()"> <template x-if="affiliate"> <div> <img :src="affiliate.avatar" class="h-8 w-8 rounded-full mr-2"> <p>Your friend <span x-text="affiliate.name"></span> has invited you to try Sitesauce</p> <button>Start your trial</button> </div> </template> </div> <script> import axios from 'axios' import Cookies from 'js-cookie' // 使用模板标签 $nextTick ,进行代码转换,这里特别感谢下我的朋友 Ryan window.component = () => ({ affiliate: null, via: new URL(location.href).searchParams.get('via') init() { if (! this.via) return this.$nextTick(() => this.affiliate = Cookies.getJSON('sitesauce.affiliate')) axios.post(`https://app.sitesauce.app/api/affiliate/${encodeURIComponent(this.via)}`).then(response => { this.$nextTick(() => this.affiliate = response.data) Cookies.set('sitesauce.affiliate', response.data, { expires: 30, domain: '.sitesauce.app', secure: true, sameSite: 'lax' }) }).catch(error => { if (!error.response || error.response.status !== 404) return console.log('Something went wrong') console.log('Affiliate does not exist. Register for our referral program here: https://app.sitesauce.app/affiliate') }) } }) </script>
Now, improve the API so that it can obtain valid data. In addition, we also need to add several fields to our existing database, which we will explain later. The following is the migration file:
class AddAffiliateColumnsToUsersTable extends Migration { /** * 迁移执行 * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->string('affiliate_tag')->nullable(); $table->string('referred_by')->nullable(); $table->string('paypal_email')->nullable(); $table->timestamp('cashed_out_at')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('affiliate_tag', 'referred_by', 'paypal_email', 'cashed_out_at'); }); } }
Implement parameter binding through the routing custom key name function (can be used on Laravel 7.X) to build our API routing.
Route::post('api/affiliate/{user:affiliate_tag}', function (User $user) { return $user->only('id', 'name', 'avatar', 'affiliate_tag'); })->middleware('throttle:30,1');
Before starting the registration operation, first read our Cookie. Since it is not encrypted, we need to add it to the except field of EncryptCookies to exclude it.
// 中间件:app/Http/Middleware/EncryptCookies.php use Illuminate\Cookie\Middleware\EncryptCookies as Middleware; class EncryptCookies extends Middleware { /** * The names of the cookies that should not be encrypted * * @var array */ protected $except = [ 'sitesauce_referral', ]; }
Now execute the registration corresponding logic through the authenticated method of RegisterController. During this period, we obtain the Cooke through the above method, and find the corresponding superior through the Cooke, and finally associate the subordinate with the superior.
/** * 上级用户已经注册 * * @param \Illuminate\Http\Request $request * @param \App\User $user */ protected function registered(Request $request, User $user) { if (! $request->hasCookie('sitesauce.referral')) return; $referral = json_decode($request->cookie('sitesauce_referral'), true)['affiliate_tag']; if (! User::where('affiliate_tag', $referral)->exists()) return; $user->update([ 'referred_by' => $referral, ]); }
We also need a method to get the list of my subordinate users, which can be easily achieved through the hasMany method of ORM.
class User extends Model { public function referred() { return $this->hasMany(self::class, 'referred_by', 'affiliate_tag'); } }
Now, let’s build our registration page. When users register, they can select the preferences tab and require them to provide their PayPal email for subsequent withdrawal operations. The following is a preview of the effect:
After member registration, we also need to provide changes to email addresses and related entrances for label changes. After it changes its label, we need to cascade update the labels of its subordinate users to ensure the unity of the two. This involves database transaction operations. To ensure the atomicity of the operation, we need to complete the above two operations in the transaction. The code is as follows:
public function update(Request $request) { $request->validate([ 'affiliate_tag' => ['required', 'string', 'min:3', 'max:255', Rule::unique('users')->ignoreModel($request->user())], 'paypal_email' => ['required', 'string', 'max:255', 'email'], ]); DB::transaction(function () use ($request) { if ($request->input('affiliate_tag') != $request->user()->affiliate_tag) { User::where('referred_by', $request->user()->affiliate_tag) ->update(['referred_by' => $request->input('affiliate_tag')]); } $request->user()->update([ 'affiliate_tag' => $request->input('affiliate_tag'), 'paypal_email' => $request->input('paypal_email'), ]); }); return redirect()->route('affiliate'); }
Next we need to determine the calculation method of member income. The percentage of all consumption amounts of lower-level users can be returned to the superior as a commission. For the convenience of calculation, we only calculate since the last settlement date. The data. We use the extension Mattias’ percentages package to make the calculations simple and straightforward.
use Mattiasgeniar\Percentage\Percentage; const COMMISSION_PERCENTAGE = 20; public function getReferralBalance() : int { return Percentage::of(static::COMISSION_PERCENTAGE, $this->referred ->map(fn (User $user) => $user->invoices(false, ['created' => ['gte' => optional($this->cashed_out_at)->timestamp]])) ->flatten() ->map(fn (\Stripe\Invoice $invoice) => $invoice->subtotal) ->sum() ); }
Finally, we distribute the commission to the superior in the form of monthly settlement, and update the cashed_out_at field to the commission distribution time. The effect is as follows:
At this point, I hope the above documents will be helpful to you. I wish you happiness every day.
Recommended tutorial: "Laravel Tutorial"
The above is the detailed content of Develop membership distribution system based on Laravel. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.
