smslib.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. <?php
  2. /**
  3. * 签名助手 2017/11/19
  4. * Class SignatureHelper
  5. */
  6. class AliSmsHelper {
  7. /**
  8. * 生成签名并发起请求
  9. *
  10. * @param $accessKeyId string AccessKeyId (https://ak-console.aliyun.com/)
  11. * @param $accessKeySecret string AccessKeySecret
  12. * @param $domain string API接口所在域名
  13. * @param $params array API具体参数
  14. * @param $security boolean 使用https
  15. * @param $method boolean 使用GET或POST方法请求,VPC仅支持POST
  16. * @return bool|\stdClass 返回API接口调用结果,当发生错误时返回false
  17. */
  18. public function request($accessKeyId, $accessKeySecret, $domain, $params, $security=false, $method='POST') {
  19. $apiParams = array_merge(array (
  20. "SignatureMethod" => "HMAC-SHA1",
  21. "SignatureNonce" => uniqid(mt_rand(0,0xffff), true),
  22. "SignatureVersion" => "1.0",
  23. "AccessKeyId" => $accessKeyId,
  24. "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
  25. "Format" => "JSON",
  26. ), $params);
  27. ksort($apiParams);
  28. $sortedQueryStringTmp = "";
  29. foreach ($apiParams as $key => $value) {
  30. if(!is_array($value))
  31. $sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value);
  32. }
  33. $stringToSign = "${method}&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1));
  34. $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&",true));
  35. $signature = $this->encode($sign);
  36. $url = ($security ? 'https' : 'http')."://{$domain}/";
  37. try {
  38. $content = $this->fetchContent($url, $method, "Signature={$signature}{$sortedQueryStringTmp}");
  39. return $content;
  40. } catch( \Exception $e) {
  41. throw $e;
  42. }
  43. }
  44. private function encode($str){
  45. $res = urlencode($str);
  46. $res = preg_replace("/\+/", "%20", $res);
  47. $res = preg_replace("/\*/", "%2A", $res);
  48. $res = preg_replace("/%7E/", "~", $res);
  49. return $res;
  50. }
  51. private function fetchContent($url, $method, $body){
  52. $ch = curl_init();
  53. if($method == 'POST') {
  54. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
  55. curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  56. } else {
  57. $url .= '?'.$body;
  58. }
  59. curl_setopt($ch, CURLOPT_URL, $url);
  60. curl_setopt($ch, CURLOPT_TIMEOUT, 10);//15秒吧 启动时会有延迟
  61. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  62. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  63. "x-sdk-client" => "php/2.0.0"
  64. ));
  65. if(substr($url, 0,5) == 'https') {
  66. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  67. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  68. }
  69. $rtn = curl_exec($ch);
  70. if($rtn === false) {
  71. // 大多由设置等原因引起,一般无法保障后续逻辑正常执行,
  72. // 所以这里触发的是E_USER_ERROR,会终止脚本执行,无法被try...catch捕获,需要用户排查环境、网络等故障
  73. throw new Exception("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch));
  74. }
  75. curl_close($ch);
  76. return $rtn;
  77. }
  78. }
  79. /**
  80. * 发送短信
  81. */
  82. function alisms_sendSms($telphone,$sms_template_code,$sms_free_sign_name,$exparams=array()) {
  83. $accessKeyId=AliSMSAccessKey;
  84. $accessKeySecret=AliSMSAccessSecret;
  85. if(empty($accessKeyId) || empty($accessKeySecret)){
  86. throw new GeneralException("","没有配置短信key/secret");
  87. }
  88. $smsflowno="SMS".time()."-".rand(123456,654321);
  89. $params = array ();
  90. // *** 需用户填写部分 ***
  91. // fixme 必填:是否启用https
  92. $security = false;
  93. // fixme 必填: 短信接收号码
  94. $params["PhoneNumbers"] = $telphone;
  95. // fixme 必填: 短信签名,应严格按"签名名称"填写,请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
  96. $params["SignName"] = $sms_free_sign_name;
  97. // fixme 必填: 短信模板Code,应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
  98. $params["TemplateCode"] = $sms_template_code;
  99. // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
  100. $params['TemplateParam'] =count($exparams)<=0?"":json_encode($exparams);
  101. // fixme 可选: 设置发送短信流水号
  102. $params['OutId'] = $smsflowno;
  103. // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段
  104. //$params['SmsUpExtendCode'] = "1234567";
  105. // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
  106. if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
  107. $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
  108. }
  109. // 初始化SignatureHelper实例用于设置参数,签名以及发送请求
  110. $helper = new AliSmsHelper();
  111. // 此处可能会抛出异常,注意catch
  112. $reqres = $helper->request(
  113. $accessKeyId,
  114. $accessKeySecret,
  115. "dysmsapi.aliyuncs.com",
  116. array_merge($params, array(
  117. "RegionId" => "cn-hangzhou",
  118. "Action" => "SendSms",
  119. "Version" => "2017-05-25",
  120. )),
  121. $security
  122. );
  123. $result=@json_decode($reqres,true);
  124. if(is_array($result) && $result["Message"]=="OK" && $result["Code"]=="OK"){
  125. return true;
  126. }else{
  127. $except_msg ="短信消息提醒服务发生错误了啊 telphone:".$telphone." ]\n";
  128. $except_msg .=" reqres:".$reqres."\n";
  129. eeglobal_log_handler('smsbase_sendSms','error',$except_msg);
  130. $message="";
  131. if($result && !empty($result["Code"]))
  132. $message.="【".$result["Code"]."】";
  133. if($result && !empty($result["Message"]))
  134. $message.=" ".$result["Message"]."";
  135. $message=empty($message)?"短信发送失败":"短信发送失败:".$message;
  136. throw new GeneralException("sms",$message);
  137. }
  138. }