Home > Article > PHP Framework > 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!