SignatureHelper.php 2.6 KB

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