QidianyunSms.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace Tool\MayouTool\Sms;
  3. use Tool\MayouTool\HttpCurl;
  4. class QidianyunSms
  5. {
  6. public static function encodePercent($str)
  7. {
  8. $res = urlencode($str);
  9. $res = preg_replace('/\+/', '%20', $res);
  10. $res = preg_replace('/\*/', '%2A', $res);
  11. $res = preg_replace('/%7E/', '~', $res);
  12. return $res;
  13. }
  14. /**
  15. * @param $apiParams
  16. * @return string
  17. */
  18. public static function buildSign($apiParams)
  19. {
  20. ksort($apiParams);
  21. $canonicalizedQueryString = '';
  22. foreach ($apiParams as $key => $value) {
  23. $canonicalizedQueryString .= '&' . self::encodePercent($key) . '=' . self::encodePercent($value);
  24. }
  25. $methodType = 'POST';
  26. return $methodType . '&%2F&' . self::encodePercent(substr($canonicalizedQueryString, 1));
  27. }
  28. public static function hmac($stringToSign, $accessSecret)
  29. {
  30. return base64_encode(hash_hmac('sha1', $stringToSign, $accessSecret . '&', true));
  31. }
  32. public static function send($mobile, $code, $sign_name = null, $template_code = null)
  33. {
  34. $content = array(
  35. 'content' => "您的验证码是: $code ,请勿向任何人提供短信验证码,五分钟内有效。",
  36. );
  37. $api_params = array(
  38. 'templateParam' => json_encode($content, JSON_UNESCAPED_UNICODE),
  39. 'receiver' => $mobile,
  40. 'smsSignName' => env("QIANDIANYUN_SIGN_NAME"),
  41. 'templateCode' => env("QIANDIANYUN_TEMPLATE_CODE"),
  42. 'timestamp' => time() * 1000,
  43. 'signType' => 'HMAC',
  44. 'account' => env("QIDIANYUN_ACCOUNT"),
  45. );
  46. // 组合请求参数
  47. $sign = self::buildSign($api_params);
  48. // 根据组合参数和密钥进行签名
  49. $sign = self::hmac($sign, env("QIANDIANYUN_SECRET"));
  50. // 将签名增加到参数中
  51. $api_params['sign'] = $sign;
  52. // 格式化准备发送参数
  53. // $sendJson = json_encode($api_params, JSON_UNESCAPED_UNICODE);
  54. // $ret = HTTP::request(self::API, $sendJson, null, [
  55. // 'Content-Type: application/json; charset=utf-8',
  56. // 'Content-Length: ' . strlen($sendJson)
  57. // ]);
  58. $ret = HttpCurl::postCurl(self::API,$api_params);
  59. return $ret;
  60. }
  61. const API = 'https://smsapi.startdt.com/v2/sms/send';
  62. }