上一篇文章中寫了如何使用騰訊云的接口發(fā)送短信。
這篇文章來使用短信構建一個“創(chuàng)建驗證碼”+“核對驗證碼”的流程。
第一步:在發(fā)送驗證碼時,將驗證碼與手機號進行持久化。
先在Mysql中建立一張存放驗證碼的表,表結構如下

captcha表結構
再使用命令行建立一個Captcha的Model
php artisan make:model Models/Captcha
在模型內指向表,約定好可寫的字段為'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ù)據庫操作,使用Eloquent的updateOrCreate方法。
public function getCode($phone,$code)
{
$result = $this->smsServer->sendWithParam(
'86',
$phone,
$this->templateId,
[$code,30],
$this->sms['smsSign']
);
//存入數(shù)據庫,使用phone字段進行過濾
Captcha::updateOrCreate(['phone'=>$phone], ['code'=>$code]);
return json_decode($result, true);
}
到這里,將發(fā)送驗證碼與驗證碼持久化的工作做完。
第二步:構建驗證碼驗證接口
直接在CodeService中,添加校驗驗證碼的方法即可
/**
* @param $phone 接收驗證碼的手機號
* @param $code 需要驗證的驗證碼
*/
public function checkCode($phone,$code){
$captcha = Captcha::where(['phone'=>$phone,'code'=>$code])->first();
if ($captcha){
$captcha->delete();
return true;
}else{
return false;
}
}