Browse Source

短信验证码接口+ali_api

master
wanghongjun 2 years ago
parent
commit
24c0838298
  1. 60
      app/common/lib/sms/AliSms/AliSms.php
  2. 44
      app/controller/Passport.php
  3. 36
      app/model/Pincode.php
  4. 28
      app/validate/User.php
  5. 3
      composer.json
  6. 1778
      composer.lock
  7. 21
      config/alisms.php
  8. 9
      route/app.php

60
app/common/lib/sms/AliSms/AliSms.php

@ -0,0 +1,60 @@
<?php
namespace app\common\lib\sms\AliSms;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class AliSms
{
public static function send(string $phone = null, int $code = null)
{
if (empty($phone) || empty($code)) {
return false;
}
try {
# 转换成json
$templateParam = json_encode(['code' => $code]);
// 创建客户端
AlibabaCloud::accessKeyClient(
config('alisms.accessKeyId'),
config('alisms.accessKeySecret')
)
->regionId(config('alisms.regionId'))
->asDefaultClient();
// 发送请求
$result = AlibabaCloud::rpc()
->product(config('alisms.product'))# 具体产品
->version('2017-05-25') # 指定版本不可修改
->action('SendSms')
->method('POST')
->host(config('alisms.host')) # host地址
->options([
'query' => [
# 指定区域
'RegionId' => config('alisms.regionId'),
//需要发送到那个手机
'PhoneNumbers' => $phone,
//必填项 签名(需要在阿里云短信服务后台申请)
'SignName' => config('alisms.SignName'),
//必填项 短信模板code (需要在阿里云短信服务后台申请)
'TemplateCode' => config('alisms.TemplateCode'),
//如果在短信中添加了${code} 变量则此项必填 要求为JSON格式
'TemplateParam' => $templateParam,
],
])
->request();
$sendRes = $result->toArray();
return $sendRes['Code'] == 'OK' ? ['status' => true, 'msg' => '发送成功'] : ['status' => false, 'msg' => '发送失败'];
} catch (ServerException $e) {
# 记录错误日志
return ['status' => false,'msg' => $e->getErrorMessage().'【1】'];
} catch (ClientException $e) {
# 记录错误日志
return ['status' => false,'msg' => $e->getErrorMessage().'【2】'];
}
}
}

44
app/controller/Passport.php

@ -3,6 +3,8 @@
namespace app\controller;
use app\BaseController;
use app\common\lib\sms\AliSms\AliSms;
use app\model\Pincode;
use app\model\User as UserModel;
use app\validate\User as UserValidate;
use think\exception\ValidateException;
@ -38,8 +40,9 @@ class Passport extends BaseController
return $this->renderError('邀请码无效');
}
if (!$userModel->verifySmsCode($phone, $smsCode)) {
return $this->renderError('短信验证码错误');
$checkCodeRes = validate(UserValidate::class)->checkCode($phone,$smsCode);
if ($checkCodeRes !== true) {
return $this->renderError($checkCodeRes);
}
// 注册用户
@ -93,12 +96,47 @@ class Passport extends BaseController
throw new ValidateException($user['msg']);
}
} catch (ValidateException $exception) {
$data = [];
$data = ['captcha_img' => ''];
if ($count >= $defaultCount) $data['captcha_img'] = captcha_src();
return $this->renderError($exception->getMessage(),$data);
}
}
/**
* 发送短信验证码
* @return array|void
*/
public function sendCode()
{
$data = Request::param();
try {
validate(UserValidate::class)->scene('sendCode')->check($data);
$phone = $data['phone'];
$code = rand(1000 , 9999);
$result = AliSms::send($phone,$code);
if (!$result['status']) {
throw new ValidateException($result['msg']);
}
$Pincode = new Pincode();
$res = $Pincode->sendSave($phone,$code);
if ($res['status']) {
return $this->renderSuccess('发送成功' , ['code' => $code]);
} else {
throw new ValidateException('发送失败');
}
} catch (ValidateException $exception) {
return $this->renderError($exception->getMessage());
}
}
/**
* 变换验证码图片
* @return array

36
app/model/Pincode.php

@ -0,0 +1,36 @@
<?php
declare (strict_types = 1);
namespace app\model;
use think\Model;
/**
* @mixin \think\Model
*/
class Pincode extends Model
{
/**
* 保存短信验证码
* @param $phone
* @param $code
* @return bool[]
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function sendSave($phone,$code)
{
$query = $this->where('mobile',$phone)->find();
if ($query) $this->where('mobile',$phone)->delete();
$this->save([
'mobile' => $phone,
'code' => $code,
'time' => time()
]);
return ['status' => true];
}
}

28
app/validate/User.php

@ -3,6 +3,7 @@ declare (strict_types = 1);
namespace app\validate;
use think\facade\Db;
use think\Validate;
class User extends Validate
@ -38,6 +39,31 @@ class User extends Validate
'login' => ['phone','password'],
'register' => ['phone','password','sms_code'],
'retrieve' => ['phone','password','sms_code'],
'modifyPassword' => ['password']
'modifyPassword' => ['password'],
'sendCode' => ['phone']
];
/**
* 手机号短信验证
* @param $mobile
* @param $code
* @return bool|string
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function checkCode($mobile,$code)
{
$pin_info = Db::name('pincode')->where('mobile',$mobile)->field('code,time')->find();
if (empty($pin_info)) {
return '短信验证码错误';
}
if ($pin_info['time'] < time() - 300) {
return '短信验证码已过期,请重新获取';
}
if ($code != $pin_info['code']) {
return '短信验证码错误';
}
return true;
}
}

3
composer.json

@ -24,7 +24,8 @@
"topthink/framework": "^6.0.0",
"topthink/think-orm": "^2.0",
"firebase/php-jwt": "^6.4",
"topthink/think-captcha": "^3.0"
"topthink/think-captcha": "^3.0",
"alibabacloud/sdk": "^1.8"
},
"require-dev": {
"symfony/var-dumper": "^4.2",

1778
composer.lock

File diff suppressed because it is too large

21
config/alisms.php

@ -0,0 +1,21 @@
<?php
// +----------------------------------------------------------------------
// | 阿里云Sms
// +----------------------------------------------------------------------
return [
// accessKeyId
'accessKeyId' => 'LTAI5tMHed9uPPMiqe5rpJVn',
// accessKeySecret
'accessKeySecret' => 'hBXoJRZoIN2FYDqVzaZn8rU6Uvw6g2',
// 指定区域
'regionId' => 'cn-hangzhou',
// 具体产品
'product' => 'Dysmsapi',
// host地址
'host' => 'dysmsapi.aliyuncs.com',
// 签名(需要在阿里云短信服务后台申请)
'SignName' => '粤职才',
// 短信模板code (需要在阿里云短信服务后台申请)
'TemplateCode' => 'SMS_461395821',
];

9
route/app.php

@ -17,10 +17,11 @@ Route::get('think', function () {
Route::group('passport',function (){
Route::post('register','passport/register');
Route::post('login','passport/login');
Route::post('retrieve','passport/retrieve');
Route::post('changeCaptcha','passport/changeCaptcha');
Route::post('register','passport/register')->allowCrossDomain();;
Route::post('login','passport/login')->allowCrossDomain();;
Route::post('retrieve','passport/retrieve')->allowCrossDomain();;
Route::post('changeCaptcha','passport/changeCaptcha')->allowCrossDomain();;
Route::post('sendCode','passport/sendCode')->allowCrossDomain();;
});
Route::group('user',function (){

Loading…
Cancel
Save