AliSmsService.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. <?php
  2. namespace App\Services;
  3. /**
  4. * 阿里云短信服务
  5. * Class AliSmsService
  6. * @package App\Services
  7. */
  8. class AliSmsService
  9. {
  10. public $accessKeyId;
  11. public $accessKeySecret;
  12. public $domain = "dysmsapi.aliyuncs.com";
  13. public $security = true;
  14. public function __construct($accessKeyId, $accessKeySecret)
  15. {
  16. $this->accessKeyId = $accessKeyId;
  17. $this->accessKeySecret = $accessKeySecret;
  18. }
  19. /**
  20. * 发送短信
  21. * @param $templateCode
  22. * @param $signName
  23. * @param $phone
  24. * @param $templateParams
  25. * @return bool|\stdClass
  26. * @throws \Exception
  27. */
  28. public function send($templateCode, $signName, $phone, $templateParams)
  29. {
  30. $params = array();
  31. // 必填:是否启用https
  32. $security = false;
  33. // 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
  34. // 必填: 短信接收号码
  35. $params["PhoneNumbers"] = $phone;
  36. // 必填: 短信签名,应严格按"签名名称"填写,请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
  37. $params["SignName"] = $signName;
  38. // 必填: 短信模板Code,应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
  39. $params["TemplateCode"] = $templateCode;
  40. // 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
  41. $params['TemplateParam'] = $templateParams;
  42. // 可选: 设置发送短信流水号
  43. $params['OutId'] = time() . rand(10000, 99999);
  44. // 可选: 上行短信扩展码, 扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段
  45. $params['SmsUpExtendCode'] = "1234567";
  46. if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
  47. $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
  48. }
  49. $params = array_merge($params, array(
  50. "RegionId" => "cn-hangzhou",
  51. "Action" => "SendSms",
  52. "Version" => "2017-05-25",
  53. ));
  54. // 此处可能会抛出异常,注意catch
  55. try {
  56. $response = $this->request($params);
  57. } catch (\Exception $e) {
  58. throw new \Exception($e->getMessage());
  59. }
  60. if ($response->Code != 'OK') {
  61. throw new \Exception($response->Code);
  62. }
  63. return $response;
  64. }
  65. /**
  66. * 批量发送
  67. * @param $templateCode
  68. * @param $signName
  69. * @param array $phoneNumbers
  70. * @param array $templateParams
  71. * @return bool|\stdClass
  72. * @throws \Exception
  73. */
  74. public function sendBatch($templateCode, $signName, array $phoneNumbers, array $templateParams)
  75. {
  76. $params = array();
  77. // 必填:是否启用https
  78. $security = false;
  79. // 必填: 待发送手机号。支持JSON格式的批量调用,批量上限为100个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
  80. $params["PhoneNumberJson"] = $phoneNumbers;
  81. // 必填: 短信签名,支持不同的号码发送不同的短信签名,每个签名都应严格按"签名名称"填写,请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
  82. foreach ($phoneNumbers as $key => $value) {
  83. $params["SignNameJson"][] = $signName;
  84. }
  85. // 必填: 短信模板Code,应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
  86. $params["TemplateCode"] = $templateCode;
  87. // 必填: 模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
  88. // 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
  89. $params["TemplateParamJson"] = $templateParams;
  90. // 可选: 上行短信扩展码, 扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段
  91. // $params["SmsUpExtendCodeJson"] = json_encode(array("90997","90998"));
  92. // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
  93. $params["TemplateParamJson"] = json_encode($params["TemplateParamJson"], JSON_UNESCAPED_UNICODE);
  94. $params["SignNameJson"] = json_encode($params["SignNameJson"], JSON_UNESCAPED_UNICODE);
  95. $params["PhoneNumberJson"] = json_encode($params["PhoneNumberJson"], JSON_UNESCAPED_UNICODE);
  96. if (!empty($params["SmsUpExtendCodeJson"]) && is_array($params["SmsUpExtendCodeJson"])) {
  97. $params["SmsUpExtendCodeJson"] = json_encode($params["SmsUpExtendCodeJson"], JSON_UNESCAPED_UNICODE);
  98. }
  99. $params = array_merge($params, array(
  100. "RegionId" => "cn-hangzhou",
  101. "Action" => "SendBatchSms",
  102. "Version" => "2017-05-25",
  103. ));
  104. // 初始化SignatureHelper实例用于设置参数,签名以及发送请求
  105. // 此处可能会抛出异常,注意catch
  106. try {
  107. $response = $this->request($params);
  108. } catch (\Exception $e) {
  109. throw new \Exception($e->getMessage());
  110. }
  111. if ($response->Code != 'OK') {
  112. throw new \Exception($response->Code);
  113. }
  114. return $response;
  115. }
  116. /**
  117. * 短信发送记录查询
  118. * @param $phoneNumber
  119. * @param $sendDate
  120. * @param null $bizId
  121. * @param int $currentPage
  122. * @param int $pageSize
  123. * @return bool|\stdClass
  124. * @throws \Exception
  125. */
  126. public function querySendDetails($phoneNumber, $sendDate, $bizId = null, $currentPage = 1, $pageSize = 10)
  127. {
  128. $params = array();
  129. // 必填: 短信接收号码
  130. $params["PhoneNumber"] = $phoneNumber;
  131. // 必填: 短信发送日期,格式Ymd,支持近30天记录查询
  132. $params["SendDate"] = $sendDate;
  133. // 必填: 分页大小
  134. $params["PageSize"] = $pageSize;
  135. // 必填: 当前页码
  136. $params["CurrentPage"] = $currentPage;
  137. // 可选: 设置发送短信流水号
  138. if ($bizId) {
  139. $params["BizId"] = $bizId;
  140. }
  141. $params = array_merge($params, array(
  142. "RegionId" => "cn-hangzhou",
  143. "Action" => "QuerySendDetails",
  144. "Version" => "2017-05-25",
  145. ));
  146. // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
  147. // 初始化SignatureHelper实例用于设置参数,签名以及发送请求
  148. // 此处可能会抛出异常,注意catch
  149. try {
  150. $response = $this->request($params);
  151. } catch (\Exception $e) {
  152. throw new \Exception($e->getMessage());
  153. }
  154. if ($response->Code != 'OK') {
  155. throw new \Exception($response->Code);
  156. }
  157. return $response;
  158. }
  159. /**
  160. * 生成签名并发起请求
  161. *
  162. * @param array $params API具体参数
  163. * @param string $method boolean 使用GET或POST方法请求,VPC仅支持POST
  164. * @return bool|\stdClass 返回API接口调用结果,当发生错误时返回false
  165. */
  166. private function request($params, $method = 'POST')
  167. {
  168. $apiParams = array_merge(array(
  169. "SignatureMethod" => "HMAC-SHA1",
  170. "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
  171. "SignatureVersion" => "1.0",
  172. "AccessKeyId" => $this->accessKeyId,
  173. "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
  174. "Format" => "JSON",
  175. ), $params);
  176. ksort($apiParams);
  177. $sortedQueryStringTmp = "";
  178. foreach ($apiParams as $key => $value) {
  179. $sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value);
  180. }
  181. $stringToSign = "${method}&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1));
  182. $sign = base64_encode(hash_hmac("sha1", $stringToSign, $this->accessKeySecret . "&", true));
  183. $signature = $this->encode($sign);
  184. $url = ($this->security ? 'https' : 'http') . "://{$this->domain}/";
  185. try {
  186. $content = $this->fetchContent($url, $method, "Signature={$signature}{$sortedQueryStringTmp}");
  187. return json_decode($content);
  188. } catch (\Exception $e) {
  189. return false;
  190. }
  191. }
  192. private function encode($str)
  193. {
  194. $res = urlencode($str);
  195. $res = preg_replace("/\+/", "%20", $res);
  196. $res = preg_replace("/\*/", "%2A", $res);
  197. $res = preg_replace("/%7E/", "~", $res);
  198. return $res;
  199. }
  200. private function fetchContent($url, $method, $body)
  201. {
  202. $ch = curl_init();
  203. if ($method == 'POST') {
  204. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
  205. curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  206. } else {
  207. $url .= '?' . $body;
  208. }
  209. curl_setopt($ch, CURLOPT_URL, $url);
  210. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  211. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  212. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  213. "x-sdk-client" => "php/2.0.0",
  214. ));
  215. if (substr($url, 0, 5) == 'https') {
  216. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  217. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  218. }
  219. $rtn = curl_exec($ch);
  220. if ($rtn === false) {
  221. // 大多由设置等原因引起,一般无法保障后续逻辑正常执行,
  222. // 所以这里触发的是E_USER_ERROR,会终止脚本执行,无法被try...catch捕获,需要用户排查环境、网络等故障
  223. trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
  224. }
  225. curl_close($ch);
  226. return $rtn;
  227. }
  228. }