feat(sms): 集成腾讯云短信插件并打通双端短信验证码业务链路

- 插件管理:集成 qcloudsms 腾讯云短信发送插件,配置应用AppID/AppKey、短信签名及各业务模板ID(登录、修改密码、重置密码、支付密码、订单核销通知)
- 业务封装:新增 SmsService 统一业务短信服务,实现防刷限流、冷却控制、短信验证码发送与防重放校验,支持完工订单自动下发客户核销码
- 接口层:恢复并升级 Sms 控制器,并在 Auth/MasterAuth/Security 控制器中支持手机验证码登录、找回登录密码及短信验证设置/修改支付密码
- 小程序端:用户端与师傅端登录页、账号安全中心、支付密码组件全面适配短信验证码交互,优化用户找回密码与支付密码安全操作流程
- 部署脚本:优化 deploy_all.py 打包剪枝逻辑,全局过滤深层 .git 目录并规范打包相对路径
这个提交包含在:
2026-11-26 15:54:15 +08:00
父节点 3baa02771a
当前提交 c664d0a5de
共有 34 个文件被更改,包括 4023 次插入 和 160 次删除

查看文件

@@ -2,6 +2,10 @@
namespace app\api\controller;
use app\common\library\AccountSecurity;
use app\common\library\SmsService;
use app\common\library\Token;
use fast\Random;
use think\Db;
use think\Validate;
@@ -10,7 +14,7 @@ use think\Validate;
*/
class Auth extends Base
{
protected $noNeedLogin = ['login', 'wxlogin', 'wxPhoneLogin'];
protected $noNeedLogin = ['login', 'wxlogin', 'wxPhoneLogin', 'sendResetPasswordSms', 'resetPasswordBySms'];
/**
* 手机号 + 密码登录(仅支持账号密码或微信一键登录,短信验证码通道已移除)
@@ -73,6 +77,104 @@ class Auth extends Base
]);
}
/**
* 发送忘记登录密码短信验证码(H5/未登录找回密码)
* @ApiMethod (POST)
*/
public function sendResetPasswordSms()
{
try {
$mobile = SmsService::normalizeMobile((string)$this->request->post('mobile', ''));
} catch (\InvalidArgumentException $e) {
$this->error($e->getMessage());
return;
}
$user = Db::name('user')->field('id,status')->where('mobile', $mobile)->find();
if (!$user) {
$this->error('该手机号尚未注册账号');
return;
}
if (isset($user['status']) && $user['status'] !== 'normal') {
$this->error('账号已被禁用');
return;
}
try {
$res = SmsService::sendVerifyCode($mobile, 'user_resetpwd', $this->request->ip());
$this->success('验证码已发送,请注意查收', array_merge($res, [
'mobile' => substr_replace($mobile, '****', 3, 4),
]));
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
}
/**
* 通过短信验证码重置登录密码(忘记密码)
* @ApiMethod (POST)
*/
public function resetPasswordBySms()
{
try {
$mobile = SmsService::normalizeMobile((string)$this->request->post('mobile', ''));
} catch (\InvalidArgumentException $e) {
$this->error($e->getMessage());
return;
}
$smsCode = trim((string)$this->request->post('sms_code', $this->request->post('captcha', '')));
$newPassword = (string)$this->request->post('new_password', '');
if (!preg_match('/^\S{6,30}$/', $newPassword)) {
$this->error('登录密码须为6至30位非空字符');
return;
}
$user = Db::name('user')->field('id,status')->where('mobile', $mobile)->find();
if (!$user) {
$this->error('该手机号尚未注册账号');
return;
}
if (isset($user['status']) && $user['status'] !== 'normal') {
$this->error('账号已被禁用');
return;
}
try {
SmsService::verifyCode($mobile, $smsCode, 'user_resetpwd', true);
} catch (\Throwable $e) {
$this->error($e->getMessage());
return;
}
$uid = (int)$user['id'];
$salt = Random::alnum();
$encrypted = $this->auth->getEncryptPassword($newPassword, $salt);
Db::startTrans();
try {
Db::name('user')->where('id', $uid)->update([
'password' => $encrypted,
'salt' => $salt,
'loginfailure' => 0,
'updatetime' => time(),
]);
AccountSecurity::ensure($uid);
Db::name('user_security')->where('user_id', $uid)->update([
'failed_attempts' => 0,
'locked_until' => 0,
]);
Token::clear($uid);
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
$this->error('密码重置失败,请稍后重试');
return;
}
$this->success('登录密码重置成功,请使用新密码登录');
}
/**
* 我的信息(含角色与师傅状态)
*/

查看文件

@@ -8,6 +8,7 @@ use app\common\library\FinishImageUrls;
use app\common\library\OrderStatus;
use app\common\library\OrderQualification;
use app\common\library\PaymentService;
use app\common\library\SmsService;
use app\common\library\TiandituService;
use app\common\library\TencentVerifyService;
use app\common\library\WxPayV3Service;
@@ -1088,12 +1089,20 @@ class Master extends MasterBase
$order = $this->ownOrder((int)$this->request->post('order_id'));
$images = FinishImageUrls::normalize((array)$this->request->post('images/a', []));
$damage = trim((string)$this->request->post('damage_remark', ''));
$code = trim((string)($order['verify_code'] ?? ''));
if ($code === '') {
$code = str_pad((string)mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
}
Db::startTrans();
try {
$this->transit($order, OrderStatus::PENDING_VERIFY, '师傅完工,等待客户验收', [
$transitExtra = [
'finish_time' => time(),
], 'master', (int)$order['master_id']);
];
if ((string)($order['verify_code'] ?? '') === '') {
$transitExtra['verify_code'] = $code;
}
$order = $this->transit($order, OrderStatus::PENDING_VERIFY, '师傅完工,等待客户验收', $transitExtra, 'master', (int)$order['master_id']);
foreach ($images as $url) {
if (!$url) {
@@ -1116,9 +1125,15 @@ class Master extends MasterBase
$this->error('提交失败:' . $e->getMessage());
}
$code = (string)$order['verify_code'];
$this->notify('user', (int)$order['user_id'], '师傅已完工,待您验收', '验收码:' . $code . ',请核对后确认完成', 'order', (int)$order['id']);
$this->success('已提交完工,等待客户验收');
$smsResult = SmsService::sendOrderVerifyCode($order);
$tip = $smsResult['sent']
? '已提交完工,验收核销码已通过短信与消息通知客户'
: '已提交完工,等待客户验收';
$this->success($tip, [
'sms_sent' => (bool)$smsResult['sent'],
'sms_mobile_mask' => (string)$smsResult['mobile_mask'],
]);
}
/**

查看文件

@@ -4,7 +4,9 @@ namespace app\api\controller;
use app\common\library\MasterSecurity;
use app\common\library\MasterToken;
use app\common\library\SmsService;
use app\common\library\WxLogin;
use fast\Random;
use think\Db;
/**
@@ -12,7 +14,7 @@ use think\Db;
*/
class MasterAuth extends MasterBase
{
protected $noNeedLogin = ['login', 'wxPhoneLogin'];
protected $noNeedLogin = ['login', 'wxPhoneLogin', 'sendResetPasswordSms', 'resetPasswordBySms'];
/**
* 师傅手机号 + 密码登录(H5调试/账号密码通道)
@@ -173,7 +175,129 @@ class MasterAuth extends MasterBase
}
/**
* 设置或修改师傅登录密码(未设置时直接设置,已设置时需校验原密码)
* 发送师傅端忘记登录密码短信验证码
* @ApiMethod (POST)
*/
public function sendResetPasswordSms()
{
try {
$mobile = SmsService::normalizeMobile((string)$this->request->post('mobile', ''));
} catch (\InvalidArgumentException $e) {
$this->error($e->getMessage());
return;
}
$master = Db::name('master')->field('id,status')->where('mobile', $mobile)->find();
if (!$master) {
$this->error('该手机号尚未注册师傅账号');
return;
}
if (isset($master['status']) && $master['status'] !== 'normal') {
$this->error('师傅账号已被禁用');
return;
}
try {
$res = SmsService::sendVerifyCode($mobile, 'master_resetpwd', $this->request->ip());
$this->success('验证码已发送,请注意查收', array_merge($res, [
'mobile' => substr_replace($mobile, '****', 3, 4),
]));
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
}
/**
* 师傅端通过短信验证码重置登录密码(忘记密码)
* @ApiMethod (POST)
*/
public function resetPasswordBySms()
{
try {
$mobile = SmsService::normalizeMobile((string)$this->request->post('mobile', ''));
} catch (\InvalidArgumentException $e) {
$this->error($e->getMessage());
return;
}
$smsCode = trim((string)$this->request->post('sms_code', $this->request->post('captcha', '')));
$newPassword = (string)$this->request->post('new_password', '');
if (!preg_match('/^\S{6,30}$/', $newPassword)) {
$this->error('登录密码须为6至30位非空字符');
return;
}
$master = Db::name('master')->field('id,status')->where('mobile', $mobile)->find();
if (!$master) {
$this->error('该手机号尚未注册师傅账号');
return;
}
if (isset($master['status']) && $master['status'] !== 'normal') {
$this->error('师傅账号已被禁用');
return;
}
try {
SmsService::verifyCode($mobile, $smsCode, 'master_resetpwd', true);
} catch (\Throwable $e) {
$this->error($e->getMessage());
return;
}
$mid = (int)$master['id'];
$salt = Random::alnum();
$encrypted = $this->masterAuth->getEncryptPassword($newPassword, $salt);
Db::startTrans();
try {
Db::name('master')->where('id', $mid)->update([
'loginfailure' => 0,
'password' => $encrypted,
'salt' => $salt,
'updatetime' => time(),
]);
MasterSecurity::ensure($mid);
Db::name('master_security')->where('master_id', $mid)->update([
'failed_attempts' => 0,
'locked_until' => 0,
]);
MasterToken::clear($mid);
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
$this->error('密码重置失败,请稍后重试');
return;
}
$this->success('登录密码重置成功,请使用新密码登录');
}
/**
* 发送修改师傅登录密码短信验证码(给当前绑定手机号发送)
* @ApiMethod (POST)
*/
public function sendPasswordSms()
{
$mid = $this->masterId();
$rawMobile = (string)Db::name('master')->where('id', $mid)->value('mobile');
try {
$mobile = SmsService::normalizeMobile($rawMobile);
} catch (\InvalidArgumentException $e) {
$this->error('当前师傅账号尚未绑定有效手机号,无法发送短信验证码');
return;
}
try {
$res = SmsService::sendVerifyCode($mobile, 'master_changepwd', $this->request->ip());
$this->success('验证码已发送至绑定手机', array_merge($res, [
'mobile' => substr_replace($mobile, '****', 3, 4),
]));
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
}
/**
* 设置或修改师傅登录密码(支持原密码校验与绑定手机短信验证码校验)
* @ApiMethod (POST)
*/
public function changeLoginPassword()
@@ -181,18 +305,29 @@ class MasterAuth extends MasterBase
$mid = $this->masterId();
$new = (string)$this->request->post('new_password', '');
$old = (string)$this->request->post('old_password', '');
$smsCode = trim((string)$this->request->post('sms_code', ''));
$verifyMode = trim((string)$this->request->post('verify_mode', $smsCode !== '' ? 'sms' : 'old_password'));
if (!preg_match('/^\S{6,30}$/', $new)) {
$this->error('登录密码须为6至30位非空字符');
}
$master = Db::name('master')->field('password')->where('id', $mid)->find();
$master = Db::name('master')->field('password,mobile')->where('id', $mid)->find();
if (!empty($master['password'])) {
try {
MasterSecurity::verify($mid, 'login', $old);
} catch (\Throwable $e) {
$this->error($e->getMessage());
if ($verifyMode === 'sms') {
try {
SmsService::verifyCode((string)($master['mobile'] ?? ''), $smsCode, 'master_changepwd', true);
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
$ignoreOld = true;
} else {
try {
MasterSecurity::verify($mid, 'login', $old);
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
$ignoreOld = false;
}
$ignoreOld = false;
} else {
$ignoreOld = true;
}
@@ -233,7 +368,32 @@ class MasterAuth extends MasterBase
}
/**
* 修改师傅支付密码(需校验原支付密码)
* 发送修改/重置师傅支付密码短信验证码(给当前绑定手机号发送)
* @ApiMethod (POST)
*/
public function sendPaymentPasswordSms()
{
$mid = $this->masterId();
$rawMobile = (string)Db::name('master')->where('id', $mid)->value('mobile');
try {
$mobile = SmsService::normalizeMobile($rawMobile);
} catch (\InvalidArgumentException $e) {
$this->error('当前师傅账号尚未绑定有效手机号,无法发送短信验证码');
return;
}
try {
$res = SmsService::sendVerifyCode($mobile, 'master_paypwd', $this->request->ip());
$this->success('验证码已发送至绑定手机', array_merge($res, [
'mobile' => substr_replace($mobile, '****', 3, 4),
]));
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
}
/**
* 修改师傅支付密码(支持原支付密码校验与绑定手机短信验证码校验)
* @ApiMethod (POST)
*/
public function changePaymentPassword()
@@ -243,16 +403,35 @@ class MasterAuth extends MasterBase
if (!preg_match('/^\d{6}$/', $new)) {
$this->error('支付密码须为6位数字');
}
MasterSecurity::ensure($mid);
$oldHash = (string)Db::name('master_security')->where('master_id', $mid)->value('payment_password_hash');
try {
MasterSecurity::verify($mid, 'payment', (string)$this->request->post('old_password', ''));
} catch (\Throwable $e) {
$this->error($e->getMessage());
if ($oldHash === '') {
$this->error('尚未设置支付密码,请先设置支付密码');
}
$smsCode = trim((string)$this->request->post('sms_code', ''));
$verifyMode = trim((string)$this->request->post('verify_mode', $smsCode !== '' ? 'sms' : 'old_password'));
if ($verifyMode === 'sms') {
$mobile = (string)Db::name('master')->where('id', $mid)->value('mobile');
try {
SmsService::verifyCode($mobile, $smsCode, 'master_paypwd', true);
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
} else {
try {
MasterSecurity::verify($mid, 'payment', (string)$this->request->post('old_password', ''));
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
}
$updated = Db::name('master_security')
->where('master_id', $mid)
->where('payment_password_hash', $oldHash)
->update(['payment_password_hash' => password_hash($new, PASSWORD_DEFAULT)]);
->update([
'payment_password_hash' => password_hash($new, PASSWORD_DEFAULT),
'payment_failed_attempts' => 0,
'payment_locked_until' => 0,
]);
if (!$updated) {
$this->error('支付密码已变更,请重新操作');
}

查看文件

@@ -2,6 +2,7 @@
namespace app\api\controller;
use app\common\library\AccountSecurity;
use app\common\library\SmsService;
use app\common\library\WxLogin;
use app\common\library\TencentVerifyService;
use app\common\library\EnterpriseLicenseImage;
@@ -14,27 +15,70 @@ class Security extends Base
$user = Db::name('user')->field('password,mobile')->where('id', $this->uid())->find();
$security = Db::name('user_security')->where('user_id', $this->uid())->find();
$cert = Db::name('user_enterprise_cert')->where('user_id', $this->uid())->find();
$rawMobile = trim((string)($user['mobile'] ?? ''));
$maskedMobile = strlen($rawMobile) === 11
? (substr($rawMobile, 0, 3) . '****' . substr($rawMobile, -4))
: $rawMobile;
$this->success('', [
'has_login_password' => !empty($user['password']),
'has_payment_password' => $security && $security['payment_password_hash'] !== '',
'mobile' => $maskedMobile,
'enterprise_cert' => $cert ?: null,
]);
}
/**
* 发送修改登录密码短信验证码(给当前登录账号绑定的手机号发送)
* @ApiMethod (POST)
*/
public function sendPasswordSms()
{
$uid = $this->uid();
$rawMobile = (string)Db::name('user')->where('id', $uid)->value('mobile');
try {
$mobile = SmsService::normalizeMobile($rawMobile);
} catch (\InvalidArgumentException $e) {
$this->error('当前账号尚未绑定有效手机号,无法发送短信验证码');
return;
}
try {
$res = SmsService::sendVerifyCode($mobile, 'user_changepwd', $this->request->ip());
$this->success('验证码已发送至绑定手机', array_merge($res, [
'mobile' => substr_replace($mobile, '****', 3, 4),
]));
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
}
public function changeLoginPassword()
{
$uid = $this->uid();
$new = (string)$this->request->post('new_password', '');
$old = (string)$this->request->post('old_password', '');
$smsCode = trim((string)$this->request->post('sms_code', ''));
$verifyMode = trim((string)$this->request->post('verify_mode', $smsCode !== '' ? 'sms' : 'old_password'));
if (!preg_match('/^\S{6,30}$/', $new)) $this->error('登录密码须为6至30位非空字符');
$user = Db::name('user')->field('password')->where('id', $uid)->find();
$user = Db::name('user')->field('password,mobile')->where('id', $uid)->find();
if (!empty($user['password'])) {
try { AccountSecurity::verify($uid, 'login', $old); } catch (\Throwable $e) { $this->error($e->getMessage()); }
$ignoreOld = false;
if ($verifyMode === 'sms') {
try {
SmsService::verifyCode((string)($user['mobile'] ?? ''), $smsCode, 'user_changepwd', true);
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
$ignoreOld = true;
} else {
try { AccountSecurity::verify($uid, 'login', $old); } catch (\Throwable $e) { $this->error($e->getMessage()); }
$ignoreOld = false;
}
} else {
$ignoreOld = true;
}
if (!$this->auth->changepwd($new, $old, $ignoreOld)) $this->error($this->auth->getError() ?: '设置失败');
AccountSecurity::ensure($uid);
Db::name('user_security')->where('user_id', $uid)->update(['failed_attempts' => 0, 'locked_until' => 0]);
\app\common\library\Token::clear($uid);
$this->success('登录密码已更新,请重新登录');
}
@@ -50,15 +94,59 @@ class Security extends Base
$this->success('支付密码设置成功');
}
/**
* 发送修改/重置支付密码短信验证码(给当前登录账号绑定的手机号发送)
* @ApiMethod (POST)
*/
public function sendPaymentPasswordSms()
{
$uid = $this->uid();
$rawMobile = (string)Db::name('user')->where('id', $uid)->value('mobile');
try {
$mobile = SmsService::normalizeMobile($rawMobile);
} catch (\InvalidArgumentException $e) {
$this->error('当前账号尚未绑定有效手机号,无法发送短信验证码');
return;
}
try {
$res = SmsService::sendVerifyCode($mobile, 'user_paypwd', $this->request->ip());
$this->success('验证码已发送至绑定手机', array_merge($res, [
'mobile' => substr_replace($mobile, '****', 3, 4),
]));
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
}
public function changePaymentPassword()
{
$uid = $this->uid();
$new = (string)$this->request->post('new_password', '');
if (!preg_match('/^\d{6}$/', $new)) $this->error('支付密码须为6位数字');
AccountSecurity::ensure($uid);
$oldHash = (string)Db::name('user_security')->where('user_id', $uid)->value('payment_password_hash');
try { AccountSecurity::verify($uid, 'payment', (string)$this->request->post('old_password', '')); }
catch (\Throwable $e) { $this->error($e->getMessage()); }
$updated = Db::name('user_security')->where('user_id', $uid)->where('payment_password_hash', $oldHash)->update(['payment_password_hash' => password_hash($new, PASSWORD_DEFAULT)]);
if ($oldHash === '') {
$this->error('尚未设置支付密码,请先设置支付密码');
}
$smsCode = trim((string)$this->request->post('sms_code', ''));
$verifyMode = trim((string)$this->request->post('verify_mode', $smsCode !== '' ? 'sms' : 'old_password'));
if ($verifyMode === 'sms') {
$mobile = (string)Db::name('user')->where('id', $uid)->value('mobile');
try {
SmsService::verifyCode($mobile, $smsCode, 'user_paypwd', true);
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
} else {
try { AccountSecurity::verify($uid, 'payment', (string)$this->request->post('old_password', '')); }
catch (\Throwable $e) { $this->error($e->getMessage()); }
}
$updated = Db::name('user_security')->where('user_id', $uid)->where('payment_password_hash', $oldHash)->update([
'payment_password_hash' => password_hash($new, PASSWORD_DEFAULT),
'payment_failed_attempts' => 0,
'payment_locked_until' => 0,
]);
if (!$updated) $this->error('支付密码已变更,请重新操作');
$this->success('支付密码修改成功');
}

查看文件

@@ -3,9 +3,12 @@
namespace app\api\controller;
use app\common\controller\Api;
use app\common\library\MasterAuth;
use app\common\library\SmsService;
use think\Db;
/**
* 手机短信接口(短信验证码通道已下线)
* 手机短信接口
*/
class Sms extends Api
{
@@ -13,20 +16,101 @@ class Sms extends Api
protected $noNeedRight = '*';
/**
* 发送验证码(已移除)
* 发送短信验证码
* @ApiMethod (POST)
* @ApiParams (name="mobile", type="string", required=true, description="手机号")
* @ApiParams (name="event", type="string", required=true, description="事件名称")
*/
public function send()
{
$this->error('短信验证码通道已移除,请使用手机号密码或微信一键登录');
$rawMobile = (string)$this->request->post('mobile', '');
$event = trim((string)$this->request->post('event', ''));
if ($event === '') {
$event = 'user_resetpwd';
}
try {
$mobile = SmsService::normalizeMobile($rawMobile);
} catch (\InvalidArgumentException $e) {
$this->error($e->getMessage());
return;
}
if (!in_array($event, SmsService::ALLOWED_EVENTS, true)) {
$this->error('不支持的短信验证码类型');
return;
}
if (in_array($event, ['changepwd', 'user_changepwd', 'paypwd', 'user_paypwd'], true)) {
if (!$this->auth->isLogin()) {
$this->error(__('Please login first'), null, 401);
return;
}
$user = $this->auth->getUser();
if (!$user || (string)$user['mobile'] !== $mobile) {
$this->error('仅支持向当前账号绑定的手机号发送验证码');
return;
}
} elseif (in_array($event, ['master_changepwd', 'master_paypwd'], true)) {
$token = $this->request->server('HTTP_TOKEN', $this->request->request('token', ''));
$masterAuth = MasterAuth::instance();
if (!$token || !$masterAuth->init($token)) {
$this->error(__('Please login first'), null, 401);
return;
}
$master = $masterAuth->getMaster();
if (!$master || (string)$master['mobile'] !== $mobile) {
$this->error('仅支持向当前师傅账号绑定的手机号发送验证码');
return;
}
} elseif (in_array($event, ['resetpwd', 'user_resetpwd'], true)) {
$user = Db::name('user')->field('id,status')->where('mobile', $mobile)->find();
if (!$user) {
$this->error('该手机号尚未注册账号');
return;
}
if (isset($user['status']) && $user['status'] !== 'normal') {
$this->error('账号已被禁用');
return;
}
} elseif ($event === 'master_resetpwd') {
$master = Db::name('master')->field('id,status')->where('mobile', $mobile)->find();
if (!$master) {
$this->error('该手机号尚未注册师傅账号');
return;
}
if (isset($master['status']) && $master['status'] !== 'normal') {
$this->error('师傅账号已被禁用');
return;
}
}
try {
$res = SmsService::sendVerifyCode($mobile, $event, $this->request->ip());
$this->success('验证码已发送,请注意查收', $res);
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
}
/**
* 检测验证码(已移除)
* 检测短信验证码(不消耗验证码,仅预校验)
* @ApiMethod (POST)
*/
public function check()
{
$this->error('短信验证码通道已移除,请使用手机号密码或微信一键登录');
$rawMobile = (string)$this->request->post('mobile', '');
$event = trim((string)$this->request->post('event', ''));
$captcha = trim((string)$this->request->post('captcha', $this->request->post('sms_code', '')));
if ($event === '') {
$event = 'user_resetpwd';
}
try {
SmsService::verifyCode($rawMobile, $captcha, $event, false);
$this->success('验证码正确');
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
}
}

查看文件

@@ -16,7 +16,7 @@ class Sms
* 验证码有效时长
* @var int
*/
protected static $expire = 120;
protected static $expire = 300;
/**
* 最大允许检测的次数
@@ -24,6 +24,39 @@ class Sms
*/
protected static $maxCheckNums = 10;
/**
* 最近一次发送失败原因
* @var mixed
*/
protected static $lastError = '';
/**
* 获取最近一次发送失败原因
* @return mixed
*/
public static function getLastError()
{
return self::$lastError;
}
/**
* 从短信插件提取错误信息
*/
protected static function captureAddonError()
{
self::$lastError = '';
try {
if (function_exists('get_addon_instance')) {
$addon = get_addon_instance('qcloudsms');
if ($addon && method_exists($addon, 'getError')) {
self::$lastError = $addon->getError();
}
}
} catch (\Throwable $e) {
self::$lastError = $e->getMessage();
}
}
/**
* 获取最后一次手机发送的数据
*
@@ -50,12 +83,14 @@ class Sms
*/
public static function send($mobile, $code = null, $event = 'default')
{
self::$lastError = '';
$code = is_null($code) ? Random::numeric(config('fastadmin.sms_captcha_length') ?: 6) : $code;
$time = time();
$ip = request()->ip();
$sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
$result = Hook::listen('sms_send', $sms, null, true);
if (!$result) {
self::captureAddonError();
$sms->delete();
return false;
}
@@ -65,19 +100,27 @@ class Sms
/**
* 发送通知
*
* @param mixed $mobile 手机号,多个以,分隔
* @param string $msg 消息内容
* @param string $template 消息模板
* @param mixed $mobile 手机号,多个以,分隔
* @param string $msg 消息内容
* @param string $template 消息模板
* @param array $templateParams 模板参数列表
* @return boolean
*/
public static function notice($mobile, $msg = '', $template = null)
public static function notice($mobile, $msg = '', $template = null, array $templateParams = [])
{
self::$lastError = '';
$params = [
'mobile' => $mobile,
'msg' => $msg,
'template' => $template
'template' => $template,
];
if (!empty($templateParams)) {
$params['params'] = array_values($templateParams);
}
$result = Hook::listen('sms_notice', $params, null, true);
if (!$result) {
self::captureAddonError();
}
return (bool)$result;
}
@@ -137,7 +180,7 @@ class Sms
->setInc('times');
// 验证码不匹配
if ($code != $sms['code']) {
if (!hash_equals((string)$sms['code'], (string)$code)) {
Db::commit(); // 提交次数增加
return false;
}

查看文件

@@ -0,0 +1,194 @@
<?php
namespace app\common\library;
use think\Db;
use think\Log;
/**
* 统一业务短信服务:频次限流、密码验证码发送/校验、完工核销码短信下发
*/
class SmsService
{
const COOLDOWN_SECONDS = 60;
const MAX_DAILY_PER_MOBILE = 10;
const MAX_HOURLY_PER_IP = 20;
const ALLOWED_EVENTS = [
'user_changepwd',
'user_resetpwd',
'user_paypwd',
'master_changepwd',
'master_resetpwd',
'master_paypwd',
'changepwd',
'resetpwd',
'paypwd',
];
/**
* 规范化并校验中国大陆 11 位手机号
*/
public static function normalizeMobile($mobile)
{
$mobile = preg_replace('/[^\d]/', '', trim((string)$mobile));
if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
throw new \InvalidArgumentException('手机号格式不正确');
}
return $mobile;
}
/**
* 校验发送频次限制并发送 6 位数字短信验证码
*
* @param string $mobile 手机号
* @param string $event 事件标识
* @param string $ip 请求 IP
* @return array ['cooldown' => int, 'expire_seconds' => int]
*/
public static function sendVerifyCode($mobile, $event, $ip = '')
{
$mobile = self::normalizeMobile($mobile);
$event = trim((string)$event);
if (!in_array($event, self::ALLOWED_EVENTS, true)) {
throw new \InvalidArgumentException('不支持的短信事件类型');
}
$now = time();
$last = Sms::get($mobile, $event);
if ($last) {
$elapsed = $now - (int)$last['createtime'];
if ($elapsed < self::COOLDOWN_SECONDS) {
$wait = self::COOLDOWN_SECONDS - $elapsed;
throw new \RuntimeException("发送过于频繁,请 {$wait} 秒后再试");
}
}
$dayCount = (int)\app\common\model\Sms::where('mobile', $mobile)
->where('createtime', '>=', $now - 86400)
->count();
if ($dayCount >= self::MAX_DAILY_PER_MOBILE) {
throw new \RuntimeException('该手机号今日短信发送次数已达上限,请明天再试');
}
if ($ip !== '') {
$ipCount = (int)\app\common\model\Sms::where('ip', $ip)
->where('createtime', '>=', $now - 3600)
->count();
if ($ipCount >= self::MAX_HOURLY_PER_IP) {
throw new \RuntimeException('当前网络请求验证码过于频繁,请稍后再试');
}
}
$sent = Sms::send($mobile, null, $event);
if (!$sent) {
$errMsg = self::formatAddonError(Sms::getLastError());
throw new \RuntimeException($errMsg);
}
return [
'cooldown' => self::COOLDOWN_SECONDS,
'expire_seconds' => 300,
];
}
/**
* 校验短信验证码(默认校验成功后立即失效,防重放)
*/
public static function verifyCode($mobile, $code, $event, $flush = true)
{
$mobile = self::normalizeMobile($mobile);
$code = trim((string)$code);
if (!preg_match('/^\d{4,6}$/', $code)) {
throw new \InvalidArgumentException('请输入有效的短信验证码');
}
$event = trim((string)$event);
if (!in_array($event, self::ALLOWED_EVENTS, true)) {
throw new \InvalidArgumentException('不支持的短信事件类型');
}
if (!Sms::check($mobile, $code, $event, $flush)) {
throw new \RuntimeException('短信验证码不正确或已过期');
}
return true;
}
/**
* 师傅完工后向订单客户联系手机下发 6 位验收核销码短信
* 注意:绝不向调用方/师傅端暴露或抛出异常阻断完工主流程
*
* @param array $order 订单记录
* @return array ['sent' => bool, 'mobile_mask' => string, 'reason' => string]
*/
public static function sendOrderVerifyCode(array $order)
{
$orderId = (int)($order['id'] ?? 0);
$code = trim((string)($order['verify_code'] ?? ''));
if ($code === '') {
return ['sent' => false, 'mobile_mask' => '', 'reason' => '核销码为空'];
}
// 优先发送到订单客户联系手机(order.mobile),异常或空时兜底取下单账号手机
$targetMobile = preg_replace('/[^\d]/', '', trim((string)($order['mobile'] ?? '')));
if (!preg_match('/^1[3-9]\d{9}$/', $targetMobile) && !empty($order['user_id'])) {
$userMobile = (string)Db::name('user')->where('id', (int)$order['user_id'])->value('mobile');
$targetMobile = preg_replace('/[^\d]/', '', trim($userMobile));
}
if (!preg_match('/^1[3-9]\d{9}$/', $targetMobile)) {
Log::warning("[SmsService::sendOrderVerifyCode] 订单#{$orderId} 缺少有效客户手机号,跳过核销码短信下发");
return ['sent' => false, 'mobile_mask' => '', 'reason' => '客户手机号无效'];
}
$maskedMobile = substr_replace($targetMobile, '****', 3, 4);
try {
$sent = Sms::notice($targetMobile, $code, 'order_verify', [$code]);
if (!$sent) {
$reason = self::formatAddonError(Sms::getLastError());
Log::warning("[SmsService::sendOrderVerifyCode] 订单#{$orderId} 下发核销码短信失败 mobile={$maskedMobile} reason={$reason}");
return ['sent' => false, 'mobile_mask' => $maskedMobile, 'reason' => $reason];
}
Log::info("[SmsService::sendOrderVerifyCode] 订单#{$orderId} 已向客户 {$maskedMobile} 下发核销码短信");
return ['sent' => true, 'mobile_mask' => $maskedMobile, 'reason' => ''];
} catch (\Throwable $e) {
Log::error("[SmsService::sendOrderVerifyCode] 订单#{$orderId} 下发核销码短信异常: " . $e->getMessage());
return ['sent' => false, 'mobile_mask' => $maskedMobile, 'reason' => '短信发送异常'];
}
}
/**
* 将插件底层错误格式化为可读提示(脱敏不透传英文协议与密钥等内部细节)
*/
public static function formatAddonError($rawError)
{
if (is_string($rawError) && $rawError !== '') {
if (strpos($rawError, '未配置') !== false) {
return '短信服务尚未配置完成,请联系平台管理员';
}
if (preg_match('/[\x{4e00}-\x{9fa5}]/u', $rawError) && !preg_match('/[A-Za-z]{4,}/', $rawError)) {
return $rawError;
}
return '短信发送失败,请稍后重试';
}
if (is_array($rawError)) {
$code = (int)($rawError['result'] ?? 0);
if ($code === 1014) {
return '短信模板审核中或未生效,请稍后再试';
}
if (in_array($code, [1013, 1022, 1023, 1024, 1025], true)) {
return '验证码发送过于频繁,请稍后再试';
}
if ($code === 1016) {
return '手机号格式不正确,请核对后重试';
}
if ($code === -1 || $code === -2) {
return '短信通道连接超时,请稍后重试';
}
if ($code > 0) {
return '短信服务暂不可用,请稍后重试或联系客服';
}
}
return '短信发送失败,请稍后重试或联系客服';
}
}

查看文件

@@ -32,6 +32,22 @@ return array (
array (
0 => 'epay',
),
'config_init' =>
array (
0 => 'qcloudsms',
),
'sms_send' =>
array (
0 => 'qcloudsms',
),
'sms_notice' =>
array (
0 => 'qcloudsms',
),
'sms_check' =>
array (
0 => 'qcloudsms',
),
),
'route' =>
array (

查看文件

@@ -4,7 +4,7 @@ return array (
'name' => '优匠优服',
'beian' => '',
'cdnurl' => '',
'version' => '1.0.100',
'version' => '1.0.102',
'timezone' => 'Asia/Shanghai',
'forbiddenip' => '',
'languages' =>