SmsService.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. <?php
  2. namespace App\Services;
  3. use App\Exceptions\SmsException;
  4. use App\Models\SmsRecord;
  5. use Illuminate\Support\Facades\Redis;
  6. use Illuminate\Support\Str;
  7. use Overtrue\EasySms\EasySms;
  8. use Overtrue\EasySms\Exceptions\Exception;
  9. use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
  10. class SmsService
  11. {
  12. const EVENT_LOGIN = 100;
  13. const DEFAULT_SMS_CODE_LENGTH = 4;
  14. const DEFAULT_SMS_CODE_EXP_TIME = 120;
  15. const EVENTS_TO_TEMPLATE = [
  16. 'login' => 377532, //好邻盟短信验证码为:{1},请在{2}分钟内输入,如非本人操作,请忽略本短信
  17. 'forget' => 377532, //好邻盟短信验证码为:{1},请在{2}分钟内输入,如非本人操作,请忽略本短信
  18. ];
  19. const EVENT_ITEM_FUNCTION = [
  20. ];
  21. /**
  22. * 获取easySms配置
  23. * @return \Illuminate\Config\Repository|\Illuminate\Contracts\Foundation\Application|mixed
  24. */
  25. static public function getEasySmsConfig()
  26. {
  27. return config('easysms');
  28. }
  29. /**
  30. * 获取 easySms 实例
  31. * @return EasySms
  32. */
  33. static public function easySms()
  34. {
  35. return new EasySms(self::getEasySmsConfig());
  36. }
  37. static public function send(int $mobile, string $event, array $eventData, $user = null)
  38. {
  39. try {
  40. self::verifySmsEvent($event);
  41. $templateId = self::getTemplateIdByEvent($event);
  42. $smsCode = self::getSmsCode();
  43. $result = self::easySms()->send($mobile, [
  44. 'template' => $templateId,
  45. 'content' => 'null',
  46. 'data' => [
  47. 'code' => $smsCode,
  48. 'expTime' => 10,
  49. ]
  50. ]);
  51. //$result = true;
  52. //缓存验证码
  53. $verifyKey = self::getVerifyKey();
  54. self::cacheSmsCodeByVerifyKey($mobile, $smsCode, $verifyKey);
  55. //存入发送记录
  56. self::storeSmsRecord($mobile, $event, $smsCode, $verifyKey, $result);
  57. return [
  58. 'verifyKey' => $verifyKey,
  59. ];
  60. } catch (SmsException $e) {
  61. return ['error' => $e->getMessage()];
  62. } catch (NoGatewayAvailableException $e) {
  63. return ['error' => '发送短信失败'];
  64. } catch (Exception $e) {
  65. return ['error' => '发送短信失败'];
  66. }
  67. }
  68. /**
  69. * 生成随机字符串用户校验验证码
  70. * @param int $length
  71. * @return string
  72. */
  73. static public function getVerifyKey(int $length = 10)
  74. {
  75. return Str::random($length);
  76. }
  77. /**
  78. * 生成短信验证码
  79. * @param int $length
  80. * @return int
  81. */
  82. static public function getSmsCode(int $length = self::DEFAULT_SMS_CODE_LENGTH)
  83. {
  84. return rand(1000, 9999);
  85. }
  86. /**
  87. * 根据验证码,verifyKey 校验是否正确
  88. * @param string $verifyKey
  89. * @param string $smsCode
  90. * @return bool
  91. * @throws SmsException
  92. */
  93. static public function checkSmsCodeByVerifyKey(string $verifyKey, string $smsCode)
  94. {
  95. if (!RedisService::redis()->exists('smsCode:verifyCode' . $verifyKey)) {
  96. throw new SmsException('验证码已过期');
  97. }
  98. $record = RedisService::redis()->get('smsCode:verifyCode' . $verifyKey);
  99. if (!json_decode($record, true)) {
  100. throw new SmsException('验证码解析失败');
  101. }
  102. $record = json_decode($record, true);
  103. if ($smsCode != $record['smsCode']) {
  104. throw new SmsException('验证码错误');
  105. }
  106. RedisService::redis()->del('smsCode:verifyCode' . $verifyKey);
  107. return true;
  108. }
  109. /**
  110. * 缓存短信验证码
  111. * @param int $mobile
  112. * @param string $smsCode
  113. * @param string $verifyKey
  114. * @param int $expTime
  115. * @return mixed
  116. */
  117. static public function cacheSmsCodeByVerifyKey(int $mobile, string $smsCode, string $verifyKey, int $expTime = self::DEFAULT_SMS_CODE_EXP_TIME)
  118. {
  119. return RedisService::redis()->SETEX('smsCode:verifyCode' . $verifyKey, $expTime, json_encode(['mobile' => $mobile, 'smsCode' => $smsCode]));
  120. }
  121. /**
  122. * 根据事件获取 短信模板ID
  123. * @param string $event
  124. * @return string
  125. * @throws SmsException
  126. */
  127. static public function getTemplateIdByEvent(string $event)
  128. {
  129. self::verifySmsEvent($event);
  130. return self::EVENTS_TO_TEMPLATE[$event];
  131. }
  132. /**
  133. * 验证发送事件
  134. * @param string $event
  135. * @return bool
  136. * @throws SmsException
  137. */
  138. static public function verifySmsEvent(string $event)
  139. {
  140. if (!array_key_exists($event, self::EVENTS_TO_TEMPLATE)) {
  141. throw new SmsException('事件类型错误');
  142. }
  143. return true;
  144. }
  145. /**
  146. * 将发送记录存到数据库以便调试
  147. * @param int $mobile
  148. * @param string $event
  149. * @param string $smsCode
  150. * @param string $verifyKey
  151. * @param $sendResult
  152. * @return mixed
  153. */
  154. static public function storeSmsRecord(int $mobile, string $event, string $smsCode, string $verifyKey, $sendResult)
  155. {
  156. return SmsRecord::create([
  157. 'mobile' => $mobile,
  158. 'event' => $event,
  159. 'sms_code' => $smsCode,
  160. 'verify_key' => $verifyKey,
  161. 'sms_result' => $sendResult
  162. ]);
  163. }
  164. }