Sms.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace App\Helpers\Utils;
  3. use Log;
  4. use Overtrue\EasySms\EasySms;
  5. /**
  6. * 不涉及数据库模型的通用工具类
  7. * 阿里云短信发送
  8. */
  9. class Sms
  10. {
  11. protected $easySms;
  12. //定义短信模版常量
  13. const LOGIN = 'SMS_205123614'; //登录/注册验证码
  14. public function __construct() {
  15. $this->easySms = new EasySms(config('easysms'));
  16. }
  17. public function send($phone, $template = 'LOGIN', $data = []) {
  18. try {
  19. if(empty($data)){
  20. $data = [
  21. 'code' => str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT) // 验证码
  22. ];
  23. }
  24. $this->easySms->send($phone, [
  25. 'template' => constant('self::' . $template), //阿里云模版
  26. 'data' => $data
  27. ]);
  28. } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
  29. $message = $exception->getException('aliyun')->getMessage();
  30. Log::info($message);
  31. return ['status'=> false, 'data'=> $data];
  32. //return $this->response->errorInternal($message ?? '短信发送异常');
  33. }
  34. return ['status'=> true, 'data'=> $data];
  35. }
  36. }