SmsService.php 5.5 KB

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