跳到正文
guokit IM 文档
服务端接口(接入方后端调用)

签令牌

POST /users/{user_id}/token

无请求体。返回:

{ "code": 0, "message": "ok", "data": { "token": "eyJ0eXAiOi…", "expires_at": "2026-11-27 10:00:00" } }
  • 有效期默认 168 小时(7 天),IM 后台「IM 设置」可调(1–8760 小时)。
  • 每次调用签一个新令牌,之前签的令牌照样有效直到过期;要让旧令牌全部作废请用踢下线。
  • 令牌是不透明字符串,客户端不要解析它,以 expires_at 判断何时续签。
  • 用户不存在 → IM_USER_NOT_FOUND(先导入再签);已封禁 → IM_USER_DISABLED。

curl:

curl -X POST https://im.example.com/api/im/v1/server/users/u1001/token \
  -H "X-Api-Key: imk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

PHP(Guzzle):登录时先同步资料、再签令牌:

use GuzzleHttp\Client;

function imCall(string $method, string $path, ?array $json = null): array {
    static $http;
    $http ??= new Client(['base_uri' => 'https://im.example.com', 'timeout' => 5, 'http_errors' => false]);
    $opt = ['headers' => ['X-Api-Key' => getenv('IM_API_KEY')]];
    if ($json !== null) $opt['json'] = $json;
    $res = $http->request($method, '/api/im/v1/server' . $path, $opt);
    return json_decode((string) $res->getBody(), true) ?: ['code' => 'INTERNAL', 'message' => 'bad response'];
}

$uid = (string) $user->id;                       // 你的用户主键,须满足 [A-Za-z0-9_-]{1,64}
imCall('PUT', '/users/' . rawurlencode($uid), ['nickname' => $user->nickname, 'avatar_url' => $user->avatar]);
$r = imCall('POST', '/users/' . rawurlencode($uid) . '/token');
if ($r['code'] === 0) {
    return ['im_token' => $r['data']['token'], 'im_expires_at' => $r['data']['expires_at']];
}
throw new RuntimeException("IM 签令牌失败:{$r['code']} {$r['message']}");