From c664d0a5ded6fb70b7b81799822f60051a893b4c Mon Sep 17 00:00:00 2001 From: MiAn Date: Thu, 26 Nov 2026 15:54:15 +0800 Subject: [PATCH] =?UTF-8?q?feat(sms):=20=E9=9B=86=E6=88=90=E8=85=BE?= =?UTF-8?q?=E8=AE=AF=E4=BA=91=E7=9F=AD=E4=BF=A1=E6=8F=92=E4=BB=B6=E5=B9=B6?= =?UTF-8?q?=E6=89=93=E9=80=9A=E5=8F=8C=E7=AB=AF=E7=9F=AD=E4=BF=A1=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E7=A0=81=E4=B8=9A=E5=8A=A1=E9=93=BE=E8=B7=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 插件管理:集成 qcloudsms 腾讯云短信发送插件,配置应用AppID/AppKey、短信签名及各业务模板ID(登录、修改密码、重置密码、支付密码、订单核销通知) - 业务封装:新增 SmsService 统一业务短信服务,实现防刷限流、冷却控制、短信验证码发送与防重放校验,支持完工订单自动下发客户核销码 - 接口层:恢复并升级 Sms 控制器,并在 Auth/MasterAuth/Security 控制器中支持手机验证码登录、找回登录密码及短信验证设置/修改支付密码 - 小程序端:用户端与师傅端登录页、账号安全中心、支付密码组件全面适配短信验证码交互,优化用户找回密码与支付密码安全操作流程 - 部署脚本:优化 deploy_all.py 打包剪枝逻辑,全局过滤深层 .git 目录并规范打包相对路径 --- scratch/deploy_all.py | 13 +- server/addons/qcloudsms/.addonrc | 1 + server/addons/qcloudsms/Qcloudsms.php | 268 +++++++++ server/addons/qcloudsms/config.php | 167 ++++++ server/addons/qcloudsms/controller/Index.php | 15 + server/addons/qcloudsms/info.ini | 10 + .../qcloudsms/library/FileVoiceSender.php | 69 +++ .../library/SmsMobileStatusPuller.php | 91 +++ .../qcloudsms/library/SmsMultiSender.php | 99 ++++ .../qcloudsms/library/SmsSenderUtil.php | 211 +++++++ .../qcloudsms/library/SmsSingleSender.php | 107 ++++ .../qcloudsms/library/SmsStatusPuller.php | 75 +++ .../library/SmsVoicePromptSender.php | 71 +++ .../library/SmsVoiceVerifyCodeSender.php | 67 +++ .../qcloudsms/library/TtsVoiceSender.php | 77 +++ server/application/api/controller/Auth.php | 104 +++- server/application/api/controller/Master.php | 23 +- .../application/api/controller/MasterAuth.php | 207 ++++++- .../application/api/controller/Security.php | 100 +++- server/application/api/controller/Sms.php | 94 ++- server/application/common/library/Sms.php | 57 +- .../application/common/library/SmsService.php | 194 +++++++ server/application/extra/addons.php | 16 + server/application/extra/site.php | 2 +- tests/sms_business_api.js | 311 ++++++++++ yjyf-app/components/YjyfPaymentPassword.vue | 191 +++++- yjyf-app/pages/login/login.vue | 278 +++++++++ yjyf-app/pages/mine/security.vue | 546 ++++++++++++++++-- yjyf-app/utils/api.js | 4 + .../components/YjyfPaymentPassword.vue | 191 +++++- yjyf-master-app/pages/login/login.vue | 277 +++++++++ yjyf-master-app/pages/master/detail.vue | 9 +- yjyf-master-app/pages/master/security.vue | 234 +++++++- yjyf-master-app/utils/api.js | 4 + 34 files changed, 4023 insertions(+), 160 deletions(-) create mode 100644 server/addons/qcloudsms/.addonrc create mode 100644 server/addons/qcloudsms/Qcloudsms.php create mode 100644 server/addons/qcloudsms/config.php create mode 100644 server/addons/qcloudsms/controller/Index.php create mode 100644 server/addons/qcloudsms/info.ini create mode 100644 server/addons/qcloudsms/library/FileVoiceSender.php create mode 100644 server/addons/qcloudsms/library/SmsMobileStatusPuller.php create mode 100644 server/addons/qcloudsms/library/SmsMultiSender.php create mode 100644 server/addons/qcloudsms/library/SmsSenderUtil.php create mode 100644 server/addons/qcloudsms/library/SmsSingleSender.php create mode 100644 server/addons/qcloudsms/library/SmsStatusPuller.php create mode 100644 server/addons/qcloudsms/library/SmsVoicePromptSender.php create mode 100644 server/addons/qcloudsms/library/SmsVoiceVerifyCodeSender.php create mode 100644 server/addons/qcloudsms/library/TtsVoiceSender.php create mode 100644 server/application/common/library/SmsService.php create mode 100644 tests/sms_business_api.js diff --git a/scratch/deploy_all.py b/scratch/deploy_all.py index 4b82de5..86f0c68 100644 --- a/scratch/deploy_all.py +++ b/scratch/deploy_all.py @@ -52,24 +52,19 @@ else: # 2. 本地项目代码打包 print("\n[步骤 2] 打包本地 server 目录...") -exclude_prefixes = [ - os.path.join(LOCAL_SERVER_DIR, 'runtime'), - os.path.join(LOCAL_SERVER_DIR, '.git'), - os.path.join(LOCAL_SERVER_DIR, '.idea'), - os.path.join(LOCAL_SERVER_DIR, '.vscode') -] +exclude_dir_names = {'.git', 'runtime', '.idea', '.vscode', 'temp'} exclude_files = {'.env', 'composer.phar'} file_count = 0 with tarfile.open(LOCAL_TAR_PATH, 'w:gz') as tar: for root, dirs, files in os.walk(LOCAL_SERVER_DIR): - if any(root.startswith(p) for p in exclude_prefixes): - continue + # 深度剪枝:跳过任何匹配的目录(包括子模块的 .git) + dirs[:] = [d for d in dirs if d not in exclude_dir_names] for file in files: if file in exclude_files or file.endswith('.log') or file.endswith('.tmp'): continue full_path = os.path.join(root, file) - rel_path = os.path.relpath(full_path, LOCAL_SERVER_DIR) + rel_path = os.path.relpath(full_path, LOCAL_SERVER_DIR).replace('\\', '/') tar.add(full_path, arcname=rel_path) file_count += 1 diff --git a/server/addons/qcloudsms/.addonrc b/server/addons/qcloudsms/.addonrc new file mode 100644 index 0000000..86a294a --- /dev/null +++ b/server/addons/qcloudsms/.addonrc @@ -0,0 +1 @@ +{"files":[],"license":"regular","licenseto":"26425","licensekey":"5pvTcWsdGoDjySkX VRNhbP5\/jKOJCVaFLkuPgjkDZjZaTOCqIprTZjv6q4U=","domains":["yjyf"],"licensecodes":[],"validations":["4dceabe25bd363f318cc03da6a62d391"]} \ No newline at end of file diff --git a/server/addons/qcloudsms/Qcloudsms.php b/server/addons/qcloudsms/Qcloudsms.php new file mode 100644 index 0000000..8349630 --- /dev/null +++ b/server/addons/qcloudsms/Qcloudsms.php @@ -0,0 +1,268 @@ +config = $this->getConfig(); + //如果使用语音短信 更换成语音短信模板 + if (!empty($this->config['isVoice']) && (int)$this->config['isVoice'] === 1) { + $this->config['template'] = $this->config['voiceTemplate'] ?? []; + //语音短信 需要另行设置Aappid 与Appkey + $this->appid = trim((string)($this->config['voiceAppid'] ?? '')); + $this->appkey = trim((string)($this->config['voiceAppkey'] ?? '')); + } else { + $this->appid = trim((string)($this->config['appid'] ?? '')); + $this->appkey = trim((string)($this->config['appkey'] ?? '')); + } + } + + /** + * 解析事件对应的短信模板 ID(支持跨端事件映射与兜底回退) + */ + private function resolveTemplateId($event, $fallbackKey = '') + { + $templates = is_array($this->config['template'] ?? null) ? $this->config['template'] : []; + $candidates = [(string)$event]; + $eventMap = [ + 'user_changepwd' => ['changepwd'], + 'master_changepwd' => ['changepwd'], + 'user_resetpwd' => ['resetpwd'], + 'master_resetpwd' => ['resetpwd'], + 'user_paypwd' => ['paypwd', 'changepwd'], + 'master_paypwd' => ['paypwd', 'changepwd'], + ]; + if (isset($eventMap[$event])) { + foreach ($eventMap[$event] as $mappedKey) { + $candidates[] = $mappedKey; + } + } + if ($fallbackKey !== '') { + $candidates[] = $fallbackKey; + } + foreach ($candidates as $key) { + if ($key !== '' && !empty($templates[$key])) { + return trim((string)$templates[$key]); + } + } + return ''; + } + + /** + * 短信发送行为 + * @param Sms $params + * @return boolean + */ + public function smsSend(&$params) + { + $this->ConfigInit(); + $this->setError(''); + if ($this->appid === '' || $this->appkey === '') { + $this->setError('腾讯云短信应用 AppID 或 AppKey 未配置'); + return false; + } + try { + $event = (string)($params['event'] ?? $params->event ?? ''); + $mobile = (string)($params['mobile'] ?? $params->mobile ?? ''); + $code = (string)($params['code'] ?? $params->code ?? ''); + + if (!empty($this->config['isTemplateSender']) && (int)$this->config['isTemplateSender'] === 1) { + $templateID = $this->resolveTemplateId($event); + if ($templateID === '') { + $this->setError('腾讯云短信模板 ID(' . $event . ')未配置'); + return false; + } + if ((int)($this->config['isVoice'] ?? 0) !== 1) { + //普通短信发送 + $sign = trim((string)($this->config['sign'] ?? '')); + if ($sign === 'your sign') { + $sign = ''; + } + $this->sender = new SmsSingleSender($this->appid, $this->appkey); + $result = $this->sender->sendWithParam("86", $mobile, (int)$templateID, ["{$code}"], $sign, "", ""); + } else { + //语音短信发送 + $this->sender = new TtsVoiceSender($this->appid, $this->appkey); + //参数: 国家码,手机号、模板ID、模板参数、播放次数(可选字段)、用户的session内容,服务器端原样返回(可选字段) + $result = $this->sender->send("86", $mobile, (int)$templateID, [$code]); + } + } else { + //判断是否是语音短信 + $msg = (string)($params['msg'] ?? $code); + if ((int)($this->config['isVoice'] ?? 0) !== 1) { + $this->sender = new SmsSingleSender($this->appid, $this->appkey); + //参数:短信类型{1营销短信,0普通短信 }、国家码、手机号、短信内容、扩展码(可留空)、服务的原样返回的参数 + $result = $this->sender->send((int)($params['type'] ?? 0), '86', $mobile, $msg, "", ""); + } else { + $this->sender = new SmsVoiceVerifyCodeSender($this->appid, $this->appkey); + //参数:国家码、手机号、短信内容、播放次数(默认2次)、服务的原样返回的参数 + $result = $this->sender->send('86', $mobile, $msg); + } + } + + $rsp = json_decode((string)$result, true); + if (is_array($rsp) && isset($rsp['result']) && (int)$rsp['result'] === 0 && ($rsp['errmsg'] ?? '') === 'OK') { + return true; + } + $this->setError(is_array($rsp) ? $rsp : (string)$result); + \think\Log::warning('[Qcloudsms::smsSend] 发送失败 mobile=' . substr($mobile, 0, 3) . '****' . substr($mobile, -4) . ' rsp=' . json_encode($rsp, JSON_UNESCAPED_UNICODE)); + return false; + } catch (\Throwable $e) { + $this->setError($e->getMessage()); + \think\Log::error('[Qcloudsms::smsSend] 异常: ' . $e->getMessage()); + } + return false; + } + + /** + * 短信发送通知 + * @param array $params + * @return boolean + */ + public function smsNotice(&$params) + { + $this->ConfigInit(); + $this->setError(''); + if ($this->appid === '' || $this->appkey === '') { + $this->setError('腾讯云短信应用 AppID 或 AppKey 未配置'); + return false; + } + try { + $templateKey = (string)($params['template'] ?? 'notice'); + $mobile = (string)($params['mobile'] ?? ''); + $msg = (string)($params['msg'] ?? ''); + $tplParams = isset($params['params']) && is_array($params['params']) + ? array_values(array_map('strval', $params['params'])) + : [$msg]; + + if (!empty($this->config['isTemplateSender']) && (int)$this->config['isTemplateSender'] === 1) { + $templateID = $this->resolveTemplateId($templateKey, 'notice'); + if ($templateID === '') { + $this->setError('腾讯云通知短信模板 ID(' . $templateKey . ')未配置'); + return false; + } + + if ((int)($this->config['isVoice'] ?? 0) !== 1) { + //普通短信发送 + $sign = trim((string)($this->config['sign'] ?? '')); + if ($sign === 'your sign') { + $sign = ''; + } + $this->sender = new SmsSingleSender($this->appid, $this->appkey); + $result = $this->sender->sendWithParam("86", $mobile, (int)$templateID, $tplParams, $sign, "", ""); + } else { + //语音短信发送 + $this->sender = new TtsVoiceSender($this->appid, $this->appkey); + //参数: 国家码,手机号、模板ID、模板参数、播放次数(可选字段)、用户的session内容,服务器端原样返回(可选字段) + $result = $this->sender->send("86", $mobile, (int)$templateID, $tplParams); + } + } else { + //判断是否是语音短信 + if ((int)($this->config['isVoice'] ?? 0) !== 1) { + $this->sender = new SmsSingleSender($this->appid, $this->appkey); + //参数:短信类型{1营销短信,0普通短信 }、国家码、手机号、短信内容、扩展码(可留空)、服务的原样返回的参数 + $result = $this->sender->send((int)($params['type'] ?? 0), '86', $mobile, $msg, "", ""); + } else { + $this->sender = new SmsVoicePromptSender($this->appid, $this->appkey); + //参数:国家码、手机号、语音类型(目前固定为2)、短信内容、播放次数(默认2次)、服务的原样返回的参数 + $result = $this->sender->send('86', $mobile, 2, $msg); + } + } + $rsp = json_decode((string)$result, true); + if (is_array($rsp) && isset($rsp['result']) && (int)$rsp['result'] === 0 && ($rsp['errmsg'] ?? '') === 'OK') { + return true; + } + $this->setError(is_array($rsp) ? $rsp : (string)$result); + \think\Log::warning('[Qcloudsms::smsNotice] 发送失败 mobile=' . substr($mobile, 0, 3) . '****' . substr($mobile, -4) . ' rsp=' . json_encode($rsp, JSON_UNESCAPED_UNICODE)); + return false; + } catch (\Throwable $e) { + $this->setError($e->getMessage()); + \think\Log::error('[Qcloudsms::smsNotice] 异常: ' . $e->getMessage()); + return false; + } + } + + /** + * 记录失败信息 + * @param [type] $err [description] + */ + private function setError($err) + { + $this->sendError = $err; + self::$lastSendError = $err; + } + + /** + * 获取失败信息 + * @return [type] [description] + */ + public function getError() + { + return $this->sendError !== '' ? $this->sendError : self::$lastSendError; + } + + /** + * 检测验证是否正确 + * @param Sms $params + * @return boolean + */ + public function smsCheck(&$params) + { + return true; + } + + /** + * 插件安装方法 + * @return bool + */ + public function install() + { + return true; + } + + /** + * 插件卸载方法 + * @return bool + */ + public function uninstall() + { + return true; + } + + /** + * 插件启用方法 + * @return bool + */ + public function enable() + { + return true; + } + + /** + * 插件禁用方法 + * @return bool + */ + public function disable() + { + return true; + } +} diff --git a/server/addons/qcloudsms/config.php b/server/addons/qcloudsms/config.php new file mode 100644 index 0000000..2c0bfc7 --- /dev/null +++ b/server/addons/qcloudsms/config.php @@ -0,0 +1,167 @@ + + array ( + 'name' => 'appid', + 'title' => '应用AppID', + 'type' => 'string', + 'content' => + array ( + ), + 'value' => '1401235283', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ), + 1 => + array ( + 'name' => 'appkey', + 'title' => '应用AppKEY', + 'type' => 'string', + 'content' => + array ( + ), + 'value' => 'd694395bb32517d1d3fdc13df2bef8d9', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ), + 2 => + array ( + 'name' => 'voiceAppid', + 'title' => '语音短信AppID', + 'type' => 'string', + 'content' => + array ( + ), + 'value' => '', + 'rule' => '', + 'msg' => '使用语音短信时填写', + 'tip' => '未开启语音短信可留空', + 'ok' => '', + 'extend' => '', + ), + 3 => + array ( + 'name' => 'voiceAppkey', + 'title' => '语音短信AppKEY', + 'type' => 'string', + 'content' => + array ( + ), + 'value' => '', + 'rule' => '', + 'msg' => '使用语音短信时填写', + 'tip' => '未开启语音短信可留空', + 'ok' => '', + 'extend' => '', + ), + 4 => + array ( + 'name' => 'sign', + 'title' => '签名', + 'type' => 'string', + 'content' => + array ( + ), + 'value' => '毕节市赵工劳务服务经营部', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ), + 5 => + array ( + 'name' => 'isVoice', + 'title' => '是否使用语音短信', + 'type' => 'radio', + 'content' => + array ( + 0 => '否', + 1 => '是', + ), + 'value' => '0', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ), + 6 => + array ( + 'name' => 'isTemplateSender', + 'title' => '是否使用短信模板发送', + 'type' => 'radio', + 'content' => + array ( + 0 => '否', + 1 => '是', + ), + 'value' => '1', + 'rule' => 'required', + 'msg' => '', + 'tip' => '', + 'ok' => '', + 'extend' => '', + ), + 7 => + array ( + 'name' => 'template', + 'title' => '短信模板', + 'type' => 'array', + 'content' => + array ( + ), + 'value' => + array ( + 'register' => '', + 'resetpwd' => '2787419', + 'changepwd' => '2787392', + 'paypwd' => '2787392', + 'order_verify' => '2787295', + 'changemobile' => '', + 'profile' => '', + 'notice' => '', + 'mobilelogin' => '2762770', + 'bind' => '', + ), + 'rule' => 'required', + 'msg' => '', + 'tip' => 'changepwd/resetpwd/paypwd 变量 {1} 为验证码(paypwd 留空时自动复用 changepwd);order_verify 变量 {1} 为6位核销码', + 'ok' => '', + 'extend' => '', + ), + 8 => + array ( + 'name' => 'voiceTemplate', + 'title' => '语音短信模板', + 'type' => 'array', + 'content' => + array ( + ), + 'value' => + array ( + 'register' => '', + 'resetpwd' => '', + 'changepwd' => '', + 'paypwd' => '', + 'order_verify' => '', + 'changemobile' => '', + 'profile' => '', + 'notice' => '', + 'mobilelogin' => '', + 'bind' => '', + ), + 'rule' => '', + 'msg' => '', + 'tip' => '未开启语音短信可留空', + 'ok' => '', + 'extend' => '', + ), +); diff --git a/server/addons/qcloudsms/controller/Index.php b/server/addons/qcloudsms/controller/Index.php new file mode 100644 index 0000000..eb595df --- /dev/null +++ b/server/addons/qcloudsms/controller/Index.php @@ -0,0 +1,15 @@ +error("当前插件暂无前台页面"); + } + +} diff --git a/server/addons/qcloudsms/info.ini b/server/addons/qcloudsms/info.ini new file mode 100644 index 0000000..aa5eb3c --- /dev/null +++ b/server/addons/qcloudsms/info.ini @@ -0,0 +1,10 @@ +name = qcloudsms +title = 腾讯云短信发送插件 +intro = 腾讯云短信发送插件 +author = Seacent +website = +version = 1.0.4 +state = 1 +url = /addons/qcloudsms +license = regular +licenseto = 26425 diff --git a/server/addons/qcloudsms/library/FileVoiceSender.php b/server/addons/qcloudsms/library/FileVoiceSender.php new file mode 100644 index 0000000..4ed9f07 --- /dev/null +++ b/server/addons/qcloudsms/library/FileVoiceSender.php @@ -0,0 +1,69 @@ +url = "https://cloud.tim.qq.com/v5/tlsvoicesvr/sendfvoice"; + $this->appid = $appid; + $this->appkey = $appkey; + $this->util = new SmsSenderUtil(); + } + + /** + * + * 按语音文件fid发送语音通知 + * + * @param string $nationCode 国家码,如 86 为中国 + * @param string $phoneNumber 不带国家码的手机号 + * @param string $fid 语音文件fid + * @param string $playtimes 播放次数,可选,最多3次,默认2次 + * @param string $ext 用户的session内容,服务端原样返回,可选字段,不需要可填空串 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + public function send($nationCode, $phoneNumber, $fid, $playtimes = 2, $ext = "") + { + $random = $this->util->getRandom(); + $curTime = time(); + $wholeUrl = $this->url . "?sdkappid=" . $this->appid . "&random=" . $random; + + // 按照协议组织 post 包体 + $data = new \stdClass(); + $tel = new \stdClass(); + $tel->nationcode = "".$nationCode; + $tel->mobile = "".$phoneNumber; + $data->tel = $tel; + $data->fid = $fid; + $data->playtimes = $playtimes; + + // app凭证 + $data->sig = $this->util->calculateSig($this->appkey, $random, + $curTime, array($phoneNumber)); + + // unix时间戳,请求发起时间,如果和系统时间相差超过10分钟则会返回失败 + $data->time = $curTime; + $data->ext = $ext; + + return $this->util->sendCurlPost($wholeUrl, $data); + } +} diff --git a/server/addons/qcloudsms/library/SmsMobileStatusPuller.php b/server/addons/qcloudsms/library/SmsMobileStatusPuller.php new file mode 100644 index 0000000..40976fb --- /dev/null +++ b/server/addons/qcloudsms/library/SmsMobileStatusPuller.php @@ -0,0 +1,91 @@ +url = "https://yun.tim.qq.com/v5/tlssmssvr/pullstatus4mobile"; + $this->appid = $appid; + $this->appkey = $appkey; + $this->util = new SmsSenderUtil(); + } + + /** + * 拉取回执结果 + * + * @param int $type 拉取类型,0表示回执结果,1表示回复信息 + * @param string $nationCode 国家码,如 86 为中国 + * @param string $mobile 不带国家码的手机号 + * @param int $beginTime 开始时间(unix timestamp) + * @param int $endTime 结束时间(unix timestamp) + * @param int $max 拉取最大条数,最多100 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + private function pull($type, $nationCode, $mobile, $beginTime, $endTime, $max) + { + $random = $this->util->getRandom(); + $curTime = time(); + $wholeUrl = $this->url . "?sdkappid=" . $this->appid . "&random=" . $random; + + $data = new \stdClass(); + $data->sig = $this->util->calculateSigForPuller($this->appkey, $random, $curTime); + $data->time = $curTime; + $data->type = $type; + $data->max = $max; + $data->begin_time = $beginTime; + $data->end_time = $endTime; + $data->nationcode = $nationCode; + $data->mobile = $mobile; + + return $this->util->sendCurlPost($wholeUrl, $data); + } + + /** + * 拉取回执结果 + * + * @param string $nationCode 国家码,如 86 为中国 + * @param string $mobile 不带国家码的手机号 + * @param int $beginTime 开始时间(unix timestamp) + * @param int $endTime 结束时间(unix timestamp) + * @param int $max 拉取最大条数,最多100 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + public function pullCallback($nationCode, $mobile, $beginTime, $endTime, $max) + { + return $this->pull(0, $nationCode, $mobile, $beginTime, $endTime, $max); + } + + /** + * 拉取回复信息 + * + * @param string $nationCode 国家码,如 86 为中国 + * @param string $mobile 不带国家码的手机号 + * @param int $beginTime 开始时间(unix timestamp) + * @param int $endTime 结束时间(unix timestamp) + * @param int $max 拉取最大条数,最多100 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + public function pullReply($nationCode, $mobile, $beginTime, $endTime, $max) + { + return $this->pull(1, $nationCode, $mobile, $beginTime, $endTime, $max); + } +} \ No newline at end of file diff --git a/server/addons/qcloudsms/library/SmsMultiSender.php b/server/addons/qcloudsms/library/SmsMultiSender.php new file mode 100644 index 0000000..18ef526 --- /dev/null +++ b/server/addons/qcloudsms/library/SmsMultiSender.php @@ -0,0 +1,99 @@ +url = "https://yun.tim.qq.com/v5/tlssmssvr/sendmultisms2"; + $this->appid = $appid; + $this->appkey = $appkey; + $this->util = new SmsSenderUtil(); + } + + /** + * 普通群发 + * + * 普通群发需明确指定内容,如果有多个签名,请在内容中以【】的方式添加到信息内容中, + * 否则系统将使用默认签名。 + * + * + * @param int $type 短信类型,0 为普通短信,1 营销短信 + * @param string $nationCode 国家码,如 86 为中国 + * @param array $phoneNumbers 不带国家码的手机号列表 + * @param string $msg 信息内容,必须与申请的模板格式一致,否则将返回错误 + * @param string $extend 扩展码,可填空串 + * @param string $ext 服务端原样返回的参数,可填空串 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + public function send($type, $nationCode, $phoneNumbers, $msg, $extend = "", $ext = "") + { + $random = $this->util->getRandom(); + $curTime = time(); + $wholeUrl = $this->url . "?sdkappid=" . $this->appid . "&random=" . $random; + + $data = new \stdClass(); + $data->tel = $this->util->phoneNumbersToArray($nationCode, $phoneNumbers); + $data->type = $type; + $data->msg = $msg; + $data->sig = $this->util->calculateSig($this->appkey, $random, + $curTime, $phoneNumbers); + $data->time = $curTime; + $data->extend = $extend; + $data->ext = $ext; + + return $this->util->sendCurlPost($wholeUrl, $data); + } + + /** + * 指定模板群发 + * + * + * @param string $nationCode 国家码,如 86 为中国 + * @param array $phoneNumbers 不带国家码的手机号列表 + * @param int $templId 模板id + * @param array $params 模板参数列表,如模板 {1}...{2}...{3},那么需要带三个参数 + * @param string $sign 签名,如果填空串,系统会使用默认签名 + * @param string $extend 扩展码,可填空串 + * @param string $ext 服务端原样返回的参数,可填空串 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + public function sendWithParam($nationCode, $phoneNumbers, $templId, $params, + $sign = "", $extend = "", $ext = "") + { + $random = $this->util->getRandom(); + $curTime = time(); + $wholeUrl = $this->url . "?sdkappid=" . $this->appid . "&random=" . $random; + + $data = new \stdClass(); + $data->tel = $this->util->phoneNumbersToArray($nationCode, $phoneNumbers); + $data->sign = $sign; + $data->tpl_id = $templId; + $data->params = $params; + $data->sig = $this->util->calculateSigForTemplAndPhoneNumbers( + $this->appkey, $random, $curTime, $phoneNumbers); + $data->time = $curTime; + $data->extend = $extend; + $data->ext = $ext; + + return $this->util->sendCurlPost($wholeUrl, $data); + } +} diff --git a/server/addons/qcloudsms/library/SmsSenderUtil.php b/server/addons/qcloudsms/library/SmsSenderUtil.php new file mode 100644 index 0000000..8e4d9db --- /dev/null +++ b/server/addons/qcloudsms/library/SmsSenderUtil.php @@ -0,0 +1,211 @@ +nationcode = $nationCode; + $telElement->mobile = $phoneNumbers[$i]; + array_push($tel, $telElement); + } while (++$i < count($phoneNumbers)); + + return $tel; + } + + /** + * 生成签名 + * + * @param string $appkey sdkappid对应的appkey + * @param string $random 随机正整数 + * @param string $curTime 当前时间 + * @param array $phoneNumber 手机号码 + * @return string 签名结果 + */ + public function calculateSigForTempl($appkey, $random, $curTime, $phoneNumber) + { + $phoneNumbers = array($phoneNumber); + + return $this->calculateSigForTemplAndPhoneNumbers($appkey, $random, + $curTime, $phoneNumbers); + } + + /** + * 生成签名 + * + * @param string $appkey sdkappid对应的appkey + * @param string $random 随机正整数 + * @param string $curTime 当前时间 + * @return string 签名结果 + */ + public function calculateSigForPuller($appkey, $random, $curTime) + { + return hash("sha256", "appkey=".$appkey."&random=".$random + ."&time=".$curTime); + } + + /** + * 生成上传文件授权 + * + * @param string $appkey sdkappid对应的appkey + * @param string $random 随机正整数 + * @param string $curTime 当前时间 + * @param array $fileSha1Sum 文件sha1sum + * @return string 授权结果 + */ + public function calculateAuth($appkey, $random, $curTime, $fileSha1Sum) + { + return hash("sha256", "appkey=".$appkey."&random=".$random + ."&time=".$curTime."&content-sha1=".$fileSha1Sum); + } + + /** + * 生成sha1sum + * + * @param string $content 内容 + * @return string 内容sha1散列值 + */ + public function sha1sum($content) + { + return hash("sha1", $content); + } + + /** + * 发送请求 + * + * @param string $url 请求地址 + * @param array $dataObj 请求内容 + * @return string 应答json字符串 + */ + public function sendCurlPost($url, $dataObj) + { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_HEADER, 0); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($curl, CURLOPT_POST, 1); + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60); + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($dataObj)); + curl_setopt($curl, CURLOPT_HTTPHEADER, array( + 'Content-Type: application/json; charset=utf-8', + 'Content-Length: ' . strlen(json_encode($dataObj))) + ); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); + + $ret = curl_exec($curl); + if (false == $ret) { + // curl_exec failed + $result = "{ \"result\":" . -2 . ",\"errmsg\":\"" . curl_error($curl) . "\"}"; + } else { + $rsp = curl_getinfo($curl, CURLINFO_HTTP_CODE); + if (200 != $rsp) { + $result = "{ \"result\":" . -1 . ",\"errmsg\":\"". $rsp + . " " . curl_error($curl) ."\"}"; + } else { + $result = $ret; + } + } + + curl_close($curl); + + return $result; + } + + /** + * 发送请求 + * + * @param string $req 请求对象 + * @return string 应答json字符串 + */ + public function fetch($req) + { + $curl = curl_init(); + + curl_setopt($curl, CURLOPT_URL, $req->url); + curl_setopt($curl, CURLOPT_HTTPHEADER, $req->headers); + curl_setopt($curl, CURLOPT_POSTFIELDS, $req->body); + curl_setopt($curl, CURLOPT_HEADER, 0); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($curl, CURLOPT_POST, 1); + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); + + $result = curl_exec($curl); + + if (false == $result) { + // curl_exec failed + $result = "{ \"result\":" . -2 . ",\"errmsg\":\"" . curl_error($curl) . "\"}"; + } else { + $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); + if (200 != $code) { + $result = "{ \"result\":" . -1 . ",\"errmsg\":\"". $rsp + . " " . curl_error($curl) ."\"}"; + } + } + curl_close($curl); + + return $result; + } +} diff --git a/server/addons/qcloudsms/library/SmsSingleSender.php b/server/addons/qcloudsms/library/SmsSingleSender.php new file mode 100644 index 0000000..dc0f104 --- /dev/null +++ b/server/addons/qcloudsms/library/SmsSingleSender.php @@ -0,0 +1,107 @@ +url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms"; + $this->appid = $appid; + $this->appkey = $appkey; + $this->util = new SmsSenderUtil(); + } + + /** + * 普通单发 + * + * 普通单发需明确指定内容,如果有多个签名,请在内容中以【】的方式添加到信息内容中,否则系统将使用默认签名。 + * + * @param int $type 短信类型,0 为普通短信,1 营销短信 + * @param string $nationCode 国家码,如 86 为中国 + * @param string $phoneNumber 不带国家码的手机号 + * @param string $msg 信息内容,必须与申请的模板格式一致,否则将返回错误 + * @param string $extend 扩展码,可填空串 + * @param string $ext 服务端原样返回的参数,可填空串 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + public function send($type, $nationCode, $phoneNumber, $msg, $extend = "", $ext = "") + { + $random = $this->util->getRandom(); + $curTime = time(); + $wholeUrl = $this->url . "?sdkappid=" . $this->appid . "&random=" . $random; + + // 按照协议组织 post 包体 + $data = new \stdClass(); + $tel = new \stdClass(); + $tel->nationcode = "".$nationCode; + $tel->mobile = "".$phoneNumber; + + $data->tel = $tel; + $data->type = (int)$type; + $data->msg = $msg; + $data->sig = hash("sha256", + "appkey=".$this->appkey."&random=".$random."&time=" + .$curTime."&mobile=".$phoneNumber, FALSE); + $data->time = $curTime; + $data->extend = $extend; + $data->ext = $ext; + + return $this->util->sendCurlPost($wholeUrl, $data); + } + + /** + * 指定模板单发 + * + * @param string $nationCode 国家码,如 86 为中国 + * @param string $phoneNumber 不带国家码的手机号 + * @param int $templId 模板 id + * @param array $params 模板参数列表,如模板 {1}...{2}...{3},那么需要带三个参数 + * @param string $sign 签名,如果填空串,系统会使用默认签名 + * @param string $extend 扩展码,可填空串 + * @param string $ext 服务端原样返回的参数,可填空串 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + public function sendWithParam($nationCode, $phoneNumber, $templId = 0, $params, + $sign = "", $extend = "", $ext = "") + { + $random = $this->util->getRandom(); + $curTime = time(); + $wholeUrl = $this->url . "?sdkappid=" . $this->appid . "&random=" . $random; + + // 按照协议组织 post 包体 + $data = new \stdClass(); + $tel = new \stdClass(); + $tel->nationcode = "".$nationCode; + $tel->mobile = "".$phoneNumber; + + $data->tel = $tel; + $data->sig = $this->util->calculateSigForTempl($this->appkey, $random, + $curTime, $phoneNumber); + $data->tpl_id = $templId; + $data->params = $params; + $data->sign = $sign; + $data->time = $curTime; + $data->extend = $extend; + $data->ext = $ext; + + return $this->util->sendCurlPost($wholeUrl, $data); + } +} diff --git a/server/addons/qcloudsms/library/SmsStatusPuller.php b/server/addons/qcloudsms/library/SmsStatusPuller.php new file mode 100644 index 0000000..26ce88f --- /dev/null +++ b/server/addons/qcloudsms/library/SmsStatusPuller.php @@ -0,0 +1,75 @@ +url = "https://yun.tim.qq.com/v5/tlssmssvr/pullstatus"; + $this->appid = $appid; + $this->appkey = $appkey; + $this->util = new SmsSenderUtil(); + } + + /** + * 拉取回执结果 + * + * @param int $type 拉取类型,0表示回执结果,1表示回复信息 + * @param int $max 最大条数,最多100 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + private function pull($type, $max) + { + $random = $this->util->getRandom(); + $curTime = time(); + $wholeUrl = $this->url . "?sdkappid=" . $this->appid . "&random=" . $random; + + $data = new \stdClass(); + $data->sig = $this->util->calculateSigForPuller($this->appkey, $random, $curTime); + $data->time = $curTime; + $data->type = $type; + $data->max = $max; + + return $this->util->sendCurlPost($wholeUrl, $data); + } + + /** + * 拉取回执结果 + * + * @param int $max 拉取最大条数,最多100 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + public function pullCallback($max) + { + return $this->pull(0, $max); + } + + /** + * 拉取回复信息 + * + * @param int $max 拉取最大条数,最多100 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + public function pullReply($max) + { + return $this->pull(1, $max); + } +} \ No newline at end of file diff --git a/server/addons/qcloudsms/library/SmsVoicePromptSender.php b/server/addons/qcloudsms/library/SmsVoicePromptSender.php new file mode 100644 index 0000000..4ee87b5 --- /dev/null +++ b/server/addons/qcloudsms/library/SmsVoicePromptSender.php @@ -0,0 +1,71 @@ +url = "https://yun.tim.qq.com/v5/tlsvoicesvr/sendvoiceprompt"; + $this->appid = $appid; + $this->appkey = $appkey; + $this->util = new SmsSenderUtil(); + } + + /** + * + * 发送语音通知 + * + * @param string $nationCode 国家码,如 86 为中国 + * @param string $phoneNumber 不带国家码的手机号 + * @param string $prompttype 语音类型,目前固定为2 + * @param string $msg 信息内容,必须与申请的模板格式一致,否则将返回错误 + * @param string $playtimes 播放次数,可选,最多3次,默认2次 + * @param string $ext 用户的session内容,服务端原样返回,可选字段,不需要可填空串 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + public function send($nationCode, $phoneNumber, $prompttype, $msg, $playtimes = 2, $ext = "") + { + $random = $this->util->getRandom(); + $curTime = time(); + $wholeUrl = $this->url . "?sdkappid=" . $this->appid . "&random=" . $random; + + // 按照协议组织 post 包体 + $data = new \stdClass(); + $tel = new \stdClass(); + $tel->nationcode = "".$nationCode; + $tel->mobile = "".$phoneNumber; + + $data->tel = $tel; + // 通知内容,utf8编码,支持中文英文、数字及组合,需要和语音内容模版相匹配 + $data->promptfile = $msg; + // 固定值 2 + $data->prompttype = $prompttype; + $data->playtimes = $playtimes; + // app凭证 + $data->sig = hash("sha256", + "appkey=".$this->appkey."&random=".$random."&time=" + .$curTime."&mobile=".$phoneNumber, FALSE); + // unix时间戳,请求发起时间,如果和系统时间相差超过10分钟则会返回失败 + $data->time = $curTime; + $data->ext = $ext; + return $this->util->sendCurlPost($wholeUrl, $data); + } +} diff --git a/server/addons/qcloudsms/library/SmsVoiceVerifyCodeSender.php b/server/addons/qcloudsms/library/SmsVoiceVerifyCodeSender.php new file mode 100644 index 0000000..f59ff2b --- /dev/null +++ b/server/addons/qcloudsms/library/SmsVoiceVerifyCodeSender.php @@ -0,0 +1,67 @@ +url = "https://yun.tim.qq.com/v5/tlsvoicesvr/sendvoice"; + $this->appid = $appid; + $this->appkey = $appkey; + $this->util = new SmsSenderUtil(); + } + + /** + * 发送语音验证码 + * + * @param string $nationCode 国家码,如 86 为中国 + * @param string $phoneNumber 不带国家码的手机号 + * @param string $msg 信息内容,必须与申请的模板格式一致,否则将返回错误 + * @param int $playtimes 播放次数,可选,最多3次,默认2次 + * @param string $ext 用户的session内容,服务端原样返回,可选字段,不需要可填空串 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + public function send($nationCode, $phoneNumber, $msg, $playtimes = 2, $ext = "") + { + $random = $this->util->getRandom(); + $curTime = time(); + $wholeUrl = $this->url . "?sdkappid=" . $this->appid . "&random=" . $random; + + // 按照协议组织 post 包体 + $data = new \stdClass(); + $tel = new \stdClass(); + $tel->nationcode = "".$nationCode; + $tel->mobile = "".$phoneNumber; + + $data->tel = $tel; + $data->msg = $msg; + $data->playtimes = $playtimes; + // app凭证 + $data->sig = hash("sha256", + "appkey=".$this->appkey."&random=".$random."&time=" + .$curTime."&mobile=".$phoneNumber, FALSE); + // unix时间戳,请求发起时间,如果和系统时间相差超过10分钟则会返回失败 + $data->time = $curTime; + $data->ext = $ext; + + return $this->util->sendCurlPost($wholeUrl, $data); + } +} diff --git a/server/addons/qcloudsms/library/TtsVoiceSender.php b/server/addons/qcloudsms/library/TtsVoiceSender.php new file mode 100644 index 0000000..b45f55e --- /dev/null +++ b/server/addons/qcloudsms/library/TtsVoiceSender.php @@ -0,0 +1,77 @@ +url = "https://cloud.tim.qq.com/v5/tlsvoicesvr/sendtvoice"; + $this->appid = $appid; + $this->appkey = $appkey; + $this->util = new SmsSenderUtil(); + } + + /** + * + * 指定模板发送语音短信 + * + * @param string $nationCode 国家码,如 86 为中国 + * @param string $phoneNumber 不带国家码的手机号 + * @param int $templId 模板 id + * @param array $params 模板参数列表,如模板 {1}...{2}...{3},需要带三个参数 + * @param string $playtimes 播放次数,可选,最多3次,默认2次 + * @param string $ext 用户的session内容,服务端原样返回,可选字段,不需要可填空串 + * @return string 应答json字符串,详细内容参见腾讯云协议文档 + */ + public function send($nationCode, $phoneNumber, $templId, $params, $playtimes = 2, $ext = "") + { + /*var_dump($nationCode); + var_dump($phoneNumber); + var_dump($templId); + var_dump($params); + var_dump($playtimes); + exit();*/ + $random = $this->util->getRandom(); + $curTime = time(); + $wholeUrl = $this->url . "?sdkappid=" . $this->appid . "&random=" . $random; + + // 按照协议组织 post 包体 + $data = new \stdClass(); + $tel = new \stdClass(); + $tel->nationcode = "".$nationCode; + $tel->mobile = "".$phoneNumber; + $data->tel = $tel; + $data->tpl_id = $templId; + $data->params = $params; + $data->playtimes = $playtimes; + + // app凭证 + $data->sig = $this->util->calculateSig($this->appkey, $random, + $curTime, array($phoneNumber)); + + // unix时间戳,请求发起时间,如果和系统时间相差超过10分钟则会返回失败 + $data->time = $curTime; + $data->ext = $ext; + //var_dump($data);exit(); + return $this->util->sendCurlPost($wholeUrl, $data); + } +} diff --git a/server/application/api/controller/Auth.php b/server/application/api/controller/Auth.php index a09ecac..d159f7a 100644 --- a/server/application/api/controller/Auth.php +++ b/server/application/api/controller/Auth.php @@ -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('登录密码重置成功,请使用新密码登录'); + } + /** * 我的信息(含角色与师傅状态) */ diff --git a/server/application/api/controller/Master.php b/server/application/api/controller/Master.php index 614990f..22fbfe7 100644 --- a/server/application/api/controller/Master.php +++ b/server/application/api/controller/Master.php @@ -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'], + ]); } /** diff --git a/server/application/api/controller/MasterAuth.php b/server/application/api/controller/MasterAuth.php index 35e6ed5..5147339 100644 --- a/server/application/api/controller/MasterAuth.php +++ b/server/application/api/controller/MasterAuth.php @@ -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('支付密码已变更,请重新操作'); } diff --git a/server/application/api/controller/Security.php b/server/application/api/controller/Security.php index ceee9bf..dbc0209 100644 --- a/server/application/api/controller/Security.php +++ b/server/application/api/controller/Security.php @@ -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('支付密码修改成功'); } diff --git a/server/application/api/controller/Sms.php b/server/application/api/controller/Sms.php index 4971a00..dd5a354 100755 --- a/server/application/api/controller/Sms.php +++ b/server/application/api/controller/Sms.php @@ -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()); + } } } diff --git a/server/application/common/library/Sms.php b/server/application/common/library/Sms.php index 0600d2f..379d82a 100755 --- a/server/application/common/library/Sms.php +++ b/server/application/common/library/Sms.php @@ -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; } diff --git a/server/application/common/library/SmsService.php b/server/application/common/library/SmsService.php new file mode 100644 index 0000000..84b27ca --- /dev/null +++ b/server/application/common/library/SmsService.php @@ -0,0 +1,194 @@ + 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 '短信发送失败,请稍后重试或联系客服'; + } +} diff --git a/server/application/extra/addons.php b/server/application/extra/addons.php index 3c00579..1f67e1d 100755 --- a/server/application/extra/addons.php +++ b/server/application/extra/addons.php @@ -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 ( diff --git a/server/application/extra/site.php b/server/application/extra/site.php index 8d60d65..7c898bd 100755 --- a/server/application/extra/site.php +++ b/server/application/extra/site.php @@ -4,7 +4,7 @@ return array ( 'name' => '优匠优服', 'beian' => '', 'cdnurl' => '', - 'version' => '1.0.100', + 'version' => '1.0.102', 'timezone' => 'Asia/Shanghai', 'forbiddenip' => '', 'languages' => diff --git a/tests/sms_business_api.js b/tests/sms_business_api.js new file mode 100644 index 0000000..c65051b --- /dev/null +++ b/tests/sms_business_api.js @@ -0,0 +1,311 @@ +const assert = require('assert'); +const http = require('http'); +const fs = require('fs'); +const path = require('path'); +const { execFileSync } = require('child_process'); + +const config = fs.readFileSync(path.join(__dirname, '../server/.env'), 'utf8').split('[database]')[1].split(/\n\s*\[/)[0]; +const get = key => (config.match(new RegExp('^' + key + '\\s*=\\s*(.*)$', 'm')) || [])[1].trim(); +const mysql = process.env.MYSQL_BIN || 'D:\\Softwares\\mysql-8.0.31-winx64\\bin\\mysql.exe'; +const phpBin = process.env.PHP_BIN || 'D:\\Softwares\\phpstudy_pro\\Extensions\\php\\php7.4.3nts\\php.exe'; + +function sql(query) { + return execFileSync(mysql, ['-h', get('hostname'), '-P', get('hostport'), '-u', get('username'), '-D', get('database'), '-N', '-e', query], { + encoding: 'utf8', + env: { ...process.env, MYSQL_PWD: get('password') }, + }).trim(); +} + +function api(route, data, token) { + return new Promise((resolve, reject) => { + const req = http.request((process.env.API_BASE || 'http://yjyf:9560/api') + route, { + method: data ? 'POST' : 'GET', + headers: { + ...(token ? { token } : {}), + ...(data ? { 'content-type': 'application/x-www-form-urlencoded' } : {}), + }, + }, res => { + let body = ''; + res.setEncoding('utf8'); + res.on('data', chunk => { body += chunk; }); + res.on('end', () => { + try { + resolve({ status: res.statusCode, json: JSON.parse(body) }); + } catch (err) { + reject(new Error(`Invalid JSON (HTTP ${res.statusCode}): ${body.slice(0, 300)}`)); + } + }); + }); + req.on('error', reject); + req.end(data ? new URLSearchParams(data).toString() : undefined); + }); +} + +(async () => { + let userMobile; + do { + userMobile = '166' + String(Math.floor(Math.random() * 100000000)).padStart(8, '0'); + } while (sql(`SELECT COUNT(*) FROM fa_user WHERE mobile='${userMobile}'`) !== '0'); + + let masterMobile; + do { + masterMobile = '167' + String(Math.floor(Math.random() * 100000000)).padStart(8, '0'); + } while (sql(`SELECT COUNT(*) FROM fa_master WHERE mobile='${masterMobile}'`) !== '0'); + + let uid = 0; + let mid = 0; + let orderId = 0; + const orderCustomerMobile = '13912345678'; + + try { + // 1. 用户注册登录并测试未配置短信时的友好拦截 + const uLogin = await api('/auth/login', { mobile: userMobile, password: 'UserInit123!' }); + assert.strictEqual(uLogin.json.code, 1, uLogin.json.msg); + uid = Number(uLogin.json.data.userinfo.id); + const uToken = uLogin.json.data.token; + + // 校验 security/status 返回脱敏手机号 + const secStatus = await api('/security/status', null, uToken); + assert.strictEqual(secStatus.json.code, 1, secStatus.json.msg); + assert.strictEqual(secStatus.json.data.mobile, userMobile.slice(0, 3) + '****' + userMobile.slice(-4)); + + // 未登录调用 /sms/send user_changepwd 必须 401 拦截 + const unauthSms = await api('/sms/send', { mobile: userMobile, event: 'user_changepwd' }); + assert.notStrictEqual(unauthSms.json.code, 1, 'unauth user_changepwd sms must fail'); + + // 短信配置未生效/待审时发送失败应明确报错(且不保留 fa_sms 脏数据) + const addonCfg = fs.readFileSync(path.join(__dirname, '../server/addons/qcloudsms/config.php'), 'utf8'); + const hasAppId = /'name'\s*=>\s*'appid'[\s\S]*?'value'\s*=>\s*'([^']+)'/.test(addonCfg) && RegExp.$1.trim() !== ''; + const sendTry = await api('/auth/sendResetPasswordSms', { mobile: userMobile }); + if (!hasAppId) { + assert.notStrictEqual(sendTry.json.code, 1, 'unconfigured addon should return error'); + assert.match(sendTry.json.msg, /未配置/); + assert.strictEqual(sql(`SELECT COUNT(*) FROM fa_sms WHERE mobile='${userMobile}'`), '0'); + } else if (sendTry.json.code !== 1) { + assert.match(sendTry.json.msg, /短信模板审核中|过于频繁|暂不可用|连接超时|短信发送失败|未配置/); + assert.doesNotMatch(sendTry.json.msg, /package format|sdkappid|tpl_id/i); + assert.strictEqual(sql(`SELECT COUNT(*) FROM fa_sms WHERE mobile='${userMobile}'`), '0'); + } + + // 测试 60s 冷却拦截(模拟存在刚发送的验证码记录) + sql(`INSERT INTO fa_sms (event,mobile,code,times,ip,createtime) VALUES ('user_resetpwd','${userMobile}','112233',0,'127.0.0.1',UNIX_TIMESTAMP())`); + const cooldownRes = await api('/auth/sendResetPasswordSms', { mobile: userMobile }); + assert.notStrictEqual(cooldownRes.json.code, 1); + assert.match(cooldownRes.json.msg, /发送过于频繁/); + sql(`DELETE FROM fa_sms WHERE mobile='${userMobile}'`); + + // 2. 用户端:通过短信验证码修改登录密码(已登录安全中心) + sql(`INSERT INTO fa_sms (event,mobile,code,times,ip,createtime) VALUES ('user_changepwd','${userMobile}','665544',0,'127.0.0.1',UNIX_TIMESTAMP())`); + const uWrongCode = await api('/security/changeLoginPassword', { + verify_mode: 'sms', + sms_code: '000000', + new_password: 'UserChanged123!' + }, uToken); + assert.notStrictEqual(uWrongCode.json.code, 1, 'wrong sms code must fail'); + + const uSmsChange = await api('/security/changeLoginPassword', { + verify_mode: 'sms', + sms_code: '665544', + new_password: 'UserChanged123!' + }, uToken); + assert.strictEqual(uSmsChange.json.code, 1, uSmsChange.json.msg); + assert.strictEqual(sql(`SELECT COUNT(*) FROM fa_sms WHERE mobile='${userMobile}' AND event='user_changepwd'`), '0', 'sms code must be flushed after use'); + + // 旧 token 必须失效 + const uOldTokenCheck = await api('/security/status', null, uToken); + assert.notStrictEqual(uOldTokenCheck.json.code, 1, 'old user token must be cleared'); + + // 新密码登录成功 + const uReLogin = await api('/auth/login', { mobile: userMobile, password: 'UserChanged123!' }); + assert.strictEqual(uReLogin.json.code, 1, uReLogin.json.msg); + + // 3. 用户端:连续输错密码锁定后,通过忘记密码短信重置解除锁定 + for (let i = 0; i < 5; i++) { + await api('/auth/login', { mobile: userMobile, password: 'WrongPassword!' }); + } + const uLocked = await api('/auth/login', { mobile: userMobile, password: 'UserChanged123!' }); + assert.notStrictEqual(uLocked.json.code, 1); + assert.match(uLocked.json.msg, /15分钟/); + + // 跨端事件隔离:master_resetpwd 的验证码不能重置 user 密码 + sql(`INSERT INTO fa_sms (event,mobile,code,times,ip,createtime) VALUES ('master_resetpwd','${userMobile}','778899',0,'127.0.0.1',UNIX_TIMESTAMP())`); + const uCrossEvent = await api('/auth/resetPasswordBySms', { + mobile: userMobile, + sms_code: '778899', + new_password: 'UserReset123!' + }); + assert.notStrictEqual(uCrossEvent.json.code, 1, 'master_resetpwd code must not reset user password'); + + sql(`INSERT INTO fa_sms (event,mobile,code,times,ip,createtime) VALUES ('user_resetpwd','${userMobile}','889900',0,'127.0.0.1',UNIX_TIMESTAMP())`); + const uResetRes = await api('/auth/resetPasswordBySms', { + mobile: userMobile, + sms_code: '889900', + new_password: 'UserReset123!' + }); + assert.strictEqual(uResetRes.json.code, 1, uResetRes.json.msg); + const uLoginAfterReset = await api('/auth/login', { mobile: userMobile, password: 'UserReset123!' }); + assert.strictEqual(uLoginAfterReset.json.code, 1, 'user login should succeed after sms password reset and unlock'); + const uToken2 = uLoginAfterReset.json.data.token; + + // 3b. 用户端:支付密码设置、输错锁定后通过短信验证码重置并解锁 + const uSetPay = await api('/security/setPaymentPassword', { new_password: '123456' }, uToken2); + assert.strictEqual(uSetPay.json.code, 1, uSetPay.json.msg); + for (let i = 0; i < 5; i++) { + await api('/security/changePaymentPassword', { old_password: '000000', new_password: '654321' }, uToken2); + } + const uPayLocked = await api('/security/changePaymentPassword', { old_password: '123456', new_password: '654321' }, uToken2); + assert.notStrictEqual(uPayLocked.json.code, 1); + assert.match(uPayLocked.json.msg, /15分钟/); + + // 跨事件隔离:user_changepwd 不能改支付密码 + sql(`INSERT INTO fa_sms (event,mobile,code,times,ip,createtime) VALUES ('user_changepwd','${userMobile}','102030',0,'127.0.0.1',UNIX_TIMESTAMP())`); + const uCrossPay = await api('/security/changePaymentPassword', { verify_mode: 'sms', sms_code: '102030', new_password: '654321' }, uToken2); + assert.notStrictEqual(uCrossPay.json.code, 1, 'user_changepwd code must not change payment password'); + + sql(`INSERT INTO fa_sms (event,mobile,code,times,ip,createtime) VALUES ('user_paypwd','${userMobile}','203040',0,'127.0.0.1',UNIX_TIMESTAMP())`); + const uPaySmsReset = await api('/security/changePaymentPassword', { verify_mode: 'sms', sms_code: '203040', new_password: '654321' }, uToken2); + assert.strictEqual(uPaySmsReset.json.code, 1, uPaySmsReset.json.msg); + assert.strictEqual(sql(`SELECT COUNT(*) FROM fa_sms WHERE mobile='${userMobile}' AND event='user_paypwd'`), '0'); + const uPayAfterReset = await api('/security/changePaymentPassword', { old_password: '654321', new_password: '112233' }, uToken2); + assert.strictEqual(uPayAfterReset.json.code, 1, 'payment lock should be cleared after sms reset'); + + // 4. 师傅端:注册登录 + 短信修改密码 + 短信重置密码 + const mLogin = await api('/master_auth/login', { mobile: masterMobile, password: 'MasterInit123!' }); + assert.strictEqual(mLogin.json.code, 1, mLogin.json.msg); + mid = Number(mLogin.json.data.masterinfo.id); + const mToken = mLogin.json.data.token; + + const mSendTry = await api('/master_auth/sendPasswordSms', {}, mToken); + if (!hasAppId) { + assert.notStrictEqual(mSendTry.json.code, 1); + assert.match(mSendTry.json.msg, /未配置/); + } else if (mSendTry.json.code !== 1) { + assert.match(mSendTry.json.msg, /短信模板审核中|过于频繁|暂不可用|连接超时|短信发送失败|未配置/); + assert.doesNotMatch(mSendTry.json.msg, /package format|sdkappid|tpl_id/i); + } + + sql(`INSERT INTO fa_sms (event,mobile,code,times,ip,createtime) VALUES ('master_changepwd','${masterMobile}','334455',0,'127.0.0.1',UNIX_TIMESTAMP())`); + const mWrongCode = await api('/master_auth/changeLoginPassword', { + verify_mode: 'sms', + sms_code: '111111', + new_password: 'MasterChanged123!' + }, mToken); + assert.notStrictEqual(mWrongCode.json.code, 1); + + const mSmsChange = await api('/master_auth/changeLoginPassword', { + verify_mode: 'sms', + sms_code: '334455', + new_password: 'MasterChanged123!' + }, mToken); + assert.strictEqual(mSmsChange.json.code, 1, mSmsChange.json.msg); + assert.strictEqual(sql(`SELECT COUNT(*) FROM fa_sms WHERE mobile='${masterMobile}' AND event='master_changepwd'`), '0'); + + const mOldTokenCheck = await api('/master_auth/securityStatus', null, mToken); + assert.notStrictEqual(mOldTokenCheck.json.code, 1, 'old master token must be cleared'); + + // 跨端隔离:user_resetpwd 验证码不能重置师傅密码 + sql(`INSERT INTO fa_sms (event,mobile,code,times,ip,createtime) VALUES ('user_resetpwd','${masterMobile}','556677',0,'127.0.0.1',UNIX_TIMESTAMP())`); + const mCrossEvent = await api('/master_auth/resetPasswordBySms', { + mobile: masterMobile, + sms_code: '556677', + new_password: 'MasterReset123!' + }); + assert.notStrictEqual(mCrossEvent.json.code, 1); + + sql(`INSERT INTO fa_sms (event,mobile,code,times,ip,createtime) VALUES ('master_resetpwd','${masterMobile}','990011',0,'127.0.0.1',UNIX_TIMESTAMP())`); + const mResetRes = await api('/master_auth/resetPasswordBySms', { + mobile: masterMobile, + sms_code: '990011', + new_password: 'MasterReset123!' + }); + assert.strictEqual(mResetRes.json.code, 1, mResetRes.json.msg); + + const mLoginAfterReset = await api('/master_auth/login', { mobile: masterMobile, password: 'MasterReset123!' }); + assert.strictEqual(mLoginAfterReset.json.code, 1, mLoginAfterReset.json.msg); + const mToken2 = mLoginAfterReset.json.data.token; + + // 4b. 师傅端:支付密码设置、输错锁定后通过短信验证码重置并解锁 + const mSetPay = await api('/master_auth/setPaymentPassword', { new_password: '123456' }, mToken2); + assert.strictEqual(mSetPay.json.code, 1, mSetPay.json.msg); + for (let i = 0; i < 5; i++) { + await api('/master_auth/changePaymentPassword', { old_password: '000000', new_password: '654321' }, mToken2); + } + const mPayLocked = await api('/master_auth/changePaymentPassword', { old_password: '123456', new_password: '654321' }, mToken2); + assert.notStrictEqual(mPayLocked.json.code, 1); + assert.match(mPayLocked.json.msg, /15分钟/); + + sql(`INSERT INTO fa_sms (event,mobile,code,times,ip,createtime) VALUES ('master_paypwd','${masterMobile}','304050',0,'127.0.0.1',UNIX_TIMESTAMP())`); + const mPaySmsReset = await api('/master_auth/changePaymentPassword', { verify_mode: 'sms', sms_code: '304050', new_password: '654321' }, mToken2); + assert.strictEqual(mPaySmsReset.json.code, 1, mPaySmsReset.json.msg); + const mPayAfterReset = await api('/master_auth/changePaymentPassword', { old_password: '654321', new_password: '112233' }, mToken2); + assert.strictEqual(mPayAfterReset.json.code, 1, 'master payment lock should be cleared after sms reset'); + + // 5. 师傅完工提交(状态 6 -> 7)与下发核销码短信调用链验证 + sql(`UPDATE fa_master SET verify_status='pass', work_status='on', realname='测试师傅' WHERE id=${mid}`); + const orderNo = 'SMSTEST' + Date.now(); + sql(`INSERT INTO fa_order (order_no,user_id,master_id,service_name,price_type,contact,mobile,province,city,district,address,status,pay_status,pay_amount,total_amount,verify_code,createtime,updatetime) VALUES ('${orderNo}',${uid},${mid},'短信测试安装','fixed','张先生','${orderCustomerMobile}','贵州省','贵阳市','观山湖区','测试路1号',6,1,100,100,'432198',UNIX_TIMESTAMP(),UNIX_TIMESTAMP())`); + orderId = Number(sql(`SELECT id FROM fa_order WHERE order_no='${orderNo}'`)); + + const finishRes = await api('/master/finish', { + order_id: orderId, + 'images[]': '/uploads/test-finish.jpg', + damage_remark: '正常完工' + }, mToken2); + assert.strictEqual(finishRes.json.code, 1, finishRes.json.msg); + assert.strictEqual(finishRes.json.data.verify_code, undefined, 'master finish response must not expose verify_code'); + assert.strictEqual(finishRes.json.data.sms_sent, false, 'sms_sent should be false when qcloudsms not configured'); + assert.strictEqual(finishRes.json.data.sms_mobile_mask, '139****5678'); + assert.strictEqual(sql(`SELECT status FROM fa_order WHERE id=${orderId}`), '7'); + const msgContent = sql(`SELECT content FROM fa_message WHERE receive_type='user' AND receive_id=${uid} AND order_id=${orderId} ORDER BY id DESC LIMIT 1`); + assert.match(msgContent, /432198/, 'in-app message should contain verify_code'); + + // 6. 验证插件内部模板解析与异常处理(通过 PHP CLI 运行单元测试) + const phpCheck = execFileSync(phpBin, ['-r', ` + define('APP_PATH', __DIR__ . '/server/application/'); + require __DIR__ . '/server/thinkphp/base.php'; + \\think\\Loader::addNamespace('addons', __DIR__ . '/server/addons/'); + $addon = new \\addons\\qcloudsms\\Qcloudsms('qcloudsms'); + $ref = new ReflectionMethod($addon, 'resolveTemplateId'); + $ref->setAccessible(true); + $prop = new ReflectionProperty($addon, 'config'); + $prop->setAccessible(true); + $prop->setValue($addon, ['template' => ['changepwd' => '1001', 'resetpwd' => '1002', 'paypwd' => '1005', 'order_verify' => '1003', 'notice' => '1004']]); + assert($ref->invoke($addon, 'user_changepwd') === '1001'); + assert($ref->invoke($addon, 'master_changepwd') === '1001'); + assert($ref->invoke($addon, 'user_resetpwd') === '1002'); + assert($ref->invoke($addon, 'master_resetpwd') === '1002'); + assert($ref->invoke($addon, 'user_paypwd') === '1005'); + assert($ref->invoke($addon, 'master_paypwd') === '1005'); + assert($ref->invoke($addon, 'order_verify', 'notice') === '1003'); + $prop->setValue($addon, ['template' => ['changepwd' => '1001', 'notice' => '1004']]); + assert($ref->invoke($addon, 'user_paypwd') === '1001'); + assert($ref->invoke($addon, 'master_paypwd') === '1001'); + assert($ref->invoke($addon, 'order_verify', 'notice') === '1004'); + echo 'PLUGIN_UNIT_OK'; + `], { cwd: path.resolve(__dirname, '..'), encoding: 'utf8' }); + assert.match(phpCheck, /PLUGIN_UNIT_OK/, phpCheck); + + console.log('sms business API & plugin integration tests passed'); + } finally { + if (orderId) { + sql(`DELETE FROM fa_order_media WHERE order_id=${orderId}`); + sql(`DELETE FROM fa_order_log WHERE order_id=${orderId}`); + sql(`DELETE FROM fa_message WHERE order_id=${orderId}`); + sql(`DELETE FROM fa_order WHERE id=${orderId}`); + } + sql(`DELETE FROM fa_sms WHERE mobile IN ('${userMobile}','${masterMobile}','${orderCustomerMobile}')`); + if (uid) { + sql(`DELETE FROM fa_user_token WHERE user_id=${uid}`); + sql(`DELETE FROM fa_user_security WHERE user_id=${uid}`); + sql(`DELETE FROM fa_user WHERE id=${uid}`); + } + if (mid) { + sql(`DELETE FROM fa_master_token WHERE master_id=${mid}`); + sql(`DELETE FROM fa_master_security WHERE master_id=${mid}`); + sql(`DELETE FROM fa_master WHERE id=${mid}`); + } + } +})().catch(e => { + console.error(e); + process.exitCode = 1; +}); diff --git a/yjyf-app/components/YjyfPaymentPassword.vue b/yjyf-app/components/YjyfPaymentPassword.vue index 4144d6a..15d0a2b 100644 --- a/yjyf-app/components/YjyfPaymentPassword.vue +++ b/yjyf-app/components/YjyfPaymentPassword.vue @@ -1,18 +1,96 @@ diff --git a/yjyf-app/pages/login/login.vue b/yjyf-app/pages/login/login.vue index f05fb9d..96a87d0 100644 --- a/yjyf-app/pages/login/login.vue +++ b/yjyf-app/pages/login/login.vue @@ -85,6 +85,10 @@ + + 忘记密码? + + + + + + + + + + + + + + + + + + + + + + + + @@ -147,6 +240,18 @@ const password = ref(''); const showPassword = ref(false); + // 忘记密码短信重置状态 + const showReset = ref(false); + const resetMobile = ref(''); + const resetCode = ref(''); + const resetNewPwd = ref(''); + const resetConfirmPwd = ref(''); + const showResetPwd = ref(false); + const sendingResetSms = ref(false); + const resetLoading = ref(false); + const resetCountdown = ref(0); + let resetTimer = null; + let redirectUrl = ''; const statusBarHeight = ref(20); @@ -212,8 +317,97 @@ onUnload(() => { uni.$off(LOGIN_AGREEMENT_EVENT, handleAgreementConfirm); + if (resetTimer) { + clearInterval(resetTimer); + resetTimer = null; + } }); + function openResetModal() { + resetMobile.value = account.value.trim(); + resetCode.value = ''; + resetNewPwd.value = ''; + resetConfirmPwd.value = ''; + showResetPwd.value = false; + showReset.value = true; + } + + function closeResetModal() { + if (resetLoading.value) return; + showReset.value = false; + } + + function startResetCountdown(sec = 60) { + if (resetTimer) clearInterval(resetTimer); + resetCountdown.value = sec; + resetTimer = setInterval(() => { + if (resetCountdown.value <= 1) { + resetCountdown.value = 0; + clearInterval(resetTimer); + resetTimer = null; + } else { + resetCountdown.value -= 1; + } + }, 1000); + } + + async function sendResetSms() { + if (sendingResetSms.value || resetCountdown.value > 0) return; + const mobile = resetMobile.value.trim(); + if (!/^1[3-9]\d{9}$/.test(mobile)) { + toast('请输入正确的手机号'); + return; + } + sendingResetSms.value = true; + try { + const res = await api.sendResetPasswordSms({ mobile }); + toast('验证码已发送'); + startResetCountdown((res && res.cooldown) || 60); + } catch (err) { + toast(formatLoginError(err, '验证码发送失败')); + } finally { + sendingResetSms.value = false; + } + } + + async function submitResetPassword() { + if (resetLoading.value) return; + const mobile = resetMobile.value.trim(); + const code = resetCode.value.trim(); + if (!/^1[3-9]\d{9}$/.test(mobile)) { + toast('请输入正确的手机号'); + return; + } + if (!/^\d{4,6}$/.test(code)) { + toast('请输入有效的短信验证码'); + return; + } + if (!/^\S{6,30}$/.test(resetNewPwd.value)) { + toast('登录密码须为6至30位非空字符'); + return; + } + if (resetNewPwd.value !== resetConfirmPwd.value) { + toast('两次输入的新密码不一致'); + return; + } + resetLoading.value = true; + try { + await api.resetPasswordBySms({ + mobile, + sms_code: code, + new_password: resetNewPwd.value + }); + account.value = mobile; + password.value = ''; + showReset.value = false; + toast('密码重置成功,请使用新密码登录'); + } catch (err) { + toast(formatLoginError(err, '密码重置失败,请重试')); + } finally { + resetLoading.value = false; + } + } + function handleBackOrHome() { if (getCurrentPages().length > 1) { uni.navigateBack({ @@ -761,4 +955,88 @@ 20%, 60% { transform: translateX(-8rpx); } 40%, 80% { transform: translateX(8rpx); } } + + .forgot-row { + width: 100%; + display: flex; + justify-content: flex-end; + margin: -8rpx 0 18rpx; + padding-right: 12rpx; + box-sizing: border-box; + } + .forgot-link { + font-size: 26rpx; + color: #F0710D; + font-weight: 500; + } + .reset-mask { + position: fixed; + inset: 0; + z-index: 999; + background: rgba(0, 0, 0, 0.5); + display: flex; + align-items: flex-end; + } + .reset-sheet { + width: 100%; + background: #FFFFFF; + border-radius: 28rpx 28rpx 0 0; + padding: 32rpx 36rpx calc(40rpx + env(safe-area-inset-bottom)); + box-sizing: border-box; + } + .reset-head { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 28rpx; + } + .reset-title { + font-size: 34rpx; + font-weight: 700; + color: #1D2129; + } + .reset-close { + width: 48rpx; + height: 48rpx; + display: flex; + align-items: center; + justify-content: center; + } + .reset-close-ico { + width: 32rpx; + height: 32rpx; + opacity: 0.65; + } + .reset-sms-row { + display: flex; + align-items: center; + gap: 16rpx; + margin-bottom: 24rpx; + } + .reset-sms-input-row { + flex: 1; + min-width: 0; + margin-bottom: 0; + } + .reset-sms-btn { + flex-shrink: 0; + height: 96rpx; + line-height: 96rpx; + padding: 0 28rpx; + border-radius: 48rpx; + background: #FFF7F0; + color: #F0710D; + font-size: 26rpx; + font-weight: 600; + border: 1.5rpx solid rgba(240, 113, 13, 0.35); + } + .reset-sms-btn::after { + border: none; + } + .reset-sms-btn[disabled] { + opacity: 0.6; + color: #86909C; + background: #F7F8FA; + border-color: #E5E6EB; + } diff --git a/yjyf-app/pages/mine/security.vue b/yjyf-app/pages/mine/security.vue index 0d15e2a..752eb8d 100644 --- a/yjyf-app/pages/mine/security.vue +++ b/yjyf-app/pages/mine/security.vue @@ -1,14 +1,76 @@ @@ -136,6 +229,17 @@ const password = ref(''); const showPassword = ref(false); + const showReset = ref(false); + const resetMobile = ref(''); + const resetCode = ref(''); + const resetNewPwd = ref(''); + const resetConfirmPwd = ref(''); + const showResetPwd = ref(false); + const sendingResetSms = ref(false); + const resetLoading = ref(false); + const resetCountdown = ref(0); + let resetTimer = null; + let redirectUrl = ''; const statusBarHeight = ref(20); @@ -200,8 +304,97 @@ onUnload(() => { uni.$off(LOGIN_AGREEMENT_EVENT, handleAgreementConfirm); + if (resetTimer) { + clearInterval(resetTimer); + resetTimer = null; + } }); + function openResetModal() { + resetMobile.value = account.value.trim(); + resetCode.value = ''; + resetNewPwd.value = ''; + resetConfirmPwd.value = ''; + showResetPwd.value = false; + showReset.value = true; + } + + function closeResetModal() { + if (resetLoading.value) return; + showReset.value = false; + } + + function startResetCountdown(sec = 60) { + if (resetTimer) clearInterval(resetTimer); + resetCountdown.value = sec; + resetTimer = setInterval(() => { + if (resetCountdown.value <= 1) { + resetCountdown.value = 0; + clearInterval(resetTimer); + resetTimer = null; + } else { + resetCountdown.value -= 1; + } + }, 1000); + } + + async function sendResetSms() { + if (sendingResetSms.value || resetCountdown.value > 0) return; + const mobile = resetMobile.value.trim(); + if (!/^1[3-9]\d{9}$/.test(mobile)) { + toast('请输入正确的手机号'); + return; + } + sendingResetSms.value = true; + try { + const res = await api.sendResetPasswordSms({ mobile }); + toast('验证码已发送'); + startResetCountdown((res && res.cooldown) || 60); + } catch (err) { + toast(formatLoginError(err, '验证码发送失败')); + } finally { + sendingResetSms.value = false; + } + } + + async function submitResetPassword() { + if (resetLoading.value) return; + const mobile = resetMobile.value.trim(); + const code = resetCode.value.trim(); + if (!/^1[3-9]\d{9}$/.test(mobile)) { + toast('请输入正确的手机号'); + return; + } + if (!/^\d{4,6}$/.test(code)) { + toast('请输入有效的短信验证码'); + return; + } + if (!/^\S{6,30}$/.test(resetNewPwd.value)) { + toast('登录密码须为6至30位非空字符'); + return; + } + if (resetNewPwd.value !== resetConfirmPwd.value) { + toast('两次输入的新密码不一致'); + return; + } + resetLoading.value = true; + try { + await api.resetPasswordBySms({ + mobile, + sms_code: code, + new_password: resetNewPwd.value + }); + account.value = mobile; + password.value = ''; + showReset.value = false; + toast('密码重置成功,请使用新密码登录'); + } catch (err) { + toast(formatLoginError(err, '密码重置失败,请重试')); + } finally { + resetLoading.value = false; + } + } + function handleBackOrHome() { if (getCurrentPages().length > 1) { uni.navigateBack({ @@ -625,4 +818,88 @@ 20%, 60% { transform: translateX(-8rpx); } 40%, 80% { transform: translateX(8rpx); } } + + .forgot-row { + width: 100%; + display: flex; + justify-content: flex-end; + margin: -8rpx 0 18rpx; + padding-right: 12rpx; + box-sizing: border-box; + } + .forgot-link { + font-size: 26rpx; + color: #F0710D; + font-weight: 500; + } + .reset-mask { + position: fixed; + inset: 0; + z-index: 999; + background: rgba(0, 0, 0, 0.5); + display: flex; + align-items: flex-end; + } + .reset-sheet { + width: 100%; + background: #FFFFFF; + border-radius: 28rpx 28rpx 0 0; + padding: 32rpx 36rpx calc(40rpx + env(safe-area-inset-bottom)); + box-sizing: border-box; + } + .reset-head { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 28rpx; + } + .reset-title { + font-size: 34rpx; + font-weight: 700; + color: #1D2129; + } + .reset-close { + width: 48rpx; + height: 48rpx; + display: flex; + align-items: center; + justify-content: center; + } + .reset-close-ico { + width: 32rpx; + height: 32rpx; + opacity: 0.65; + } + .reset-sms-row { + display: flex; + align-items: center; + gap: 16rpx; + margin-bottom: 24rpx; + } + .reset-sms-input-row { + flex: 1; + min-width: 0; + margin-bottom: 0; + } + .reset-sms-btn { + flex-shrink: 0; + height: 96rpx; + line-height: 96rpx; + padding: 0 28rpx; + border-radius: 48rpx; + background: #FFF7F0; + color: #F0710D; + font-size: 26rpx; + font-weight: 600; + border: 1.5rpx solid rgba(240, 113, 13, 0.35); + } + .reset-sms-btn::after { + border: none; + } + .reset-sms-btn[disabled] { + opacity: 0.6; + color: #86909C; + background: #F7F8FA; + border-color: #E5E6EB; + } diff --git a/yjyf-master-app/pages/master/detail.vue b/yjyf-master-app/pages/master/detail.vue index c3e2278..51418b8 100644 --- a/yjyf-master-app/pages/master/detail.vue +++ b/yjyf-master-app/pages/master/detail.vue @@ -608,7 +608,7 @@ - 请向客户索取订单详情页中的 6 位数字验收码,核销成功后工钱即刻结算至您的钱包 + 请向客户索取订单详情或短信中的 6 位数字验收码,核销成功后工钱即刻结算至您的钱包 @@ -170,7 +212,7 @@ @@ -450,23 +583,71 @@ .input-box { height: 92rpx; + box-sizing: border-box; padding: 0 20rpx 0 24rpx; border-radius: $yjyf-radius-sm; background: $yjyf-bg-page; + border: 1.5rpx solid transparent; display: flex; align-items: center; gap: 12rpx; } + .input-box:focus-within { + background: $yjyf-bg-card; + border-color: $yjyf-primary; + } .input-field { flex: 1; min-width: 0; height: 92rpx; font-size: $yjyf-font-body; color: $yjyf-text-main; } .eye-btn { width: 56rpx; height: 56rpx; display: flex; align-items: center; justify-content: center; flex-shrink: 0; } .eye-ico { width: 34rpx; height: 34rpx; } .hint { font-size: $yjyf-font-micro; color: $yjyf-text-muted; line-height: 1.5; } .center-hint { text-align: center; } + .mode-tabs { display: flex; gap: 16rpx; } + .mode-tab { + flex: 1; + height: 76rpx; + box-sizing: border-box; + display: flex; + align-items: center; + justify-content: center; + border-radius: $yjyf-radius-sm; + background: $yjyf-bg-page; + border: 1.5rpx solid transparent; + color: $yjyf-text-secondary; + font-size: $yjyf-font-sub; + font-weight: 600; + } + .mode-tab.active { background: $yjyf-primary-bg; color: $yjyf-primary; border-color: rgba(240, 113, 13, 0.35); } + .sms-target { font-size: $yjyf-font-micro; color: $yjyf-text-secondary; } + .sms-row { display: flex; align-items: center; gap: 16rpx; } + .sms-input-box { flex: 1; min-width: 0; } + .sms-btn { + flex-shrink: 0; + height: 92rpx; + box-sizing: border-box; + display: flex; + align-items: center; + justify-content: center; + padding: 0 28rpx; + margin: 0; + border-radius: $yjyf-radius-sm; + background: $yjyf-primary-bg; + color: $yjyf-primary; + font-size: $yjyf-font-sub; + font-weight: 600; + border: 1.5rpx solid rgba(240, 113, 13, 0.35); + } + .sms-btn::after { border: none; } + .sms-btn[disabled] { opacity: 0.6; color: $yjyf-text-secondary; background: $yjyf-bg-page; border-color: $yjyf-border-color; } + .switch-link { text-align: center; font-size: $yjyf-font-sub; color: $yjyf-info; padding-top: 4rpx; } .primary { width: 100%; height: 90rpx; - line-height: 90rpx; + margin: 8rpx 0 0; + padding: 0; + display: flex; + align-items: center; + justify-content: center; border-radius: $yjyf-radius-pill; background: $yjyf-gradient-primary; box-shadow: $yjyf-shadow-button; @@ -476,4 +657,5 @@ border: none; } .primary::after { border: none; } + .primary[disabled] { opacity: 0.65; } diff --git a/yjyf-master-app/utils/api.js b/yjyf-master-app/utils/api.js index c7e8be5..1bf4051 100644 --- a/yjyf-master-app/utils/api.js +++ b/yjyf-master-app/utils/api.js @@ -20,7 +20,11 @@ export default { logout: () => post('/master_auth/logout', {}, { silent: true }), profile: () => get('/master_auth/profile'), securityStatus: () => get('/master_auth/securityStatus'), + sendPasswordSms: () => post('/master_auth/sendPasswordSms', {}), + sendPaymentPasswordSms: () => post('/master_auth/sendPaymentPasswordSms', {}), changeLoginPassword: (data) => post('/master_auth/changeLoginPassword', data), + sendResetPasswordSms: (data) => post('/master_auth/sendResetPasswordSms', data), + resetPasswordBySms: (data) => post('/master_auth/resetPasswordBySms', data), setPaymentPassword: (data) => post('/master_auth/setPaymentPassword', data), changePaymentPassword: (data) => post('/master_auth/changePaymentPassword', data),