上一篇文章中寫了如何使用騰訊云的接口發(fā)送短信五督。
這篇文章來使用短信構(gòu)建一個“創(chuàng)建驗證碼”+“核對驗證碼”的流程寝并。
第一步:在發(fā)送驗證碼時习寸,將驗證碼與手機(jī)號進(jìn)行持久化。
先在Mysql中建立一張存放驗證碼的表鹉戚,表結(jié)構(gòu)如下
captcha表結(jié)構(gòu)
再使用命令行建立一個Captcha的Model
php artisan make:model Models/Captcha
在模型內(nèi)指向表,約定好可寫的字段為'phone','code':
//Captcha.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Captcha extends Model
{
protected $table = 'captchas';
protected $fillable = [
'phone','code'
];
}
接下來在CodeService中加入數(shù)據(jù)庫操作专控,使用Eloquent的updateOrCreate方法抹凳。
public function getCode($phone,$code)
{
$result = $this->smsServer->sendWithParam(
'86',
$phone,
$this->templateId,
[$code,30],
$this->sms['smsSign']
);
//存入數(shù)據(jù)庫,使用phone字段進(jìn)行過濾
Captcha::updateOrCreate(['phone'=>$phone], ['code'=>$code]);
return json_decode($result, true);
}
到這里,將發(fā)送驗證碼與驗證碼持久化的工作做完伦腐。
第二步:構(gòu)建驗證碼驗證接口
直接在CodeService中赢底,添加校驗驗證碼的方法即可
/**
* @param $phone 接收驗證碼的手機(jī)號
* @param $code 需要驗證的驗證碼
*/
public function checkCode($phone,$code){
$captcha = Captcha::where(['phone'=>$phone,'code'=>$code])->first();
if ($captcha){
$captcha->delete();
return true;
}else{
return false;
}
}