Home > PHP Framework > Laravel > Develop membership distribution system based on Laravel

Develop membership distribution system based on Laravel

Guanhui
Release: 2020-05-28 10:16:32
forward
3690 people have browsed it

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'
    })
}
Copy after login

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')
    })
}
Copy after login

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 &#39;axios&#39;
import Cookies from &#39;js-cookie&#39;
// 使用模板标签 $nextTick ,进行代码转换,这里特别感谢下我的朋友 Ryan 
window.component = () => ({
    affiliate: null,
    via: new URL(location.href).searchParams.get(&#39;via&#39;)
    init() {
        if (! this.via) return this.$nextTick(() => this.affiliate = Cookies.getJSON(&#39;sitesauce.affiliate&#39;))
        axios.post(`https://app.sitesauce.app/api/affiliate/${encodeURIComponent(this.via)}`).then(response => {
            this.$nextTick(() => this.affiliate = response.data)
            Cookies.set(&#39;sitesauce.affiliate&#39;, response.data, {
                expires: 30, domain: &#39;.sitesauce.app&#39;, secure: true, sameSite: &#39;lax&#39;
            })
        }).catch(error => {
            if (!error.response || error.response.status !== 404) return console.log(&#39;Something went wrong&#39;)
            console.log(&#39;Affiliate does not exist. Register for our referral program here: https://app.sitesauce.app/affiliate&#39;)
        })
    }
})
</script>
Copy after login

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(&#39;users&#39;, function (Blueprint $table) {
            $table->string(&#39;affiliate_tag&#39;)->nullable();
            $table->string(&#39;referred_by&#39;)->nullable();
            $table->string(&#39;paypal_email&#39;)->nullable();
            $table->timestamp(&#39;cashed_out_at&#39;)->nullable();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table(&#39;users&#39;, function (Blueprint $table) {
            $table->dropColumn(&#39;affiliate_tag&#39;, &#39;referred_by&#39;, &#39;paypal_email&#39;, &#39;cashed_out_at&#39;);
        });
    }
}
Copy after login

Implement parameter binding through the routing custom key name function (can be used on Laravel 7.X) to build our API routing.

Route::post(&#39;api/affiliate/{user:affiliate_tag}&#39;, function (User $user) {
    return $user->only(&#39;id&#39;, &#39;name&#39;, &#39;avatar&#39;, &#39;affiliate_tag&#39;);
})->middleware(&#39;throttle:30,1&#39;);
Copy after login

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 = [
        &#39;sitesauce_referral&#39;,
    ];
}
Copy after login

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(&#39;sitesauce.referral&#39;)) return;
    $referral = json_decode($request->cookie(&#39;sitesauce_referral&#39;), true)[&#39;affiliate_tag&#39;];
    if (! User::where(&#39;affiliate_tag&#39;, $referral)->exists()) return;
    $user->update([
        &#39;referred_by&#39; => $referral,
    ]);
}
Copy after login

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, &#39;referred_by&#39;, &#39;affiliate_tag&#39;);
    }
}
Copy after login

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([
            &#39;affiliate_tag&#39; => [&#39;required&#39;, &#39;string&#39;, &#39;min:3&#39;, &#39;max:255&#39;, Rule::unique(&#39;users&#39;)->ignoreModel($request->user())],
            &#39;paypal_email&#39; => [&#39;required&#39;, &#39;string&#39;, &#39;max:255&#39;, &#39;email&#39;],
        ]);
        DB::transaction(function () use ($request) {
            if ($request->input(&#39;affiliate_tag&#39;) != $request->user()->affiliate_tag) {
                User::where(&#39;referred_by&#39;, $request->user()->affiliate_tag)
                    ->update([&#39;referred_by&#39; => $request->input(&#39;affiliate_tag&#39;)]);
            }
            $request->user()->update([
                &#39;affiliate_tag&#39; => $request->input(&#39;affiliate_tag&#39;),
                &#39;paypal_email&#39; => $request->input(&#39;paypal_email&#39;),
            ]);
        });
        return redirect()->route(&#39;affiliate&#39;);
    }
Copy after login

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, [&#39;created&#39; => [&#39;gte&#39; => optional($this->cashed_out_at)->timestamp]]))
            ->flatten()
            ->map(fn (\Stripe\Invoice $invoice) => $invoice->subtotal)
            ->sum()
    );
}
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template