发短信集合类-阿里云短信涉及类
作者:互联网
1 namespace modulelib; 2 3 /** 4 * 签名助手 2017/11/19 5 * 6 * Class SignatureHelper 7 */ 8 class SignatureHelper { 9 10 /** 11 * 生成签名并发起请求 12 * 13 * @param $accessKeyId string AccessKeyId (https://ak-console.aliyun.com/) 14 * @param $accessKeySecret string AccessKeySecret 15 * @param $domain string API接口所在域名 16 * @param $params array API具体参数 17 * @param $security boolean 使用https 18 * @return bool|\stdClass 返回API接口调用结果,当发生错误时返回false 19 */ 20 public function request($accessKeyId, $accessKeySecret, $domain, $params, $security=false) { 21 $apiParams = array_merge(array ( 22 "SignatureMethod" => "HMAC-SHA1", 23 "SignatureNonce" => uniqid(mt_rand(0,0xffff), true), 24 "SignatureVersion" => "1.0", 25 "AccessKeyId" => $accessKeyId, 26 "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"), 27 "Format" => "JSON", 28 ), $params); 29 ksort($apiParams); 30 31 $sortedQueryStringTmp = ""; 32 foreach ($apiParams as $key => $value) { 33 $sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value); 34 } 35 36 $stringToSign = "GET&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1)); 37 38 $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&",true)); 39 40 $signature = $this->encode($sign); 41 42 $url = ($security ? 'https' : 'http')."://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}"; 43 44 try { 45 $content = $this->fetchContent($url); 46 return json_decode($content); 47 } catch( \Exception $e) { 48 return false; 49 } 50 } 51 52 private function encode($str) 53 { 54 $res = urlencode($str); 55 $res = preg_replace("/\+/", "%20", $res); 56 $res = preg_replace("/\*/", "%2A", $res); 57 $res = preg_replace("/%7E/", "~", $res); 58 return $res; 59 } 60 61 private function fetchContent($url) { 62 $ch = curl_init(); 63 curl_setopt($ch, CURLOPT_URL, $url); 64 curl_setopt($ch, CURLOPT_TIMEOUT, 5); 65 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 66 curl_setopt($ch, CURLOPT_HTTPHEADER, array( 67 "x-sdk-client" => "php/2.0.0" 68 )); 69 70 if(substr($url, 0,5) == 'https') { 71 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 72 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 73 } 74 75 $rtn = curl_exec($ch); 76 77 if($rtn === false) { 78 trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR); 79 } 80 curl_close($ch); 81 82 return $rtn; 83 } 84 }
标签:ch,短信,setopt,res,encode,阿里,发短信,false,curl 来源: https://www.cnblogs.com/exo5/p/13576063.html