Sms.php
3.4 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
<?php
namespace app\api\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 事件名称
*/
public function send()
{
$mobile = $this->request->get("mobile");
$this->error('测试:'.$mobile);
$event = $this->request->param("event");
$event = $event ? $event : 'changemobile';
if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('手机号不正确'));
}
$last = Smslib::get($mobile, $event);
if ($last && time() - $last['createtime'] < 60) {
$this->error(__('发送频繁'));
}
$ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
if ($ipSendTotal >= 5) {
$this->error(__('发送频繁'));
}
if ($event) {
$userinfo = User::getByMobile($mobile);
if ($event == 'changemobile' && $userinfo) {
//已被注册
$this->error(__('已被占用'));
}
}
// if (!Hook::get('sms_send')) {
// $this->error(__('请在后台插件管理安装短信验证插件'));
// }
// $ret = Smslib::send($mobile, null, $event);
$ret = $this->getCode($mobile, null, $event);
if ($ret) {
$this->success(__('发送成功'));
} else {
$this->error($ret['msg']);
}
}
public 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']);
}
/**
* 校验验证码
*/
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;
}
}
}