json(['message' => '手机号格式错误'], 400); } $cacheData = EasySms::getSmsCodeCache($to); if ($cacheData) { if (time() - $cacheData['send_time'] <= config('sms.sendTimeout') ?? 60) { return response()->json(['message' => '短信消息发送不能太过频繁'], 400); } } $smsCode = $this->createSmsCode(); $default = [ 'content' => '您好!您的验证码为${code},请在15分钟内填写。', 'template' => 'SMS_162110318', 'data' => [ 'code' => $smsCode ], ]; $message = array_merge($default, $message); try { parent::send($to, $message, $gateways); $this->setSmsCodeCache($to, $smsCode); //缓存至redis return response()->json(['message' => '发送成功']); } catch (NoGatewayAvailableException $exception) { Log::error(var_export($exception->getResults(), 1)); return response()->json(['message' => '网关发送失败'], 400); } catch (\Throwable $throwable) { Log::error(var_export($throwable->getMessage(), 1)); return response()->json(['message' => '短信发送失败'], 400); } } /** * 设置短信验证码缓存 * @author hjc * @param $mobile * @param $smsCode */ private function setSmsCodeCache($mobile, $smsCode) { $cacheKey = 'hash_sms_' . strtolower(config('name')) . '_' . $mobile; $cacheData = [ 'mobile' => $mobile, 'code' => $smsCode, 'send_time' => time() ]; Redis::hmset($cacheKey, $cacheData); Redis::expire($cacheKey, config('sms.redisExpire') ?? 600); } /** * 获得短信验证码 * @author hjc * @param $mobile * @return mixed */ public static function getSmsCodeCache($mobile) { $cacheKey = 'hash_sms_' . strtolower(config('name')) . '_' . $mobile; $cacheData = Redis::hgetall($cacheKey); return $cacheData; } /** * 随机生成的code码 * @author hjc * @return string */ private function createSmsCode() { $num = config('sms.codeSize') ?? 4; //生成的随机数个数 $isIncludeStr = config('sms.codeIsIncludeStr') ?? false; //是否包含字符串 $value = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; if ($isIncludeStr) { $strVal = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ]; $value = array_merge($value, $strVal); } shuffle($value); //排序打乱 $key = array_rand($value, $num); $string = ''; foreach ($key as $v) { $string .= $value[$v]; } return $string; } }