请求签名
每个请求都要签名,包括 GET。签名用你的 Secret 计算 HMAC-SHA256,结果是 64 位小写十六进制。
| 请求头 | 规则 |
|---|---|
X-TE-Key | Key ID:tek_ + 24 位小写十六进制 |
X-TE-Timestamp | Unix 秒,9–11 位数字;与平台时间相差超过 300 秒拒绝 |
X-TE-Nonce | 16–64 位 A-Z a-z 0-9 _ -,每个请求新生成;通过验签后即作废,任何重试都要新 nonce、新签名 |
X-TE-Signature | 64 位小写十六进制:用 Secret 对待签名串计算 HMAC-SHA256 |
Idempotency-Key | 8–128 位 A-Z a-z 0-9 _ - : .;下分、链上出款必填,担保收款单的确认交付和退款可选 |
Content-Type | 有请求体时发 application/json |
待签名串
5 行用换行符(\n)连接,末尾不加换行:
Text
METHOD
PATH_WITH_QUERY
X-TE-Timestamp
X-TE-Nonce
SHA256_HEX(raw body bytes)
- 请求方法,大写,例如
POST; - 实际发送的完整路径,含查询串,按发送时的 URL 编码,例如
/partner/v1/collect/deposits?customer_ref=u1001; X-TE-Timestamp的值;X-TE-Nonce的值;- 请求体原始字节的 SHA-256 小写十六进制;空请求体(例如
GET)为e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855。
签名后不要再改请求体(包括重新格式化 JSON):发送的字节必须和计算哈希的字节完全一致。查询串先按 URL 编码拼好,再用同一个字符串签名和发送。
测试向量
用下面的示例值检查你的实现,结果应该完全相同。示例 Secret 不是真实密钥。
Test vector
Secret tes_example_do_not_use
Method POST
Path /partner/v1/collect/orders
Timestamp 1767225600
Nonce 3f9c2a7d0b1e4c55a6d7e8f901234567
Body {"external_ref":"ORDER-1001","amount":"75.24"}
Body SHA-256 3132daec2adb29c527e1fc7f90423e3d7926a3e1909b9df8313b2d7e441a150b
String to sign:
POST
/partner/v1/collect/orders
1767225600
3f9c2a7d0b1e4c55a6d7e8f901234567
3132daec2adb29c527e1fc7f90423e3d7926a3e1909b9df8313b2d7e441a150b
X-TE-Signature 7b1d2df3bc45c50781c75325b7d69abd1366a48d65f0a9161025ebc2426b3e19
示例:curl / Python / Node.js / PHP
四个示例实现同一个签名算法,TE_KEY_ID、TE_SECRET 从环境变量读取,不要写进代码。curl 示例的 Secret 会出现在进程列表里,只在你自己的服务器上调试时用。
curl + openssl (bash)
#!/usr/bin/env bash
# Sign one request with openssl and send it with curl. TE_KEY_ID and TE_SECRET come from the environment.
set -euo pipefail
API="${TE_API:-https://open.e8qianbao.com}"
METHOD="POST"
REQ_PATH="/partner/v1/collect/orders" # with the query string, exactly as sent
BODY='{"external_ref":"ORDER-1001","amount":"75.24"}' # GET: BODY='' and drop --data-binary
TS=$(date +%s)
NONCE=$(openssl rand -hex 16)
BODY_SHA=$(printf '%s' "$BODY" | openssl dgst -sha256 -r | cut -d' ' -f1)
SIG=$(printf '%s\n%s\n%s\n%s\n%s' "$METHOD" "$REQ_PATH" "$TS" "$NONCE" "$BODY_SHA" \
| openssl dgst -sha256 -hmac "$TE_SECRET" -r | cut -d' ' -f1)
curl -sS -X "$METHOD" "$API$REQ_PATH" \
-H "Content-Type: application/json" \
-H "X-TE-Key: $TE_KEY_ID" \
-H "X-TE-Timestamp: $TS" \
-H "X-TE-Nonce: $NONCE" \
-H "X-TE-Signature: $SIG" \
--data-binary "$BODY"
Python 3 (standard library)
import hashlib
import hmac
import json
import os
import secrets
import time
import urllib.error
import urllib.request
API = os.environ.get("TE_API", "https://open.e8qianbao.com")
KEY_ID, SECRET = os.environ["TE_KEY_ID"], os.environ["TE_SECRET"]
def call(method, path, payload=None, idempotency_key=None):
"""path includes the query string exactly as sent, e.g. /partner/v1/collect/deposits?limit=50"""
method = method.upper()
body = b"" if payload is None else json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode()
ts, nonce = str(int(time.time())), secrets.token_hex(16)
canonical = "\n".join([method, path, ts, nonce, hashlib.sha256(body).hexdigest()])
headers = {
"Content-Type": "application/json",
"X-TE-Key": KEY_ID,
"X-TE-Timestamp": ts,
"X-TE-Nonce": nonce,
"X-TE-Signature": hmac.new(SECRET.encode(), canonical.encode(), hashlib.sha256).hexdigest(),
}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
req = urllib.request.Request(API + path, data=body or None, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=10) as r:
status, raw = r.status, r.read()
except urllib.error.HTTPError as e:
status, raw = e.code, e.read()
try:
return status, json.loads(raw or b"{}")
except ValueError: # an HTML error page from a proxy
return status, {"success": False, "code": "NON_JSON_RESPONSE"}
status, doc = call("POST", "/partner/v1/collect/orders", {"external_ref": "ORDER-1001", "amount": "75.24"})
print(status, doc["data"]["checkout_url"] if doc.get("success") else doc)
Node.js 18+
// Node.js 18+ (built-in fetch and crypto). TE_KEY_ID and TE_SECRET come from the environment.
const crypto = require("node:crypto");
const API = process.env.TE_API || "https://open.e8qianbao.com";
const KEY_ID = process.env.TE_KEY_ID;
const SECRET = process.env.TE_SECRET;
async function call(method, path, payload, idempotencyKey) {
// path includes the query string exactly as sent, e.g. /partner/v1/collect/deposits?limit=50
method = method.toUpperCase();
const body = payload === undefined ? "" : JSON.stringify(payload);
const ts = Math.floor(Date.now() / 1000).toString();
const nonce = crypto.randomBytes(16).toString("hex");
const bodySha = crypto.createHash("sha256").update(body, "utf8").digest("hex");
const canonical = [method, path, ts, nonce, bodySha].join("\n");
const headers = {
"Content-Type": "application/json",
"X-TE-Key": KEY_ID,
"X-TE-Timestamp": ts,
"X-TE-Nonce": nonce,
"X-TE-Signature": crypto.createHmac("sha256", SECRET).update(canonical, "utf8").digest("hex"),
};
if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
const res = await fetch(API + path, { method, headers, body: body === "" ? undefined : body });
return { status: res.status, doc: await res.json().catch(() => ({ success: false })) };
}
call("POST", "/partner/v1/collect/orders", { external_ref: "ORDER-1001", amount: "75.24" }).then(({ status, doc }) =>
console.log(status, doc.success ? doc.data.checkout_url : doc)
);
PHP 7.4+ (curl)
<?php
// PHP 7.4+ with the curl extension. TE_KEY_ID and TE_SECRET come from the environment.
function e8_call(string $method, string $path, ?array $payload = null, ?string $idempotencyKey = null): array
{
// $path includes the query string exactly as sent, e.g. /partner/v1/collect/deposits?limit=50
$api = getenv('TE_API') ?: 'https://open.e8qianbao.com';
$method = strtoupper($method);
$body = $payload === null ? '' : json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$ts = (string) time();
$nonce = bin2hex(random_bytes(16));
$canonical = implode("\n", [$method, $path, $ts, $nonce, hash('sha256', $body)]);
$headers = [
'Content-Type: application/json',
'X-TE-Key: ' . getenv('TE_KEY_ID'),
'X-TE-Timestamp: ' . $ts,
'X-TE-Nonce: ' . $nonce,
'X-TE-Signature: ' . hash_hmac('sha256', $canonical, getenv('TE_SECRET')),
];
if ($idempotencyKey !== null) {
$headers[] = 'Idempotency-Key: ' . $idempotencyKey;
}
$ch = curl_init($api . $path);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
if ($body !== '') {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
$raw = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return [$status, json_decode((string) $raw, true)];
}
[$status, $doc] = e8_call('POST', '/partner/v1/collect/orders', ['external_ref' => 'ORDER-1001', 'amount' => '75.24']);
echo $status, ' ', ($doc['success'] ?? false) ? $doc['data']['checkout_url'] : json_encode($doc), PHP_EOL;
服务端校验顺序与自检
签名头格式 → 时间戳 → 按来源 IP 限流 → 密钥存在、未停用、未过期 → 商户主账号正常 → 客户端已启用 → 商户正常营业 → 来源 IP 在白名单 → 签名 → nonce 未用过(重放一律拒绝)→ 按客户端限流 → 授权范围。
写好签名后先调用 GET /partner/v1/me 自检,任何有效密钥都能调用。它返回 client_code、merchant_code、scopes、key_id、key_expires_at(2026-11-29 之前建的长期有效密钥为 null)、rate_limit_per_min、environment(正式环境为 chain)、notice;收款商户另有 payout_enabled(接口出款是否已打开)和 checkout_mode(付款链接现在实际打开的方式)。
常见签名错误
| 错误码 | HTTP | 含义 |
|---|---|---|
SIGNATURE_REQUIRED | 401 | 缺少签名头或格式不对 |
TIMESTAMP_EXPIRED | 401 | 时间戳超出 ±300 秒,检查服务器时间同步 |
INVALID_SIGNATURE | 401 | 方法、路径(含查询串)、时间戳、nonce、请求体任一和签名不一致;常见原因是签名后又重新序列化了 JSON |
NONCE_REPLAYED | 401 | nonce 已用过;任何重试都要新 nonce、新签名 |
IP_NOT_ALLOWED | 403 | 来源 IP 不在白名单 |
全部错误码见限流与错误码。