Aliyun.php 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace crmeb\services\sms\storage;
  3. use crmeb\basic\BaseSms;
  4. use think\facade\Config;
  5. use AlibabaCloud\Client\AlibabaCloud;
  6. use AlibabaCloud\Client\Exception\ClientException;
  7. use AlibabaCloud\Client\Exception\ServerException;
  8. class Aliyun extends BaseSms
  9. {
  10. protected $server = 'dysmsapi.aliyuncs.com';
  11. protected $accessKey;
  12. protected $accessSecret;
  13. protected $client;
  14. protected $sign;
  15. protected function initialize(array $config)
  16. {
  17. parent::initialize($config); // TODO: Change the autogenerated stub
  18. $this->accessKey = Config::get($this->configFile . '.stores.' . $this->name . '.access_key', '');
  19. $this->accessSecret = Config::get($this->configFile . '.stores.' . $this->name . '.access_secret', '');
  20. $this->sign = Config::get($this->configFile . '.stores.' . $this->name . '.sign', '');
  21. $this->client = AlibabaCloud::accessKeyClient($this->accessKey, $this->accessSecret)
  22. ->regionId('cn-hangzhou')
  23. ->asDefaultClient();
  24. }
  25. public function send(string $phone, string $templateId, array $data = [])
  26. {
  27. if (!$this->accessKey || !$this->accessSecret || !$this->sign) {
  28. return $this->setError('aliyun 短信参数未设置');
  29. }
  30. if (!$phone) {
  31. return $this->setError('手机号为空');
  32. }
  33. $templateCode = $this->getTemplateCode($templateId);
  34. if (!$templateCode) {
  35. return $this->setError('找不到短信模板');
  36. }
  37. try {
  38. $res = AlibabaCloud::rpc()
  39. ->product('Dysmsapi')
  40. ->version('2017-05-25')
  41. ->action('SendSms')
  42. ->method('POST')
  43. ->host($this->server)
  44. ->options([
  45. 'query' => [
  46. 'RegionId' => 'cn-hangzhou',
  47. 'PhoneNumbers' => $phone,
  48. 'SignName' => $this->sign,
  49. 'TemplateCode' => $templateCode,
  50. 'TemplateParam' => json_encode($data),
  51. ],
  52. ])
  53. ->request();
  54. if (!$res) {
  55. return $this->setError('返回空值');
  56. }
  57. $res = $res->toArray();
  58. if (!isset($res['Code'])) {
  59. return $this->setError('异常返回值');
  60. }
  61. if ($res['Code'] != 'OK') {
  62. $err = isset($res['Message']) ? $res['Message'] : '';
  63. return $this->setError($err);
  64. }
  65. /*
  66. * res: ['Message':'OK','RequestId':'string36','BizId':'string20','Code':'OK']
  67. */
  68. return [
  69. 'data' => [
  70. 'content' => $templateId,
  71. 'template' => $templateId,
  72. 'id' => intval(substr($res['BizId'],8)),
  73. ],
  74. ];
  75. } catch (ClientException $e) {
  76. return $this->setError($e->getErrorMessage());
  77. } catch (ServerException $e) {
  78. return $this->setError($e->getErrorMessage());
  79. } // try...catch...
  80. }
  81. }