AliSms.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. use think\facade\Log;
  14. class AliSms implements SmsBase
  15. {
  16. /**
  17. * 阿里云发送验证码的场景
  18. * @param string $phone
  19. * @param int $code
  20. * @return bool
  21. * @throws ClientException
  22. */
  23. public static function sendCode(string $phone, int $code): bool
  24. {
  25. if (empty($phone) || empty($code)) {
  26. return false;
  27. }
  28. AlibabaCloud::accessKeyClient(config('aliyun.access_key_id'), config('aliyun.access_key_secret'))
  29. ->regionId(config('aliyun.region_id'))
  30. ->asDefaultClient();
  31. $templateParam = [
  32. "code" => $code
  33. ];
  34. try {
  35. $result = AlibabaCloud::rpc()
  36. ->product('Dysmsapi')
  37. // ->scheme('https') // https | http
  38. ->version('2017-05-25')
  39. ->action('SendSms')
  40. ->method('POST')
  41. ->host(config('aliyun.host'))
  42. ->options([
  43. 'query' => [
  44. 'RegionId' => "cn-hangzhou",
  45. 'PhoneNumber' => $phone,
  46. 'SingName' => config('aliyun.sign_name'),
  47. 'TemplateCode' => config('aliyun.template_code'),
  48. 'TemplateParam' => json_encode($templateParam)
  49. ],
  50. ])
  51. ->request();
  52. Log::info("alisms-sendCode-{$phone}-result" . json_encode($result->toArray()));
  53. // print_r($result->toArray());
  54. } catch (ClientException $e) {
  55. Log::error("alisms-sendCode-{$phone}-ClientException" . $e->getErrorMessage());
  56. return false;
  57. // echo $e->getErrorMessage() . PHP_EOL;
  58. } catch (ServerException $e) {
  59. Log::error("alisms-sendCode-{$phone}-ServerException" . $e->getErrorMessage());
  60. return false;
  61. // echo $e->getErrorMessage() . PHP_EOL;
  62. }
  63. if (isset($result['Code']) && $result['Code'] === 'OK') {
  64. return true;
  65. }
  66. return false;
  67. }
  68. }