SmsService.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. 'code' => $smsCode,
  60. ];
  61. } catch (SmsException $e) {
  62. return ['error' => $e->getMessage()];
  63. } catch (NoGatewayAvailableException $e) {
  64. return ['error' => json_encode($e)];
  65. return ['error' => '发送短信失败2'];
  66. } catch (Exception $e) {
  67. return ['error' => '发送短信失败'];
  68. }
  69. }
  70. /**
  71. * 生成随机字符串用户校验验证码
  72. * @param int $length
  73. * @return string
  74. */
  75. static public function getVerifyKey(int $length = 10)
  76. {
  77. return Str::random($length);
  78. }
  79. /**
  80. * 生成短信验证码
  81. * @param int $length
  82. * @return int
  83. */
  84. static public function getSmsCode(int $length = self::DEFAULT_SMS_CODE_LENGTH)
  85. {
  86. return rand(1000, 9999);
  87. }
  88. /**
  89. * 根据验证码,verifyKey 校验是否正确
  90. * @param string $verifyKey
  91. * @param string $smsCode
  92. * @return bool
  93. * @throws SmsException
  94. */
  95. static public function checkSmsCodeByVerifyKey(string $verifyKey, string $smsCode)
  96. {
  97. if (!RedisService::redis()->exists('smsCode:verifyCode' . $verifyKey)) {
  98. throw new SmsException('验证码已过期');
  99. }
  100. $record = RedisService::redis()->get('smsCode:verifyCode' . $verifyKey);
  101. if (!json_decode($record, true)) {
  102. throw new SmsException('验证码解析失败');
  103. }
  104. $record = json_decode($record, true);
  105. if ($smsCode != $record['smsCode']) {
  106. throw new SmsException('验证码错误');
  107. }
  108. RedisService::redis()->del('smsCode:verifyCode' . $verifyKey);
  109. return true;
  110. }
  111. /**
  112. * 缓存短信验证码
  113. * @param int $mobile
  114. * @param string $smsCode
  115. * @param string $verifyKey
  116. * @param int $expTime
  117. * @return mixed
  118. */
  119. static public function cacheSmsCodeByVerifyKey(int $mobile, string $smsCode, string $verifyKey, int $expTime = self::DEFAULT_SMS_CODE_EXP_TIME)
  120. {
  121. return RedisService::redis()->SETEX('smsCode:verifyCode' . $verifyKey, $expTime, json_encode(['mobile' => $mobile, 'smsCode' => $smsCode]));
  122. }
  123. /**
  124. * 根据事件获取 短信模板ID
  125. * @param string $event
  126. * @return string
  127. * @throws SmsException
  128. */
  129. static public function getTemplateIdByEvent(string $event)
  130. {
  131. self::verifySmsEvent($event);
  132. return self::EVENTS_TO_TEMPLATE[$event];
  133. }
  134. /**
  135. * 验证发送事件
  136. * @param string $event
  137. * @return bool
  138. * @throws SmsException
  139. */
  140. static public function verifySmsEvent(string $event)
  141. {
  142. if (!array_key_exists($event, self::EVENTS_TO_TEMPLATE)) {
  143. throw new SmsException('事件类型错误');
  144. }
  145. return true;
  146. }
  147. /**
  148. * 将发送记录存到数据库以便调试
  149. * @param int $mobile
  150. * @param string $event
  151. * @param string $smsCode
  152. * @param string $verifyKey
  153. * @param $sendResult
  154. * @return mixed
  155. */
  156. static public function storeSmsRecord(int $mobile, string $event, string $smsCode, string $verifyKey, $sendResult)
  157. {
  158. return SmsRecord::create([
  159. 'mobile' => $mobile,
  160. 'event' => $event,
  161. 'sms_code' => $smsCode,
  162. 'verify_key' => $verifyKey,
  163. 'sms_result' => $sendResult
  164. ]);
  165. }
  166. }