'注册', self::TYPE_LOGIN => '登录', self::TYPE_RESET_PASSWORD => '找回密码', self::TYPE_CHANGE_MOBILE => '修改手机', self::TYPE_CHANGE_EMAIL => '修改邮箱', self::TYPE_OTHER => '其他' ]; } /** * 获取状态列表 * @return array */ public static function getStatusList(): array { return [ self::STATUS_UNUSED => '未使用', self::STATUS_USED => '已使用', self::STATUS_EXPIRED => '已失效' ]; } /** * 获取发送渠道列表 * @return array */ public static function getChannelList(): array { return [ self::CHANNEL_SMS => '短信', self::CHANNEL_EMAIL => '邮件' ]; } /** * 创建验证码 * @param string $account 账号 * @param string $code 验证码 * @param int $codeType 验证码类型 * @param string $channel 发送渠道 * @param string $ipAddress IP地址 * @param int $userId 用户ID * @param int $expireMinutes 过期时间(分钟) * @return UserVerificationCode */ public static function createCode( string $account, string $code, int $codeType, string $channel, string $ipAddress = '', int $userId = 0, int $expireMinutes = 5 ): self { $data = [ 'user_id' => $userId, 'account' => $account, 'code' => $code, 'code_type' => $codeType, 'channel' => $channel, 'ip_address' => $ipAddress, 'status' => self::STATUS_UNUSED, 'expired_at' => date('Y-m-d H:i:s', time() + $expireMinutes * 60) ]; return self::create($data); } /** * 验证验证码 * @param string $account 账号 * @param string $code 验证码 * @param int $codeType 验证码类型 * @return bool */ public static function verifyCode(string $account, string $code, int $codeType): bool { $verificationCode = self::where([ 'account' => $account, 'code' => $code, 'code_type' => $codeType, 'status' => self::STATUS_UNUSED ]) ->where('expired_at', '>', date('Y-m-d H:i:s')) ->find(); if (!$verificationCode) { return false; } // 更新验证码状态 $verificationCode->status = self::STATUS_USED; $verificationCode->used_at = date('Y-m-d H:i:s'); return $verificationCode->save(); } /** * 使验证码失效 * @param string $account 账号 * @param int $codeType 验证码类型 * @return bool */ public static function invalidateCode(string $account, int $codeType): bool { return self::where([ 'account' => $account, 'code_type' => $codeType, 'status' => self::STATUS_UNUSED ])->update([ 'status' => self::STATUS_EXPIRED ]); } /** * 获取最近的验证码 * @param string $account 账号 * @param int $codeType 验证码类型 * @return UserVerificationCode|null */ public static function getLatestCode(string $account, int $codeType): ?self { return self::where([ 'account' => $account, 'code_type' => $codeType, 'status' => self::STATUS_UNUSED ]) ->where('expired_at', '>', date('Y-m-d H:i:s')) ->order('id', 'desc') ->find(); } }