$accessKeyId, // 必填,您的 AccessKey Secret "accessKeySecret" => $accessKeySecret ]); // 访问的域名 $config->endpoint = "dysmsapi.aliyuncs.com"; return new OpenApiClient($config); } /** * API 相关 * @return Params OpenApi.Params */ public static function createApiInfo(): Params { $params = new Params([ // 接口名称 "action" => "SendSms", // 接口版本 "version" => "2017-05-25", // 接口协议 "protocol" => "HTTPS", // 接口 HTTP 方法 "method" => "POST", "authType" => "AK", "style" => "RPC", // 接口 PATH "pathname" => "/", // 接口请求体内容格式 "reqBodyType" => "json", // 接口响应体内容格式 "bodyType" => "json" ]); return $params; } /** * 发送短信 * @param string $phone_numbers 手机号 * @param array $template_param 参数 * @param string $template_code 短信模版编码 * @param int $scene 场景 */ public static function sendSms(string $phone_numbers,array $template_param,string $template_code,int $scene): void { $config = config("alibaba.dysms"); $client = self::createClient($config['accessKey'], $config['accessKeySecret']); $params = self::createApiInfo(); // query params $queries = []; $queries["PhoneNumbers"] = $phone_numbers; $queries["SignName"] = "肝胆相照"; $queries["TemplateCode"] = $template_code; $queries["TemplateParam"] = json_encode($template_param,JSON_UNESCAPED_UNICODE); // runtime options $runtime = new RuntimeOptions([]); $request = new OpenApiRequest([ "query" => OpenApiUtilClient::query($queries) ]); // 复制代码运行请自行打印 API 的返回值 // 返回值为 Map 类型,可从 Map 中获得三类数据:响应体 body、响应头 headers、HTTP 返回的状态码 statusCode $result = $client->callApi($params, $request, $runtime); if (empty($result)){ throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::CODE_FAIL)); } if (empty($result['body'])){ throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::CODE_FAIL)); } if ($result['body']['Code'] != "OK"){ throw new BusinessException($result['body']['Message'],HttpEnumCode::CODE_FAIL); } if (empty($result['body']['RequestId'])){ // 无唯一值 throw new BusinessException($result['body']['Message'],HttpEnumCode::CODE_FAIL); } // 记录log $data = array(); $data['type'] = 1; $data['status'] = 1; $data['scene'] = $scene; $data['phone'] = $phone_numbers; $data['code'] = $template_code; $data['third_code'] = $result['body']['RequestId']; $data['remarks'] = json_encode($template_param,JSON_UNESCAPED_UNICODE); $res = CodeLog::addCodeLog($data); if (empty($res)){ // 发送成功,记录失败 throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::CODE_FAIL)); } } }