vsevolod-ryzhov/yii2-code-validation

通过密钥(短信等)验证表单更改

v0.2 2020-05-31 09:13 UTC

This package is auto-updated.

Last update: 2024-09-29 05:49:29 UTC


README

通过外部服务(短信、电子邮件等)发送的代码验证模型更改

安装

通过 Composer

composer require vsevolod-ryzhov/yii2-code-validation

使用方法

在您的控制器中注入服务

private $service;

public function __construct($id, $module, \vsevolodryzhov\yii2CodeValidation\Service $service, $config = [])
{
    parent::__construct($id, $module, $config);
    $this->service = $service;
}

创建带有某些表单(模型或ActiveRecord)的操作

public function actionChangeRequest()
{
    $form = new Form();

    if ($form->load(Yii::$app->request->post()) && $form->validate()) {
        // if form submitted and validated use "set" function to store form and get generated code
        $code = $this->service->set($form);
        // send $code here and then redirect to verify action
        return $this->redirect('/verify');
    }

    return $this->render('change', ['form' => $form]);
}

创建验证操作

public function actionVerify()
{
    if (!$this->service->exists()) {
        // if nothing to verify - throw new Exception, redirect or do something else
    }

    // create CodeValidationForm (included in this package) with stored code and new instance of same form, created in previews action
    $form = new \vsevolodryzhov\yii2CodeValidation\CodeValidationForm($this->service->getCode(), new Form($this->service->getData()));

    if ($form->load(Yii::$app->request->post()) && $form->validate()) {
        // clear all data on success
        $this->service->clear();
        // refresh or redirect to success page
        return $this->refresh();
    }

    return $this->render('verify', ['form' => $form]);
}

此外,您还可以创建额外的操作来更新现有代码

public function actionUpdate()
{
    $response = $this->service->renewCode();
}

renewCode 操作返回包含一些有用信息的 \vsevolodryzhov\yii2CodeValidation\Response 对象

  • $response->getDone() 返回 true 如果代码已更新
  • $response->getWait() 返回下一次可能的更新时间之前的秒数
  • $response->getCode() 返回新代码(如果已生成)或 null