Skip to content

Node.js ​

Compatibility

Node.js ≥ 18 (native fetch). No third-party dependencies.

Client Implementation ​

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,
  }
}

// Thrown for every response whose `code` is not 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          // business code: 40000 / 40100 / 40400 / 40900 / 42900 / 50000 ...
    this.errorKey = errorKey  // stable machine key — branch on this, never on `message`
    this.retryAfter = retryAfter  // Retry-After header in seconds (set on 429)
  }
}

// Returns `data` when code === 0, throws ApiError otherwise
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 {
    // Not our JSON envelope (e.g. a proxy error page)
    throw new ApiError(res.status, undefined, undefined, res.statusText, retryAfter)
  }
  // Most business errors arrive with HTTP 200 — check `code`, not res.ok
  if (resp.code === 0) return resp.data
  throw new ApiError(res.status, resp.code, resp.error_key, resp.message, retryAfter)
}

// Webhook signature verification
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')

  // Constant-time compare
  return (
    Buffer.byteLength(sig) === Buffer.byteLength(expected) &&
    crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))
  )
}

Usage ​

js
import { randomUUID } from 'node:crypto'
import { call, ApiError } from './brand.js'

// 1. List card headers
let data = await call('/api/v1/openapi/card_headers/list', { page: 1, page_size: 20 })
console.log(data.list[0].header_id)

// 2. List card configs
data = await call('/api/v1/openapi/card_configs/list', { header_id: 'hdr_5' })
const packageId = data.list[0].package_id

// 3. Apply virtual card
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. Once the card is active (card.opened webhook / status 2), create a recharge.
//    `amount` is in the package's recharge asset (e.g. 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 → wait for webhook
} catch (e) {
  if (!(e instanceof ApiError)) throw e
  if (e.errorKey === 'insufficient_balance') console.log('Top up your wallet first')
  else if (e.errorKey === 'card_number_not_ready') console.log('virtual_s921 right after opening — retry in a few seconds')
  else throw e
}

Errors & Retry ​

Success is code === 0. Most business errors (40000, 40001, 50000) come back with HTTP 200, so never rely on res.ok / the HTTP status alone — call() throws ApiError for any non-zero code, and you branch on errorKey.

js
import { call, ApiError } from './brand.js'

const sleep = (s) => new Promise((r) => setTimeout(r, s * 1000))

// Retry only what is safe to retry; reuse the SAME Idempotency-Key on every attempt
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: wait Retry-After seconds
        await sleep(e.retryAfter ?? Math.min(2 ** attempt, 30))
        continue
      }
      if (e.errorKey === 'openapi_idempotency_key_in_progress') {
        // HTTP 409: the first request with this key is still running — retry later, same key
        await sleep(2 ** attempt)
        continue
      }
      if (e.code === 50000 && (!idempotencyKey || e.httpStatus >= 500)) {
        // Read endpoints are safe to retry. On write endpoints an HTTP-200 50000 is stored
        // under the Idempotency-Key and would only be replayed — check the state instead.
        await sleep(2 ** attempt)
        continue
      }
      // 40100 openapi_invalid_credentials (HTTP 401): fix signature / clock / credential.
      // 40000 / 40001 / 40300 / 40400 / 40900 openapi_idempotency_key_conflict: fix the request.
      throw e
    }
  }
}

Webhook Receiver (Express) ​

js
import express from 'express'
import { verifyWebhook } from './brand.js'

const app = express()
const WEBHOOK_SECRET = process.env.BRAND_WEBHOOK_SECRET

// Important: raw body, NOT a parsed JSON object
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')
    }
    if (Math.abs(Math.floor(Date.now() / 1000) - Number(ts)) > 300) {
      return res.status(401).send('timestamp expired')
    }
    if (await alreadyProcessed(eventId)) return res.sendStatus(200)

    const payload = JSON.parse(req.body.toString('utf8'))
    await enqueue(eventType, payload)   // push to queue
    await markProcessed(eventId)

    res.sendStatus(200)
  })

app.listen(3000)

Webhook Receiver (Fastify) ​

js
import Fastify from 'fastify'
import { verifyWebhook } from './brand.js'

const fastify = Fastify()

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 Types ​

ts
export interface ApiResponse<T = unknown> {
  code: number        // 0 = success; otherwise a business code such as 40000 / 40100 / 42900 / 50000
  message: string     // localized, for humans only — never branch on it
  error_key?: string  // present on every error response, absent on success
  data?: T            // present on success
}

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  // omitted until the card is activated
  created_at: string
}

Released under MIT-equivalent terms.