Smsservice.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------------------------------
  4. * GouGuOPEN [ 左手研发,右手开源,未来可期!]
  5. +-----------------------------------------------------------------------------------------------
  6. * @Copyright (c) 2021~2024 http://www.gouguoa.com All rights reserved.
  7. +-----------------------------------------------------------------------------------------------
  8. * @Licensed 勾股OA,开源且可免费使用,但并不是自由软件,未经授权许可不能去除勾股OA的相关版权信息
  9. +-----------------------------------------------------------------------------------------------
  10. * @Author 勾股工作室 <hdm58@qq.com>
  11. +-----------------------------------------------------------------------------------------------
  12. */
  13. declare (strict_types = 1);
  14. namespace smsservice;
  15. use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
  16. use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
  17. use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
  18. use AlibabaCloud\Tea\Exception\TeaError;
  19. use think\facade\Config;
  20. use think\facade\Log;
  21. class Smsservice
  22. {
  23. protected $client;
  24. public function __construct()
  25. {
  26. $config = config('aliyun');
  27. $configData = new \Darabonba\OpenApi\Models\Config([
  28. 'accessKeyId' => $config['access_key_id'],
  29. 'accessKeySecret' => $config['access_key_secret'],
  30. 'endpoint' => 'dysmsapi.aliyuncs.com',
  31. 'protocol' => 'HTTP',
  32. 'regionId' => $config['region_id']
  33. ]);
  34. $this->client = new Dysmsapi($configData);
  35. }
  36. /**
  37. * 发送短信
  38. *
  39. * @param string $phone 手机号
  40. * @param string $templateCode 模板CODE(如:SMS_123456789)
  41. * @param array $params 模板变量,如 ['code' => '1234']
  42. * @return array
  43. */
  44. public function sendSms(string $phone, string $templateCode, array $params = [])
  45. {
  46. $request = new SendSmsRequest([
  47. "signName" => config('aliyun.sign_name'),
  48. "templateCode" => $templateCode,
  49. "phoneNumbers" => $phone,
  50. "templateParam" => json_encode($params, JSON_UNESCAPED_UNICODE)
  51. ]);
  52. try {
  53. $response = $this->client->sendSms($request);
  54. $body = $response->body;
  55. return json_decode(json_encode($body),true);
  56. } catch (TeaUnableRetryError $e) {
  57. return ['code' => 1, 'msg' => '网络错误或请求失败', 'error' => $e->getMessage()];
  58. }
  59. }
  60. }