AliSms.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * Created by PhpStorm
  4. * User: 林志杰
  5. * Email: [email protected]
  6. * Time: 2020/1/11 17:36
  7. */
  8. declare(strict_types=1);
  9. namespace app\common\lib\sms;
  10. use AlibabaCloud\Client\AlibabaCloud;
  11. use AlibabaCloud\Client\Exception\ClientException;
  12. use AlibabaCloud\Client\Exception\ServerException;
  13. class AliSms
  14. {
  15. /**
  16. * 阿里云发送验证码的场景
  17. * @param string $phone
  18. * @param int $code
  19. * @return bool
  20. * @throws ClientException
  21. */
  22. public static function sendCode(string $phone, int $code): bool
  23. {
  24. if (empty($phone) || empty($code)) {
  25. return false;
  26. }
  27. AlibabaCloud::accessKeyClient(config('aliyun.access_key_id'), config('aliyun.access_key_secret'))
  28. ->regionId(config('aliyun.region_id'))
  29. ->asDefaultClient();
  30. $templateParam = [
  31. "code" => $code
  32. ];
  33. try {
  34. $result = AlibabaCloud::rpc()
  35. ->product('Dysmsapi')
  36. // ->scheme('https') // https | http
  37. ->version('2017-05-25')
  38. ->action('SendSms')
  39. ->method('POST')
  40. ->host(config('aliyun.host'))
  41. ->options([
  42. 'query' => [
  43. 'RegionId' => "cn-hangzhou",
  44. 'PhoneNumber' => $phone,
  45. 'SingName' => config('aliyun.sign_name'),
  46. 'TemplateCode' => config('aliyun.template_code'),
  47. 'TemplateParam' => json_encode($templateParam)
  48. ],
  49. ])
  50. ->request();
  51. // print_r($result->toArray());
  52. } catch (ClientException $e) {
  53. return false;
  54. // echo $e->getErrorMessage() . PHP_EOL;
  55. } catch (ServerException $e) {
  56. return false;
  57. // echo $e->getErrorMessage() . PHP_EOL;
  58. }
  59. return true;
  60. }
  61. }