SmsService.php 5.7 KB

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