SmsService.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace App\Services;
  3. use Overtrue\EasySms\EasySms;
  4. use Illuminate\Support\Facades\Log;
  5. class SmsService
  6. {
  7. protected $easySms;
  8. public function __construct()
  9. {
  10. $this->easySms = new EasySms(config('sms'));
  11. }
  12. /**
  13. * 发送验证码短信
  14. *
  15. * @param string $mobile 手机号
  16. * @param string $code 验证码
  17. * @return bool
  18. */
  19. public function sendVerifyCode(string $mobile, string $code): bool
  20. {
  21. try {
  22. $templateId = env('TENCENT_SMS_TEMPLATE_ID');
  23. $result = $this->easySms->send($mobile, [
  24. 'template' => $templateId,
  25. 'data' => [
  26. $code,
  27. 5 // 验证码有效期(分钟)
  28. ],
  29. ]);
  30. Log::info('SMS sent', [
  31. 'mobile' => $mobile,
  32. 'code' => $code,
  33. 'result' => $result
  34. ]);
  35. return true;
  36. } catch (\Exception $e) {
  37. Log::error('SMS sending failed', [
  38. 'mobile' => $mobile,
  39. 'error' => $e->getMessage()
  40. ]);
  41. throw $e;
  42. }
  43. }
  44. }