安裝:composer require mrgoon/aliyun-sms dev-master
在config/app.php里的providers配置
'providers'=>[
/**
* 阿里云短信
*/
Mrgoon\AliSms\ServiceProvider::class,
]
順便設(shè)置別名
'aliases' => [
/**
* 阿里云短信
*/
'AliSms'=>Mrgoon\AliSms\ServiceProvider::class,
]
運行 php artisan vendor:publish
命令
配置config/aliyunsms.php
return [
'access_key' => env('ALIYUN_ACCESSKEYID'), // accessKey
'access_secret' => env('ALIYUN_ACCESSKEYSECRET'), // accessSecret
'sign_name' => env('ALIYUN_SMS_SIGN_NAME'), // 簽名
];
在.env文件配置以下三項
ALIYUN_ACCESSKEYID=簽名id
ALIYUN_ACCESSKEYSECRET=簽名key 密碼
ALIYUN_SMS_SIGN_NAME=你的簽名
在Driver文件夾新建一個AliAliSMSDrv.php
class AliSMSDrv
{
/**
* 發(fā)送驗證碼
* @param $account
* @param $msg
* @return bool|mixed
*/
public function sendCode($account,$msg)
{
$response = $this->sendSMS($account,array('msgno'=>$msg));
return $response;
}
/**
* 通用
* @param $mobile 手機號
* @param $data 數(shù)據(jù)格式
* $data = array('key1'=>'value1','key2'=>'value2', …… )
* @param string $templateCode 短信模板Code
* @return bool
*/
public static function sendSMS($mobile, $data, $templateCode='你的模板id') {
$aliSms = new AliSms();
$response = $aliSms->sendSms($mobile,$templateCode, $data);
if($response->Message == 'OK'){
return true;
}else {
return false;
}
}
}
接著在需要使用的地方調(diào)用
驗證碼業(yè)務(wù)邏輯層
<?php
/**
* 驗證碼業(yè)務(wù)邏輯層
* Created by PhpStorm.
* User: Administrator
* Date: 2018/12/26
* Time: 10:12
*/
namespace App\Services;
use App\Models\ValidateCode;
use App\Models\User;
use App\Driver\AliSMSDrv;
use App\Exceptions\WrongException;
class ValidateCodeService extends BaseModelService {
const PHONE_VALIDATE = 'phone';//獲取手機驗證碼
private $phone_driver = AliSMSDrv::class;
protected static function getModel()
{
return ValidateCode::class;
}
/**
* 生成隨機的短信驗證碼貌笨,修改驗證碼長度在AppServiceProvider中驗證碼拓展校驗
*/
private function genValidateCode()
{
return mt_rand(000000,999999);
}
/**
* 獲取驗證碼
*/
public function getCode($account,$type)
{
//生成隨機的驗證碼
$code = $this->genValidateCode();
//發(fā)送驗證碼
$driver = new $this->phone_driver();
$result = $driver->sendCode($account,$code);
if (!$result) {
throw new WrongException('發(fā)送失敗');
}
//刪除舊的驗證碼
ValidateCode::where(['account'=>$account,'v_type'=>$type])->delete();
//發(fā)送成功后將驗證碼保存到數(shù)據(jù)庫
$validate_code = new ValidateCode();
$validate_code->account = $account;
$validate_code->v_type = $type;
$validate_code->send_time = time();
$validate_code->v_code = $code;
if(!$validate_code->save()){
throw new WrongException('發(fā)送驗證碼失敗');
}
return $code;
}
/**
* 驗證驗證碼是否正確
*/
public function checkCode($mobile,$v_code)
{
$limit_secords = 900 + time();
$record = ValidateCode::where('send_time','<',$limit_secords)
->where('account', '=', $mobile)
->orderBy('v_id','desc')
->first();
if($record){
if ($record->v_times >= 5) {
throw new WrongException('請重新獲取驗證碼');
}
$record->v_times = $record->v_times + 1;
$record->save();
if($record->v_code == $v_code){
ValidateCode::destroy($record->v_id);
return true;
}
}
throw new WrongException('驗證碼錯誤');
}
}