Authentication and signing
About 925 words
v1 draft
This page is part of the draft v1 integration contract; details may change along with the integration checklist, so rely on the official checklist published in the portal.
Credentials
Each shop has a pair of credentials, generated and rotated in the portal under "Shop details":
| Credential | Purpose | Where to store it |
|---|---|---|
| API Key | Identifies the caller; sent with the request headers | Server-side configuration is fine |
| API Secret | Computes request signatures; never sent with requests | Server-side secret storage only; never expose it in front-end code |
A shop has only one valid Secret at any time. During rotation the new key takes effect first, while the old key keeps working through a grace period and then expires automatically.
Request headers
| Header | Required | Example | Description |
|---|---|---|---|
X-Xstock-Api-Key | Yes | xs_live_2f7c... | Shop API Key |
X-Xstock-Timestamp | Yes | 1795000000 | Current Unix timestamp (seconds); must be within 300 seconds of platform time |
X-Xstock-Signature | Yes | 9f2c1d... | Lowercase hexadecimal HMAC-SHA256 |
Content-Type | POST only | application/json; charset=utf-8 | Fixed for write commands; not needed for GET queries |
Signing algorithm
The two request shapes use different strings to sign.
Write commands (POST, jcmd in the request body)
body_digest = SHA256(raw_request_body) 的十六进制小写
string_to_sign = timestamp + "\n" + cmd + "\n" + body_digest
signature = HMAC_SHA256(secret, string_to_sign) 的十六进制小写Query commands (GET, command in the path, fields in the query)
query_digest = SHA256(canonical_query) 的十六进制小写
string_to_sign = timestamp + "\n" + cmd + "\n" + query_digest
signature = HMAC_SHA256(secret, string_to_sign) 的十六进制小写cmd comes from the path /dist/api/v1/{cmd}, and canonical_query is the canonical form of the query:
- Take all business fields from the query (excluding signing-related headers).
- Sort them by field name in ASCII ascending order.
- For arrays, first join the values into a single value with a half-width comma
,(the comma itself is not encoded); percent-encode the remaining characters per RFC 3986 (use%20for spaces, not+). - Join them with
&in the forma=1&b=2. When there are no parameters,canonical_queryis an empty string and the digest isSHA256("").
Key points:
- For POST,
raw_request_bodymust be the exact raw bytes actually sent; do not parse and re-serialize it (field order and whitespace both change the digest). - For GET, build
canonical_queryyourself following steps 2–4 before computing the digest. Do not use the raw query string produced by a browser or HTTP library — parameter order and whether commas in arrays get encoded both affect the digest. - For POST,
cmdcomes from the request body and must match the command in the path; for GET,cmdcomes from the path. timestampmust be identical to the value in the request header.- Compare signatures in constant time.
Examples
curl (GET query)
TS=$(date +%s)
QUERY="page=1&page_size=20"
DIGEST=$(printf '%s' "$QUERY" | openssl dgst -sha256 -hex | sed 's/^.* //')
SIG=$(printf '%s\n%s\n%s' "$TS" "get_goods" "$DIGEST" | openssl dgst -sha256 -hmac "$XS_SECRET" -hex | sed 's/^.* //')
curl -sS "https://api.xstock.example/dist/api/v1/get_goods?$QUERY" \
-H "X-Xstock-Api-Key: $XS_KEY" \
-H "X-Xstock-Timestamp: $TS" \
-H "X-Xstock-Signature: $SIG"curl (POST write)
BODY='{"id":"demo-2","cmd":"post_order","data":{"req_id":"demo-0001","items":[{"sku_id":1001,"qty":"1"}]},"stamp":1795000000}'
TS=$(date +%s)
DIGEST=$(printf '%s' "$BODY" | openssl dgst -sha256 -hex | sed 's/^.* //')
SIG=$(printf '%s\n%s\n%s' "$TS" "post_order" "$DIGEST" | openssl dgst -sha256 -hmac "$XS_SECRET" -hex | sed 's/^.* //')
curl -sS https://api.xstock.example/dist/api/v1/post_order \
-H 'Content-Type: application/json; charset=utf-8' \
-H "X-Xstock-Api-Key: $XS_KEY" \
-H "X-Xstock-Timestamp: $TS" \
-H "X-Xstock-Signature: $SIG" \
--data-binary "$BODY"Node.js (GET query)
import { createHash, createHmac } from 'node:crypto'
function canonicalize(params) {
return Object.keys(params)
.sort()
.map((key) => {
const raw = Array.isArray(params[key]) ? params[key].join(',') : String(params[key])
// 逗号是数组分隔符,不参与编码
const value = encodeURIComponent(raw).replace(/%2C/g, ',')
return `${encodeURIComponent(key)}=${value}`
})
.join('&')
}
const timestamp = Math.floor(Date.now() / 1000).toString()
const query = canonicalize({ page: 1, page_size: 20 })
const digest = createHash('sha256').update(query).digest('hex')
const signature = createHmac('sha256', process.env.XS_SECRET)
.update(`${timestamp}\nget_goods\n${digest}`)
.digest('hex')
const res = await fetch(
`https://api.xstock.example/dist/api/v1/get_goods?${query}`,
{
headers: {
'X-Xstock-Api-Key': process.env.XS_KEY,
'X-Xstock-Timestamp': timestamp,
'X-Xstock-Signature': signature,
},
},
)C# (POST write)
using System.Security.Cryptography;
using System.Text;
static string Sign(string secret, string timestamp, string cmd, string rawBody)
{
var bodyDigest = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(rawBody))).ToLowerInvariant();
var stringToSign = $"{timestamp}\n{cmd}\n{bodyDigest}";
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
return Convert.ToHexString(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign))).ToLowerInvariant();
}
// POST 到 https://api.xstock.example/dist/api/v1/post_orderAuthentication failures
| HTTP | code | Cause | Action |
|---|---|---|---|
| 401 | 1002 | Missing authentication header | Check whether a gateway strips the headers |
| 401 | 1002 | Timestamp out of range | Correct the system clock and sync via NTP |
| 401 | 1002 | Signature mismatch | Recompute the digest from the raw request body |
| 401 | 1002 | Key revoked | Rotate in the portal, then update your configuration |
| 403 | 1003 | Shop lacks permission for this command | Enable the permission in the portal |
Security recommendations
- Keep the Secret server-side only, in environment variables or a secrets manager; never commit it to a repository.
- Serve callback URLs over HTTPS and verify signatures on the receiving end.
- Enabling an IP allowlist significantly reduces the risk after a key leak.
- Rotate keys regularly, and keep a short dual-key transition during rotation to avoid failed cutovers.