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 class="h-8 w-8 rounded-full mr-2 lazy" src="/static/imghwm/default1.png" data-src="affiliate.avatar" : alt="Develop membership distribution system based on Laravel" > <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!

Laravel stands out by simplifying the web development process and delivering powerful features. Its advantages include: 1) concise syntax and powerful ORM system, 2) efficient routing and authentication system, 3) rich third-party library support, allowing developers to focus on writing elegant code and improve development efficiency.

Laravelispredominantlyabackendframework,designedforserver-sidelogic,databasemanagement,andAPIdevelopment,thoughitalsosupportsfrontenddevelopmentwithBladetemplates.

Laravel and Python have their own advantages and disadvantages in terms of performance and scalability. Laravel improves performance through asynchronous processing and queueing systems, but due to PHP limitations, there may be bottlenecks when high concurrency is present; Python performs well with the asynchronous framework and a powerful library ecosystem, but is affected by GIL in a multi-threaded environment.

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

Laravel can be used for front-end development. 1) Use the Blade template engine to generate HTML. 2) Integrate Vite to manage front-end resources. 3) Build SPA, PWA or static website. 4) Combine routing, middleware and EloquentORM to create a complete web application.

PHP and Laravel can be used to build efficient server-side applications. 1.PHP is an open source scripting language suitable for web development. 2.Laravel provides routing, controller, EloquentORM, Blade template engine and other functions to simplify development. 3. Improve application performance and security through caching, code optimization and security measures. 4. Test and deployment strategies to ensure stable operation of applications.

Laravel and Python have their own advantages and disadvantages in terms of learning curve and ease of use. Laravel is suitable for rapid development of web applications. The learning curve is relatively flat, but it takes time to master advanced functions. Python's grammar is concise and the learning curve is flat, but dynamic type systems need to be cautious.

Laravel's advantages in back-end development include: 1) elegant syntax and EloquentORM simplify the development process; 2) rich ecosystem and active community support; 3) improved development efficiency and code quality. Laravel's design allows developers to develop more efficiently and improve code quality through its powerful features and tools.


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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.