where('status=1')->select(); if (empty($sms)) { return json_status(40602); } //随机一个数组元素 $key = array_rand($sms); $sms = $sms[$key]; return empty($sms) ? json_status(40601) : $sms; } /** * 发送短信验证码【单条】 * @param string $mobile 手机号 * @param int $tempid 模板id * @return \type|void */ public static function send($mobile = '', $tempid = 1) { if (!Validate::is($mobile, 'mobile')) { return json_status(40601); } //获取短信服务端信息 $sms = self::db(); //替换模板变量 $code = mt_rand(999, 10000); $replace_str = [ '{code}' => $code, ]; Cache::set('sms_' . $mobile . '_' . $tempid, $code, 300); $text = self::parseTemplate($tempid, $replace_str); $data = SendSms::send($sms, $mobile, $sms['code_url'], $text); $data['mobile'] = $mobile; //重复发送的api没有返回mobile self::writeLog($data, $sms['name'], $text); //记录短信日志 return $data; } /** * 验证验证码 * @param $mobile 手机号 * @param $code 验证码 * @param $tempid 模板id */ public static function verification($mobile, $code, $tempid = 1) { $validate = new \app\api\validate\Sms; $data = [ 'mobile' => $mobile, 'code' => $code, ]; if (!$validate->check($data)) { return json_status($validate->getError()); } //验证手机号 $cache_name = 'sms_' . $mobile . '_' . $tempid; $cache_code = Cache::get($cache_name); if ($cache_code != $code) { return json_status(40605); } //删除成功后的缓存 Cache::rm($cache_name); return json_status(); } /** * 发送系统通知类【单条】 * @param string $mobile 手机号 * @param int $tempid 模板id * @param int $arr 需要替换的变量数组 * @return \type|void */ public static function sendNotify($mobile = 0, $arr = [], $tempid = 3) { if (!Validate::is($mobile, 'mobile')) { return json_status(40601); } //获取短信服务端信息 $sms = self::db(); $text = self::parseTemplate($tempid, $arr); $data = SendSms::send($sms, $mobile, $sms['notify_url'], $text); self::writeLog($data, $sms['name'], $text); //记录短信日志 return $data; } /** * 记录发送日志 * @param array $arr 短信服务商返回数据 * @param $sms_name 当前短信发送服务商名称 * @param $text 短信内容 */ private static function writeLog($arr = [], $sms_name, $text) { if (isset($arr['data'][0])) { $_data = $arr['data'][0]; } else { $_data = $arr; } $_data['text'] = $text; $_data['platform'] = $sms_name; $_data['status'] = $_data['code'] === 0 ? 1 : 0; $_data['create_time'] = time(); $_data['month'] = date('Y-m'); Db::name(self::$table_log)->strict(false)->insert($_data); } /** * 短信模板解析 * @param $tempid * @param array $arr */ private static function parseTemplate($tempid, $arr = []) { $template = Db::name(self::$table_config)->find($tempid); if (empty($template)) { return json_status(40603); } $template['content'] = str_replace(array_keys($arr), $arr, $template['content']); return $template['content']; } }