Node.js
兼容性
Node.js ≥ 18(原生 fetch)。无第三方依赖。
客户端实现
js
import crypto from 'node:crypto'
const APP_ID = 'cp_a1b2c3d4...'
const SECRET = 'f1e2d3c4...'
const BASE = 'https://api.coinepay.net'
function sign(method, path, body) {
const ts = Math.floor(Date.now() / 1000).toString()
const nonce = crypto.randomBytes(16).toString('hex')
const bodyHash = crypto.createHash('sha256').update(body).digest('hex')
const signInput = `${method}\n${path}\n\n${ts}\n${nonce}\n${bodyHash}`
const sig = crypto.createHmac('sha256', SECRET).update(signInput).digest('hex')
return {
'X-App-Id': APP_ID,
'X-Timestamp': ts,
'X-Nonce': nonce,
'X-Signature': sig,
}
}
// code 不为 0 的响应一律抛出该错误
export class ApiError extends Error {
constructor(httpStatus, code, errorKey, message, retryAfter) {
super(`HTTP ${httpStatus} code=${code} error_key=${errorKey}: ${message}`)
this.httpStatus = httpStatus
this.code = code // 业务码:40000 / 40100 / 40400 / 40900 / 42900 / 50000 ...
this.errorKey = errorKey // 稳定的机器标识——据此分支,不要用 message
this.retryAfter = retryAfter // Retry-After 响应头(秒),429 时设置
}
}
// code === 0 时返回 data,否则抛出 ApiError
export async function call(path, bodyDict, idempotencyKey) {
const body = JSON.stringify(bodyDict ?? {})
const headers = {
...sign('POST', path, body),
'Content-Type': 'application/json',
}
if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey
const res = await fetch(BASE + path, { method: 'POST', headers, body })
const retryAfter = Number(res.headers.get('Retry-After')) || undefined
let resp
try {
resp = await res.json()
} catch {
// 不是我们的 JSON 包络(如代理层错误页)
throw new ApiError(res.status, undefined, undefined, res.statusText, retryAfter)
}
// 大部分业务错误的 HTTP 状态码是 200——判断 code,不要看 res.ok
if (resp.code === 0) return resp.data
throw new ApiError(res.status, resp.code, resp.error_key, resp.message, retryAfter)
}
// Webhook 验签
export function verifyWebhook(sigHeader, tsHeader, rawBody, webhookSecret) {
if (!sigHeader || !sigHeader.startsWith('v1,')) return false
const sig = sigHeader.slice(3)
const expected = crypto
.createHmac('sha256', webhookSecret)
.update(`${tsHeader}.`)
.update(rawBody)
.digest('hex')
// 恒定时间比较
return (
Buffer.byteLength(sig) === Buffer.byteLength(expected) &&
crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))
)
}使用示例
js
import { randomUUID } from 'node:crypto'
import { call, ApiError } from './brand.js'
// 1. 列卡头
let data = await call('/api/v1/openapi/card_headers/list', { page: 1, page_size: 20 })
console.log(data.list[0].header_id)
// 2. 列卡配置
data = await call('/api/v1/openapi/card_configs/list', { header_id: 'hdr_5' })
const packageId = data.list[0].package_id
// 3. 申请虚拟卡(带幂等键)
data = await call(
'/api/v1/openapi/card/apply',
{
header_id: 'hdr_5',
package_id: packageId,
cardholder_id: 'chd_1024',
},
randomUUID(),
)
const cardId = data.card_id
console.log(`Created card: ${cardId}`)
// 4. 卡激活后(card.opened webhook / status 2)创建充值。
// amount 的单位是套餐的充值资产(如 USDT)。
try {
data = await call(
'/api/v1/openapi/card/recharge',
{ card_id: cardId, amount: '100.00' },
randomUUID(),
)
console.log(`Transaction: ${data.transaction_id} (${data.status_desc})`) // processing → 等待 webhook
} catch (e) {
if (!(e instanceof ApiError)) throw e
if (e.errorKey === 'insufficient_balance') console.log('请先给钱包充值')
else if (e.errorKey === 'card_number_not_ready') console.log('virtual_s921 刚开卡,卡号尚未下发——几秒后重试')
else throw e
}错误处理与重试
成功的判断是 code === 0。大部分业务错误(40000、40001、50000)的 HTTP 状态码是 200,不要只凭 res.ok / HTTP 状态码判断——call() 对任何非 0 的 code 都会抛出 ApiError,再按 errorKey 分支处理。
js
import { call, ApiError } from './brand.js'
const sleep = (s) => new Promise((r) => setTimeout(r, s * 1000))
// 只重试可以安全重试的情况;每次重试都使用同一个 Idempotency-Key
export async function callWithRetry(path, body, idempotencyKey, maxAttempts = 4) {
for (let attempt = 0; ; attempt++) {
try {
return await call(path, body, idempotencyKey)
} catch (e) {
if (!(e instanceof ApiError) || attempt === maxAttempts - 1) throw e
if (e.code === 42900) {
// HTTP 429 too_many_requests:等待 Retry-After 秒
await sleep(e.retryAfter ?? Math.min(2 ** attempt, 30))
continue
}
if (e.errorKey === 'openapi_idempotency_key_in_progress') {
// HTTP 409:同一个 key 的首个请求仍在处理——稍后用同一个 key 重试
await sleep(2 ** attempt)
continue
}
if (e.code === 50000 && (!idempotencyKey || e.httpStatus >= 500)) {
// 读接口可以安全重试。写接口返回的 HTTP 200 + 50000 已按 Idempotency-Key 存档,
// 重试只会重放同一结果——请先查询状态
await sleep(2 ** attempt)
continue
}
// 40100 openapi_invalid_credentials(HTTP 401):检查签名 / 时钟 / 凭证
// 40000 / 40001 / 40300 / 40400 / 40900 openapi_idempotency_key_conflict:修正请求
throw e
}
}
}Webhook 接收(Express)
js
import express from 'express'
import { verifyWebhook } from './brand.js'
const app = express()
const WEBHOOK_SECRET = process.env.BRAND_WEBHOOK_SECRET
// 关键:raw body,不是 JSON parse 后的对象
app.post('/webhook',
express.raw({ type: 'application/json' }),
async (req, res) => {
const sig = req.header('Webhook-Signature') || ''
const ts = req.header('Webhook-Timestamp') || ''
const eventId = req.header('Webhook-Id') || ''
const eventType = req.header('Webhook-Type') || ''
if (!verifyWebhook(sig, ts, req.body, WEBHOOK_SECRET)) {
return res.status(401).send('invalid signature')
}
// 时间戳 ±5 分钟
if (Math.abs(Math.floor(Date.now() / 1000) - Number(ts)) > 300) {
return res.status(401).send('timestamp expired')
}
// event_id 去重
if (await alreadyProcessed(eventId)) return res.sendStatus(200)
const payload = JSON.parse(req.body.toString('utf8'))
await enqueue(eventType, payload) // 重活丢队列
await markProcessed(eventId)
res.sendStatus(200)
})
app.listen(3000)Webhook 接收(Fastify)
js
import Fastify from 'fastify'
import { verifyWebhook } from './brand.js'
const fastify = Fastify()
// 保留 raw body
fastify.addContentTypeParser(
'application/json',
{ parseAs: 'buffer' },
(req, body, done) => {
req.rawBody = body
try {
done(null, JSON.parse(body.toString('utf8')))
} catch (e) {
done(e)
}
},
)
fastify.post('/webhook', async (req, reply) => {
const sig = req.headers['webhook-signature'] || ''
const ts = req.headers['webhook-timestamp'] || ''
if (!verifyWebhook(sig, ts, req.rawBody, process.env.BRAND_WEBHOOK_SECRET)) {
return reply.code(401).send('invalid signature')
}
await enqueue(req.headers['webhook-type'], req.body)
return { ok: true }
})
fastify.listen({ port: 3000 })TypeScript 类型
ts
export interface ApiResponse<T = unknown> {
code: number // 0 = 成功;否则为 40000 / 40100 / 42900 / 50000 等业务码
message: string // 本地化文案,仅供人阅读——不要据此分支
error_key?: string // 所有错误响应都带,成功时不带
data?: T // 成功时返回
}
export interface PageData<T> {
list: T[]
total: number
page: number
page_size: number
total_pages: number
has_next: boolean
has_prev: boolean
}
export interface CardInfo {
card_id: string
card_type: 'virtual_l' | 'virtual_p' | 'virtual_v' | 'virtual_r' | 'virtual_g' | 'virtual_a' | 'virtual_s921'
card_brand: string
currency: string
status: 1 | 2 | 3 | 4 | 5 | 6
status_desc: string
masked_card_no: string
last_four: string
balance: string
frozen_balance: string
activated_at?: string // 卡激活前不返回
created_at: string
}