ysy/hyperf-cache

Hyperf 生成诸如邀请链接中用的过期验证code

Installs: 1

Dependents: 0

Suggesters: 0

Security: 0

pkg:composer/ysy/hyperf-cache

1.0.0 2025-12-03 09:38 UTC

This package is not auto-updated.

Last update: 2025-12-04 07:59:39 UTC


README

Hyperf 专用过期验证码生成工具,适用于邀请链接、临时验证等场景,支持自定义过期时间、扩展数据存储。

安装

composer require ysy/hyperf-cache

依赖说明

  • PHP >= 8.2
  • Hyperf 框架(需启用 hyperf/cache 组件,确保缓存配置正常)

核心功能

  1. 生成唯一验证码(支持前缀防冲突)
  2. 缓存存储扩展数据(如用户ID、业务标识等)
  3. 验证码有效性校验
  4. 手动作废验证码

使用示例

1. 控制器完整示例(直接复用)

<?php

declare(strict_types=1);

namespace App\Controller\Pro;

use App\Middleware\OaTokenAuthMiddleware;
use Ysy\Hyperf\Cache\CacheService; // 引入包内服务
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Ysy\Hyperf\PermissionAnnotation\Annotation\Permission;
use Ysy\Hyperf\PermissionAnnotation\Middleware\PermissionMiddleware;
use Ysy\Hyperf\Traits\ExceptionHandlerTrait;

#[AutoController]
class InvitingWriteController
{
    use ExceptionHandlerTrait;

    /**
     * 生成邀请链接(带验证码)
     * @param RequestInterface $request
     * @param CacheService $cacheService 依赖注入
     * @return array
     */
    #[PostMapping]
    #[Middlewares([OaTokenAuthMiddleware::class, PermissionMiddleware::class])]
    #[Permission('regInfoAdd:add', name: '注册信息表邀请')]
    public function regInfoAdd(RequestInterface $request, CacheService $cacheService)
    {
        try {
            // 接收请求参数
            $input = $request->all();
            
            // 必传参数校验(实际项目建议补充)
            if (empty($input['url']) || empty($input['id']) || empty($input['invalid_type'])) {
                return ['code' => 400, 'msg' => '缺少必要参数'];
            }

            // 生成验证码并存储缓存
            $code = $cacheService->create(
                extData: ['id' => $input['id']], // 自定义扩展数据(可传任意键值对)
                expire: $this->calculateExpiration($input['invalid_type']), // 过期时间(秒)
                perfix: 'invite' // 验证码前缀(防不同业务冲突)
            );

            // 拼接邀请链接(urlencode处理特殊字符)
            $inviteUrl = $input['url'] . '?code=' . urlencode($code);

            return [
                'code' => 200,
                'msg' => '生成成功',
                'url' => $inviteUrl,
                'code' => $code // 可选返回验证码
            ];
        } catch (\Throwable $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 校验验证码有效性
     * @param RequestInterface $request
     * @param CacheService $cacheService
     * @return array
     */
    #[GetMapping]
    public function checkCode(RequestInterface $request, CacheService $cacheService)
    {
        try {
            $code = $request->input('code');
            if (empty($code)) {
                return ['code' => 400, 'msg' => '验证码不能为空'];
            }

            // 验证并获取存储的全部数据
            $cacheData = $cacheService->verify($code);

            return [
                'code' => $cacheData ? 200 : 400,
                'msg' => $cacheData ? '验证通过' : '链接无效或已过期',
                'data' => $cacheData // 有效时返回扩展数据+基础字段(id、perm、ctime)
            ];
        } catch (\Throwable $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 作废验证码(示例:如用户取消邀请)
     * @param RequestInterface $request
     * @param CacheService $cacheService
     * @return array
     */
    #[PostMapping('invalidCode')]
    public function invalidCode(RequestInterface $request, CacheService $cacheService)
    {
        try {
            $code = $request->input('code');
            if (empty($code)) {
                return ['code' => 400, 'msg' => '验证码不能为空'];
            }

            $result = $cacheService->invalid($code);
            return [
                'code' => $result ? 200 : 400,
                'msg' => $result ? '作废成功' : '作废失败(验证码不存在)'
            ];
        } catch (\Throwable $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 计算过期时间(按 invalid_type 映射)
     * @param string $invalidType 0=永久有效,1=1天,7=7天,30=30天
     * @return int 过期秒数
     */
    private function calculateExpiration(string $invalidType): int
    {
        return match ($invalidType) {
            '0' => 0,          // 永久有效
            '1' => 86400,      // 1天 = 24*60*60 秒
            '7' => 604800,     // 7天
            '30' => 2592000,   // 30天
            default => 86400,  // 默认1天
        };
    }
}

2. 请求参数说明

生成邀请链接(POST)

参数名类型说明必传
urlstring基础链接(如 https://xxx.com/reg
idint/string业务标识(如用户ID、活动ID)
invalid_typestring过期类型(0=永久,1=1天,7=7天,30=30天)

校验验证码(GET)

参数名类型说明必传
codestring生成的验证码(url解码后)

作废验证码(POST)

参数名类型说明必传
codestring要作废的验证码

3. 返回结果示例

生成成功

{
  "code": 200,
  "msg": "生成成功",
  "url": "https://xxx.com/reg?code=invite_1a2b3c",
  "code": "invite_1a2b3c"
}

验证通过

{
  "code": 200,
  "msg": "验证通过",
  "data": {
    "id": 10086,
    "perm": false,
    "ctime": 1735689600
  }
}

验证失败

{
  "code": 400,
  "msg": "链接无效或已过期",
  "data": null
}

API 说明

CacheService 核心方法

方法名作用参数说明返回值
create生成验证码并存储$extData: 扩展数据(数组)、$expire: 过期秒数(0=永久)、$perfix: 前缀(可选)生成的唯一验证码(string)
verify验证码有效性校验$code: 验证码有效返回缓存数据(array),无效返回null
invalid作废验证码(删缓存)$code: 验证码成功返回true,失败返回false

注意事项

  1. 缓存依赖 Hyperf 的 cache 组件,请确保 config/autoload/cache.php 配置正确(如驱动、前缀等)。
  2. 验证码拼接链接时必须用 urlencode 处理,避免特殊字符(如 &、=)导致链接失效。
  3. 扩展数据支持任意键值对,可根据业务需求存储(如 ['uid'=>10086, 'activity_id'=>5, 'source'=>'wechat'])。
  4. 永久有效($expire=0)的验证码需手动调用 invalid 方法作废,否则会一直存在缓存中。
  5. 生成验证码时会自动防重复(通过 cache->has 校验),确保唯一性。