PHP code example of wiseadmin / wise-api

1. Go to this page and download the library: Download wiseadmin/wise-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wiseadmin / wise-api example snippets


// config/wise-api.php
return [
    'jwt' => [
        'algorithm'   => 'HS256',
        'secret'      => env('JWT_SECRET', 'change-me'),
        'ttl'         => 7200,
        'refresh_ttl' => 1800,
    ],
    'sign' => [
        'enable'        => true,
        'secret'        => env('SIGN_SECRET', 'change-me'),
        'timestamp_ttl' => 300,
        'enable_nonce'  => true,
    ],
    'rate_limit' => [
        'enable'    => true,
        'algorithm' => 'token_bucket',
        'key_by'    => 'combine',
        'default'   => ['algorithm' => 'token_bucket', 'capacity' => 60, 'rate' => 1.0],
        'groups'    => [
            // 'api/v1/login' => ['algorithm' => 'sliding_window', 'limit' => 10, 'window' => 60],
        ],
    ],
    // ...
];

namespace app\api\controller\v1;

use think\model\User;
use wise\api\ApiController;
use wise\api\middleware\RateLimitMiddleware;
use wise\api\middleware\SignVerifyMiddleware;
use wise\api\middleware\JwtAuthMiddleware;

class UserController extends ApiController
{
    /**
     * 中间件栈
     * - 限流:60 个令牌,1 个/秒
     * - 签名验证
     * - JWT 鉴权
     */
    protected $middleware = [
        RateLimitMiddleware::class . ':60,1',
        SignVerifyMiddleware::class,
        JwtAuthMiddleware::class,
    ];

    /**
     * GET /api/v1/users
     */
    public function index()
    {
        $params = $this->validateRequest([
            'page'      => 'integer|egt:1',
            'page_size' => 'integer|between:1,100',
            'keyword'   => 'chs',
        ]);
        $query = User::order('id desc');
        if (!empty($params['keyword'])) {
            $query->where('name', 'like', "%{$params['keyword']}%");
        }
        return $this->paginate($query, (int) ($params['page_size'] ?? 15));
    }

    /**
     * GET /api/v1/users/5?fields=id,name,email
     */
    public function read($id)
    {
        $user = User::find($id);
        if (!$user) {
            return $this->error(4001, '用户不存在');
        }
        $fields = $this->resolveFields(['id', 'name', 'email', 'create_time']);
        return $this->success($this->allowFields($fields, $user));
    }

    /**
     * POST /api/v1/users
     */
    public function save()
    {
        $params = $this->validateRequest([
            'name'  => '

// app/api/route/v1.php
use think\Route;

Route::group('v1', function () {
    Route::resource('users', 'v1.User');
});

use wise\api\facade\Jwt;

// 签发
$token = Jwt::issue($userId, ['role' => 'admin', 'custom_claims' => ['role' => 'admin']]);
// → eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.xxx.yyy

// 解析(带完整校验)
$payload = Jwt::parse($token);
echo $payload['sub']; // 用户 ID
echo $payload['role']; // 业务自定义字段

// 安全解析(失败返回 null)
$payload = Jwt::tryParse($token);

$user = $this->currentUser();
// ['id' => '123', 'payload' => [...]]

use wise\api\sign\SignVerifier;

$verifier = new SignVerifier();
$params = ['app_key' => 'demo', 'timestamp' => time(), 'nonce' => 'xyz', 'foo' => 'bar'];
$sign = $verifier->sign($params, 'your-secret');
// 客户端将 sign 追加到 params 后发起请求即可

// config/wise-api.php
'rate_limit' => [
    'groups' => [
        'api/v1/login' => ['algorithm' => 'sliding_window', 'limit' => 10, 'window' => 60],
        'api/v1/sms'   => ['algorithm' => 'token_bucket',   'capacity' => 5, 'rate' => 0.1],
    ],
],

src/
├── ApiController.php          控制器基类
├── Service.php                服务注册
├── helper.php                 助手函数
├── middleware/                限流 / 签名 / JWT 中间件
├── jwt/                       JWT 核心 + HS256 / RS256
├── rate/                      令牌桶 / 滑动窗口 / 协调者
├── sign/                      签名验证器
├── response/                  统一响应 + 错误码枚举
├── debug/                     调试面板
├── exception/                 JWT 异常
└── facade/                    JwtFacade
config/wise-api.php             配置文件
route/wise.php                 默认路由(debug 模式)