Skip to content

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
}

採用 MIT 等價條款釋出