D
D
Daniil Sidorov2019-08-02 11:38:51
Yii
Daniil Sidorov, 2019-08-02 11:38:51

Yii2. How to implement a referral system?

Good afternoon.
I'm trying to implement a referral program on the site. Right now it only works when going to the main page.
I just check the required GET parameter:

//SiteController actionIndex

$ref_name = Yii::$app->request->get('ref');
//Если есть параметр ref, то записываю куки
//И потом просто заново перенаправляю на главную страницу
$this->redirect(Yii::app()->getHomeUrl());

But I want to make sure that the referral link can lead to any page. I am trying to do the following. I inherited all the necessary controllers from MainController , and in MainController I create beforeAction :
//MainController

public function beforeAction($action)
{
    $ref_name = Yii::$app->request->get('ref');
    //Далее стандартные проверки на наличие такого рефа и запись куки
    //Но теперь надо перенаправить на запрашиваемую страницу
    //убрав при этом GET параметр "ref"
    return parent::beforeAction($action);
}

It is necessary that, when entering, it is allowed to: the
site.com/article?ref=123
user eventually gets to:
site.com/article
There is also a difficulty with pages that already have other parameters:
site.com/article/view?id=20&ref=123
It is necessary to somehow remove the "ref" parameter, and leave the rest:
site.com/article/view?id=20
Perhaps someone has some experience in this topic. Or does it make no sense to bother with hiding these parameters? Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2019-08-02
@DaniLaFokc

And if you forget to inherit from this controller somewhere? It is possible for you to decide without inheritance from the main controller. Hang the handler on the whole application using before or after:

'as beforeAction' => function () {
//Тут ваши действия для анонимной функции
}

If there is a lot of logic, use a separate class, for example, behaviors. But behaviors will be removed in Yii3. Think about it too)
'as beforeAction' => [
        'class' => app\modules\users\behaviors\LastVisitBehavior::class
    ],

You can clear the URL from the required parameter with PS It seems to me that it is not necessary to make a referral link to all actions. It is unlikely that the user will change the link. And why should you consider it. Give a working link to register. There you are looking for the desired option. Remember it and always substitute it when registering, if any. But why do you need a referral in the news, articles and so on. I don’t understand the expediency of the decision) Usually they do something like this:
/**
     * Страница сохранения реферера (пригласившего)
     *
     * @param int $id
     *
     * @return Response|string
     */
    public function actionReferral(int $id)
    {
        if (Yii::$app->user->isGuest) {
            ReferralHelper::setReferrerId($id);
        }
        return $this->redirect('site/registration');
    }

/**
     * Страница регистрации
     *
     * @return Response|string
     * @throws \yii\base\InvalidArgumentException
     * @throws \yii\db\Exception
     */
    public function actionRegistration()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        $userForm = new UserForm();
        if ($userForm->load(Yii::$app->request->post())) {
            $referrerId = ReferralHelper::getReferrerId();
            $referrer = $referrerId !== null ? $this->getUser((int)$referrerId) : null;
            $userForm->setReferrer($referrer);
            if ($userForm->save() && $userForm->login()) {
                $message = 'Спасибо за регистрацию.';
                if ($referrer !== null) {
                    $message .= ' Вас пригласил ' . $referrer;
                }
                Yii::$app->session->setFlash('success', $message);
                ReferralHelper::removeReferrer();
                return $this->goHome();
            }
            $this->addErrorForForm($userForm);
        }
        $userForm->password = '';
        return $this->render('registration', [
            'model' => $userForm,
        ]);
    }

class ReferralHelper
{
    const KEY_REFERRER_ID = 'referrer_id';
    public static function setReferrerId(int $referrerId)
    {
        \Yii::$app->getSession()->set(self::KEY_REFERRER_ID, $referrerId);
    }
    public static function getReferrerId()
    {
        return \Yii::$app->getSession()->get(self::KEY_REFERRER_ID, null);
    }
    public static function removeReferrer()
    {
        return \Yii::$app->getSession()->remove(self::KEY_REFERRER_ID);
    }
}

I took it from a ready-made solution on Yii2. The code is not very good, but it works.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question