服务端 SDK

服务端接口采用标准 HTTP + JSON,签名规则简单(SHA1),任何语言都可以直接调用。本页提供 Node.js / Java / Python / Go 的签名样例与封装建议。

已有可用实物

Node.js App Server SDK 已交付:@ni-paas-im/server-sdk(sdk/server-node),封装 Open API + Admin API、内置签名/重试/错误映射,并有真实服务端冒烟。见 Node.js App Server SDK。

Java / Go / PHP / Python 没有实物包;推荐由 OpenAPI 3.1 导出生成,并自行补签名拦截器(页面内含步骤与降级注意事项)。

签名算法​

Text
Signature = hex_lower(sha1(AppSecret + Nonce + Timestamp))

请求头需要 App-Key、Nonce、Timestamp、Signature 与 Content-Type;时间戳允许 ±5 分钟误差。

多语言签名示例​

import { createHash, randomBytes } from 'node:crypto';

export function signHeaders(appKey, appSecret) {
  const nonce = randomBytes(16).toString('hex');
  const timestamp = String(Date.now());
  const signature = createHash('sha1')
    .update(appSecret + nonce + timestamp)
    .digest('hex');
  return { 'App-Key': appKey, Nonce: nonce, Timestamp: timestamp, Signature: signature };
}

const res = await fetch('https://im.example.com/open/api/v1/user/register', {
  method: 'POST',
  headers: { 'content-type': 'application/json', ...signHeaders(APP_KEY, APP_SECRET) },
  body: JSON.stringify({ userId: 'user1', name: 'Alice' }),
});
const json = await res.json();
if (json.code !== 0) throw new Error(json.msg);
import java.security.MessageDigest;
import java.util.HexFormat;

static String signature(String secret, String nonce, String timestamp) throws Exception {
    var md = MessageDigest.getInstance("SHA-1");
    var digest = md.digest((secret + nonce + timestamp).getBytes(java.nio.charset.StandardCharsets.UTF_8));
    return HexFormat.of().formatHex(digest);
}
import hashlib, secrets, time

def sign_headers(app_key: str, app_secret: str) -> dict:
    nonce = secrets.token_hex(16)
    timestamp = str(int(time.time() * 1000))
    signature = hashlib.sha1((app_secret + nonce + timestamp).encode()).hexdigest()
    return {"App-Key": app_key, "Nonce": nonce, "Timestamp": timestamp, "Signature": signature}
APP_KEY=YOUR_APP_KEY
APP_SECRET=YOUR_APP_SECRET
NONCE=$(openssl rand -hex 16)
TS=$(date +%s%3N)
SIG=$(printf "%s" "$APP_SECRET$NONCE$TS" | openssl sha1 | awk '{print $2}')

curl -sS https://im.example.com/open/api/v1/user/register \
  -H "Content-Type: application/json" \
  -H "App-Key: $APP_KEY" -H "Nonce: $NONCE" -H "Timestamp: $TS" -H "Signature: $SIG" \
  -d '{"userId":"user1","name":"Alice"}'

封装建议​

  • 统一处理 code !== 0 的错误与重试(5xx 与可重试错误按指数退避);
  • 所有请求携带 X-Request-Id,便于在控制台按请求 ID 追查;
  • 写操作使用业务幂等键(如 clientMsgId / requestId);
  • 不要在客户端持有 AppSecret。

相关文档​