跳到主要内容

加密与签名

服务端 Studio 脚本可以使用 Node 内置 crypto API,处理第三方集成中常见的签名、哈希和请求 nonce。

常用方法​

方法说明
createHash(algorithm)创建哈希计算器;常用算法是 sha256
createHmac(algorithm, secret)使用密钥创建 HMAC 签名器;常用算法是 sha256
.update(value, encoding)添加参与哈希或签名的文本或字节;普通文本使用 utf8
.digest('hex')输出小写十六进制文本;很多接口签名使用这种格式
.digest('base64')输出 Base64 文本;部分接口要求 Base64 签名
randomUUID()生成 UUID;外部接口支持时可作为 nonce、request ID 或幂等键
new Date().toISOString()生成 ISO 时间戳,常用于签名请求
JSON.stringify(value)生成参与签名的精确 JSON 请求体文本

SHA-256 哈希​

import { createHash } from 'node:crypto';

const hash = createHash('sha256')
.update('content to sign', 'utf8')
.digest('hex');

HMAC-SHA256 签名​

import { createHmac } from 'node:crypto';

const timestamp = new Date().toISOString();
const bodyText = JSON.stringify({ orderNo: 'SO-1001' });
const signingContent = `${timestamp}\n${bodyText}`;

const signature = createHmac('sha256', 'your-secret')
.update(signingContent, 'utf8')
.digest('hex');

发送签名请求​

const response = await context.http.requestJson({
url: 'https://example.com/api/orders',
method: 'POST',
headers: {
'x-timestamp': timestamp,
'x-signature': signature,
},
body: bodyText,
});

随机 UUID​

import { randomUUID } from 'node:crypto';

const nonce = randomUUID();

说明​

签名规则必须和第三方平台完全一致,包括字段顺序、换行符、JSON 格式、输出格式如 hex 或 base64,以及时间格式。