TencentSms.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace common\models\extend\sms;
  3. use yii\helpers\Json;
  4. use yii\web\UnprocessableEntityHttpException;
  5. use Overtrue\EasySms\Contracts\MessageInterface;
  6. use Overtrue\EasySms\Contracts\PhoneNumberInterface;
  7. use Overtrue\EasySms\Gateways\Gateway;
  8. use Overtrue\EasySms\Support\Config;
  9. use TencentCloud\Common\Credential;
  10. use TencentCloud\Common\Profile\ClientProfile;
  11. use TencentCloud\Common\Profile\HttpProfile;
  12. use TencentCloud\Common\Exception\TencentCloudSDKException;
  13. use TencentCloud\Sms\V20190711\SmsClient;
  14. use TencentCloud\Sms\V20190711\Models\SendSmsRequest;
  15. /**
  16. * Class TencentSms
  17. * @package common\models\extend\sms
  18. */
  19. class TencentSms extends Gateway
  20. {
  21. public $config = [];
  22. /**
  23. * @param PhoneNumberInterface $to
  24. * @param MessageInterface $message
  25. * @param Config $config
  26. * @return bool
  27. * @throws UnprocessableEntityHttpException
  28. */
  29. public function send(PhoneNumberInterface $to, MessageInterface $message, Config $config)
  30. {
  31. $this->config = [
  32. 'appid' => $config->get('access_app_id'),
  33. 'secret_id' => $config->get('access_key_id'),
  34. 'secret_key' => $config->get('access_key_secret'),
  35. ];
  36. try {
  37. $cred = new Credential($this->config['secret_id'], $this->config['secret_key']);
  38. $httpProfile = new HttpProfile();
  39. $httpProfile->setEndpoint("sms.tencentcloudapi.com");
  40. $clientProfile = new ClientProfile();
  41. $clientProfile->setHttpProfile($httpProfile);
  42. $client = new SmsClient($cred, "ap-guangzhou", $clientProfile);
  43. $req = new SendSmsRequest();
  44. $params = [
  45. "PhoneNumberSet" => [
  46. '86'.$to->getNumber(),
  47. ],
  48. "TemplateID" => $message->getTemplate(),
  49. "Sign" => $config->get('sign_name'),
  50. "TemplateParamSet" => [
  51. (string)$message->getData()['code'],
  52. ],
  53. "SmsSdkAppid" => $this->config['appid'],
  54. ];
  55. $req->fromJsonString(Json::encode($params));
  56. $resp = $client->SendSms($req);
  57. $result = $resp->toJsonString();
  58. $result = Json::decode($result);
  59. } catch (TencentCloudSDKException $e) {
  60. throw new UnprocessableEntityHttpException($e->getMessage());
  61. }
  62. if (isset($result['SendStatusSet'][0]['Code']) && $result['SendStatusSet'][0]['Code'] == 'Ok') {
  63. return true;
  64. }
  65. throw new UnprocessableEntityHttpException($result['SendStatusSet'][0]['Message'] ?? '发送失败');
  66. }
  67. }
粤ICP备19079148号