200, 'msg' => 'success']; } $code = self::query()->where('phone', $phone)->where('code', $code)->where('status', 1)->where('is_delete', 0)->first(); if (!$code) return ['code' => 201, 'msg' => '验证码错误']; if ($code->created_at < time() - 600) return ['code' => 201, 'msg' => '验证码已过期']; $code->status = 2; $code->updated_at = time(); $code->save(); return ['code' => 200, 'msg' => 'success']; } /** * 记录验证码 * @param string $phone * @param int $code * @param int $currentLimit 限制次数 * @param int $timeOut 限制时间 * @return array */ public static function CreateCode(string $phone, int $code, int $currentLimit = 5, int $timeOut = 300): array { $time = time(); $times = self::query()->where('phone', $phone)->whereBetween('created_at', [$time - $timeOut, $time])->count(); //验证缓存,如存在则继续限制发送,时间设置 300s if (RedisUtil::getInstance(RedisKeyEnum::SEND_SMS_MOBILE, $phone)->get()) { return ['code' => 201, 'msg' => '您的发送过于频繁!']; } //5分钟之内 次数超过5次,限制发送,并记录缓存 if ($times > $currentLimit) { //每次锁定 递增 锁定时间,达到最大锁定次数则将当日无法发送 $end_time = Common::todayTimeRemain();//设置次日凌晨过期 if (!$times = RedisUtil::getInstance(RedisKeyEnum::SEND_SMS_TIMEOUT_TIMES, $phone)->tryTimes($end_time, $currentLimit)) { $timeOut = $end_time;//如果达到最大锁定次数,则设置当日过期 } else { $timeOut = $times * $timeOut;//如果未达到最大次数,则依次递增锁定时间 // 如果最大次数过期时间 超过 当日时间,则直接设置当日过期 if ($timeOut > $end_time) { $timeOut = $end_time; } } RedisUtil::getInstance(RedisKeyEnum::SEND_SMS_MOBILE, $phone)->setex('1',$timeOut); $minutes = $timeOut / 60; return ['code' => 201, 'msg' => "发送过于频繁,请{$minutes}分钟后再试"]; } $code = self::query()->insert([ 'phone' => $phone, 'code' => $code, 'status' => 1, 'created_at' => time(), 'updated_at' => time(), ]); if (!$code) return ['code' => 201, 'msg' => '发送失败']; return ['code' => 200, 'msg' => 'success']; } /** * 发送短信 * @param string $phone * @param int $code * @return bool * @throws \Twilio\Exceptions\ConfigurationException * @throws \Twilio\Exceptions\TwilioException */ public function send(string $phone, int $code, string $area_code = '+86') { if ($area_code == '+86'){ $sms = new AliSms(); if (!$sms->send($phone,['code' => $code])){ return $this->error($sms->getMessage() ?? '发送失败',$sms->getData()); } }else{ // 国外短信 $text = "【好滴用车】验证码:{$code},您正在使用好滴用车,此验证码10分钟内有效。"; $sms = new Sms(); if (!$sms->send("{$area_code}{$phone}",$text)){ return $this->error($sms->getMessage() ?? '发送失败'); } } return $this->success('发送成功',$sms->getData()); } }