AliSmsFacadeRepository.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Repositories\Eloquent;
  3. use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
  4. use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
  5. use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
  6. use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
  7. use App\Repositories\Contracts\SmsInterface;
  8. use Darabonba\OpenApi\Models\Config;
  9. class AliSmsFacadeRepository extends BaseRepository implements SmsInterface
  10. {
  11. private static $instance = null;
  12. private $client;
  13. public $request;
  14. private function __construct($config)
  15. {
  16. $config = new Config($config);
  17. $config->endpoint = "dysmsapi.ap-southeast-1.aliyuncs.com";
  18. $this->client = new Dysmsapi($config);
  19. $this->request = new SendSmsRequest();
  20. }
  21. public static function client($config = [])
  22. {
  23. if (self::$instance === null) {
  24. if(!$config) {
  25. $config = [
  26. // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
  27. "accessKeyId" => config('sms.alisms.accessKeyId'),
  28. // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
  29. "accessKeySecret" => config('sms.alisms.accessKeySecret'),
  30. ];
  31. }
  32. self::$instance = new self($config);
  33. }
  34. return self::$instance;
  35. }
  36. public function getClient()
  37. {
  38. return $this->client;
  39. }
  40. public function setRequest($phoneNumber, $templateCode, $templateParam)
  41. {
  42. $this->request->phoneNumbers = $phoneNumber; // 接收短信的手机号码
  43. $this->request->signName = config('sms.alisms.signName'); // 短信签名名称
  44. $this->request->templateCode = $templateCode; // 短信模板ID
  45. $this->request->templateParam = json_encode($templateParam); // 短信模板变量对应的实际值
  46. return $this;
  47. }
  48. public function send()
  49. {
  50. $client = $this->getClient();
  51. try{
  52. $runtime = new RuntimeOptions();
  53. $runtime->maxIdleConns = 3;
  54. $runtime->connectTimeout = 1000;
  55. $runtime->readTimeout = 1000;
  56. $res = $client->sendSms($this->request, $runtime);
  57. var_dump($res);exit;
  58. }catch (TeaUnableRetryError $e) {
  59. // 获取报错数据
  60. var_dump($e->getErrorInfo());
  61. // 获取报错信息
  62. var_dump($e->getMessage());
  63. // 获取最后一次报错的 Exception 实例
  64. var_dump($e->getLastException());
  65. // 获取最后一次请求的 Request 实例
  66. var_dump($e->getLastRequest());
  67. }
  68. }
  69. }