Sign.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. /**
  3. * QcloudApi_Common_Sign
  4. * 签名类
  5. */
  6. class QcloudApi_Common_Sign
  7. {
  8. /**
  9. * sign
  10. * 生成签名
  11. * @param string $srcStr 拼接签名源文字符串
  12. * @param string $secretKey secretKey
  13. * @param string $method 请求方法
  14. * @return
  15. */
  16. public static function sign($srcStr, $secretKey, $method = 'HmacSHA1')
  17. {
  18. switch ($method) {
  19. case 'HmacSHA1':
  20. $retStr = base64_encode(hash_hmac('sha1', $srcStr, $secretKey, true));
  21. break;
  22. // case 'HmacSHA256':
  23. // $retStr = base64_encode(hash_hmac('sha256', $srcStr, $secretKey, true));
  24. // break;
  25. default:
  26. throw new Exception($method . ' is not a supported encrypt method');
  27. return false;
  28. break;
  29. }
  30. return $retStr;
  31. }
  32. /**
  33. * makeSignPlainText
  34. * 生成拼接签名源文字符串
  35. * @param array $requestParams 请求参数
  36. * @param string $requestMethod 请求方法
  37. * @param string $requestHost 接口域名
  38. * @param string $requestPath url路径
  39. * @return
  40. */
  41. public static function makeSignPlainText($requestParams,
  42. $requestMethod = 'GET', $requestHost = YUNAPI_URL,
  43. $requestPath = '/v2/index.php')
  44. {
  45. $url = $requestHost . $requestPath;
  46. // 取出所有的参数
  47. $paramStr = self::_buildParamStr($requestParams, $requestMethod);
  48. $plainText = $requestMethod . $url . $paramStr;
  49. return $plainText;
  50. }
  51. /**
  52. * _buildParamStr
  53. * 拼接参数
  54. * @param array $requestParams 请求参数
  55. * @param string $requestMethod 请求方法
  56. * @return
  57. */
  58. protected static function _buildParamStr($requestParams, $requestMethod = 'GET')
  59. {
  60. $paramStr = '';
  61. ksort($requestParams);
  62. $i = 0;
  63. foreach ($requestParams as $key => $value)
  64. {
  65. if ($key == 'Signature')
  66. {
  67. continue;
  68. }
  69. // 排除上传文件的参数
  70. if ($requestMethod == 'POST' && substr($value, 0, 1) == '@') {
  71. continue;
  72. }
  73. // 把 参数中的 _ 替换成 .
  74. if (strpos($key, '_'))
  75. {
  76. $key = str_replace('_', '.', $key);
  77. }
  78. if ($i == 0)
  79. {
  80. $paramStr .= '?';
  81. }
  82. else
  83. {
  84. $paramStr .= '&';
  85. }
  86. $paramStr .= $key . '=' . $value;
  87. ++$i;
  88. }
  89. return $paramStr;
  90. }
  91. }