Sms.php
3.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
namespace app\mobile\controller;
use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\User;
use think\Hook;
/**
* 手机短信接口
*/
class Sms extends Api
{
protected $noNeedLogin = '*';
protected $noNeedRight = '*';
/**
* 发送验证码
*
* @param string $mobile 手机号
* @param string $event 事件名称:register=注册,resetpwd=忘记密码,changemobile1=修改手机号第一步,changemobile2=修改手机号第二步,changepwd=修改密码
*/
public function send()
{
$mobile = $this->request->get("mobile");
$event = $this->request->get("event");
$event = $event ? $event : 'register';
if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('手机号不正确'));
}
$last = Smslib::get($mobile, $event);
if ($last && time() - $last['createtime'] < 300) {
$this->error(__('发送频繁'));
}
$ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
if ($ipSendTotal >= 500) {
$this->error(__('发送频繁'));
}
if ($event) {
$userinfo = User::getByMobile($mobile);
if ($event == 'register' && $userinfo) {
//已被注册
$this->error(__('已被注册'));
} elseif (in_array($event, ['changemobile2']) && $userinfo) {
//被占用
$this->error(__('已被占用'));
} elseif (in_array($event, ['changepwd', 'resetpwd', 'changemobile1']) && !$userinfo) {
//未注册
$this->error(__('未注册'));
}
}
$ret = $this->getCode($mobile, null, $event);
if ($ret) {
$this->success(__('发送成功'),['code'=>$ret]);
} else {
$this->error($ret['msg']);
}
}
private function getCode($mobile, $code = null, $event = 'default'){
$code = is_null($code) ? mt_rand(1000, 9999) : $code;
$time = time();
$sms = \app\common\model\Sms::create([
'event' => $event,
'mobile' => $mobile,
'code' => $code,
'ip' => request()->ip(),
'createtime' => $time
]);
// $ret = send_sms2([
// 'content' => "【帛芮定制】您的验证码是:" . $code . ",请尽快返回完成验证,请勿转载或泄露,谨防被骗。",//短信内容
// 'mobile' => $mobile,//手机号码
// 'tKey' => time(),
// ]);
// $ret = json_decode($ret,true);
// if($ret['code'] == 200){
// return true;
// }
// $this->error($ret['msg']);
return $code;
}
/**
* 校验验证码
* @ApiInternal
*/
public static function check($mobile, $code, $event = 'default')
{
$time = time() - 120;
$sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
->order('id', 'DESC')
->find();
if ($sms) {
if ($sms['createtime'] > $time && $sms['times'] <= 10) {
$correct = $code == $sms['code'];
if (!$correct) {
$sms->times = $sms->times + 1;
$sms->save();
return false;
} else {
return true;
}
} else {
// 过期则清空该手机验证码
Smslib::flush($mobile, $event);
return false;
}
} else {
return false;
}
}
}