SignatureHelper.php 2.8 KB

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