JavaScript SDK

The official @paybin/sdk package wraps the Paybin API for Node.js and TypeScript. It builds request hashes, signs requests, keeps amounts exact, verifies callbacks and returns typed responses, so you can integrate without implementing those details yourself. A separate entry point provides a React symbol selector for your frontend.

Installation

The SDK requires Node.js 20 or newer.

npm install @paybin/sdk

The main package runs on your server only: it holds your Secret Key and signing key. Never import it into browser code. In the browser, use the React components from @paybin/sdk/react, which need no keys.

Configure the client

Create one client and reuse it for every request.

paybin.ts

import { Paybin } from '@paybin/sdk'

export const paybin = new Paybin({
  publicKey: process.env.PAYBIN_PUBLIC_KEY!,
  secretKey: process.env.PAYBIN_SECRET_KEY!,
  environment: 'sandbox', // use 'production' for live traffic
  signature: { env: 'PAYBIN_SIGNATURE_PRIVATE_KEY' },
})
OptionDefaultDescription
publicKeyrequiredYour Public Key. Sent as PublicKey in every request.
secretKeyrequiredYour Secret Key. Sent in the X-Api-Key header and used for request hashes and callback signatures.
environment'sandbox''sandbox' uses https://sandbox.paybin.io, 'production' uses https://gateway.paybin.io.
baseUrl—Overrides the base URL, for example to point at a local mock server.
timeoutMs30000Request timeout in milliseconds.
retryno retriesmaxRetries (0–10), initialDelayMs (250) and maxDelayMs (5000). Applies to read-only calls only.
signature—Your RS512 private key for request signing. Set exactly one of key (PEM string), path (PEM file) or env (environment variable name). An empty object reads PAYBIN_SIGNATURE_PRIVATE_KEY.

Keys are checked when the client is created: a missing key, or a configured signature source that is empty, throws immediately instead of failing on the first request.

Request signing

When signature is set, the SDK signs the exact bytes of every POST body and sends the X-Signature header. You need a signature key for:

  • deposit.verify — the recommended way to handle callbacks.
  • deposit.generateUrl — the signed hosted deposit page.
  • withdraw.add — with a key configured, the SDK uses the signed withdraw route; without one it uses the unsigned route. Both still require your email, two-factor code and IP allowlist.

Calling deposit.verify or deposit.generateUrl without a key throws before any request is sent. Generate the key pair in Paybin Portfolio as described in Set up a signature key.

Responses and errors

Most methods resolve to the standard response envelope with camelCase fields: apiVersion, code, message and data. data can be null, so always check it. The two single-symbol price methods return the bare price object instead.

Any response whose code is not 200, any HTTP error and any network failure is thrown as a PaybinError:

PropertyDescription
codeThe Paybin error code from the response, such as Z513 (see Errors). Without one, the numeric code, the HTTP status, or a transport code such as ECONNABORTED or ERR_CANCELED.
httpStatusThe HTTP status, or 0 when no response arrived.
responseCodeThe code field of the response envelope, when there was one.
validationErrorsField validation messages, for example Symbol: ['The Symbol field is required.'].
retryAfterMsThe server's Retry-After delay, when sent.
requestIdThe request ID, when the server sent one.
import { PaybinError, PaybinErrorCode } from '@paybin/sdk'

try {
  const { data } = await paybin.balance.get('USDT')
  console.log(data)
} catch (error) {
  if (error instanceof PaybinError) {
    if (error.code === PaybinErrorCode.Z513) {
      // Insufficient balance
    } else if (error.httpStatus === 401) {
      // Wrong API keys or an invalid request signature (the body is empty)
    } else if (error.httpStatus === 417) {
      // Rate limited — wait before trying again
    }
  }
  throw error
}

Every method also accepts a last options argument with signal (an AbortSignal) and timeoutMs:

await paybin.balance.get(undefined, { signal: AbortSignal.timeout(5000) })

Only read-only calls are retried, and only when you configure retry. Creating addresses, withdraws, verification transfers and hosted URLs is never replayed automatically.

Exact amounts

JavaScript numbers cannot hold every crypto amount exactly — token amounts can have up to 18 decimals. The SDK avoids rounding in both directions:

  • Responses: every monetary value (balances, amounts, fees, minimums, prices) is returned as a decimal string such as '125.500000'. Network IDs, statuses and counts stay numbers.
  • Requests: monetary inputs accept a decimal string or a number. Prefer strings: '0.00000001' is sent exactly as written, and the request hash is computed from the same text.

Store amounts as text or in a decimal column, and use a decimal library for arithmetic.

Deposits

Find the symbols you can accept

deposit.getAvailableSymbols() returns the assets configured for your account, each with its network ID and minimum deposit amounts. Use the exact symbol value in later calls — for example ETH, TRX-USD or BSC-USD (see Supported symbols).

const { data: assets } = await paybin.deposit.getAvailableSymbols()

for (const asset of assets ?? []) {
  console.log(asset.symbol, asset.network, asset.networkId)
  for (const minimum of asset.minAmounts) {
    console.log(minimum.amount, minimum.currency) // e.g. '10.00' 'USD'
  }
}

Minimums keep their original currency: a USD minimum is not a token amount. An empty minAmounts list means no minimum is configured.

Create a deposit address

deposit.createAddress creates an address for the customer, or returns the existing one, and registers the callback URL. The request hash is built for you.

const { data: deposit } = await paybin.deposit.createAddress({
  symbol: 'TRX-USD',
  label: 'Customer 42',
  referenceId: 'customer-42',
  callbackUrl: 'https://example.com/paybin/callback',
})

console.log(deposit?.wallet) // the address to show your customer

To look an address up without creating one, use deposit.getAddress. It returns data: null when no active address matches.

import { NetworkId } from '@paybin/sdk'

const { data: existing } = await paybin.deposit.getAddress({
  memberId: 'customer-42',
  symbol: 'TRX-USD',
  networkId: NetworkId.TronMainnet,
})

Look up deposits

Use deposit.list to reconcile, or to recover deposits whose callback you missed. Results are paginated with a cursor.

let cursor: string | undefined

do {
  const { data: page } = await paybin.deposit.list({
    referenceId: 'customer-42',
    fromUtc: '2026-11-01T00:00:00Z',
    pageSize: 100,
    cursor,
  })
  for (const deposit of page?.items ?? []) {
    console.log(deposit.id, deposit.amount, deposit.status)
  }
  cursor = page?.nextCursor ?? undefined
} while (cursor)
  • Filters: referenceId, uniqueId, address, symbol, networkId, status, fromUtc (inclusive) and toUtc (exclusive). Timestamps need an explicit offset, such as Z.
  • pageSize is 1–100 (default 50). Keep the filters unchanged while you follow nextCursor.
  • Record IDs are strings. deposit.getTransaction(id) returns one deposit by ID, or data: null if it does not exist.
  • Statuses are listed in Deposit statuses and available as the DepositStatus enum.

Hosted deposit page

deposit.generateUrl returns the URL of a Paybin-hosted payment page. It needs a signature key.

const { data } = await paybin.deposit.generateUrl({
  referenceId: 'customer-42',
  amount: '100.00',
  currency: 'USD',
  symbol: 'ETH',
  redirectUrl: 'https://example.com/paid',
  callbackUrl: 'https://example.com/paybin/callback',
})

console.log(data?.url)

Handle deposit callbacks

Paybin calls your callbackUrl when a deposit is confirmed. The Webhooks page describes the payload and the protocol; the SDK covers each step:

  1. Read the raw body. Pass the exact bytes you received to the SDK — not an object from JSON.parse or express.json(), which can round the amount. A body that was already parsed is rejected.
  2. Check the signature with verifyWebhook(rawBody, secretKey).
  3. Confirm the deposit with Paybin using deposit.verify. The callback signature only covers UniqueId, so credit the amount, address and reference returned by deposit.verify, not the ones in the callback.
  4. Store the deposit once. The same callback can arrive more than once. Use a unique key such as UniqueId + OrderId + Address + Symbol so a repeated callback cannot credit twice.
  5. Acknowledge with HTTP 200 and the JSON body from createWebhookAcknowledgement(yourTransactionId). Any other answer is treated as not delivered. See Responding to callbacks.

Callback handler

import express from 'express'
import {
  createWebhookAcknowledgement,
  parseDepositWebhook,
  verifyWebhook,
} from '@paybin/sdk'
import { paybin } from './paybin'

const app = express()
const secretKey = process.env.PAYBIN_SECRET_KEY!

app.post(
  '/paybin/callback',
  express.raw({ type: 'application/json', limit: '32kb' }), // keep the raw bytes
  async (req, res) => {
    if (!verifyWebhook(req.body, secretKey)) {
      return res.status(401).json({ error: 'Invalid signature' })
    }

    try {
      const callback = parseDepositWebhook(req.body)
      const { data: deposit } = await paybin.deposit.verify({
        txId: callback.uniqueId,
        address: callback.address,
        amount: callback.amount,
      })
      if (!deposit) throw new Error('Deposit not found')

      // Your code: credit deposit.amount exactly once, return your record ID
      const transactionId = await creditDeposit(deposit)

      res.status(200).json(createWebhookAcknowledgement(transactionId))
    } catch {
      res.status(500).json({ error: 'Callback could not be processed' })
    }
  },
)

parseDepositWebhook returns the callback with camelCase fields: address, uniqueId, symbol, amount (decimal string), referenceId, price, orderId, signature and hash. For Express there is also createWebhookMiddleware(secretKey). Mount it after express.raw(): it checks the signature, answers 401 or 400 itself, and replaces req.body with the parsed callback. You still call deposit.verify and acknowledge yourself.

Withdrawals

Create a withdraw

withdraw.add builds the request hash and picks the withdraw route for you. Read How a withdraw works first: depending on your account's approval mode, a withdraw is sent at once or waits for approval.

import { NetworkId, PaybinError } from '@paybin/sdk'

const merchantTransactionId = 'payout-1001' // your unique ID for this withdraw

try {
  const result = await paybin.withdraw.add({
    referenceId: 'customer-42',
    symbol: 'TRX-USD',
    networkId: NetworkId.TronMainnet,
    amount: '25.50',
    address: 'TQ5NZ8Vwq8tG5n8wTN8V9kJ1X3Zb1k2Q9n',
    label: 'Payout',
    merchantTransactionId,
    email: 'operator@example.com', // a user with two-factor authentication
    tfaCode: '123456', // that user's current code
  })

  if (result.data?.success && result.data.txId) {
    console.log('Sent:', result.data.txId)
  } else {
    // Waiting for approval, for example Z509 (email) or Z529 (SMS)
    console.log('Pending:', result.message)
  }
} catch (error) {
  if (!(error instanceof PaybinError)) throw error

  // The request can fail after the withdraw was stored (for example Z100,
  // a timeout or a lost connection). Check before you do anything else.
  const { data: stored } = await paybin.withdraw.getStatus(merchantTransactionId)
  if (stored) {
    console.log('Stored with status', stored.status, stored.txId)
  } else {
    console.log('Not stored:', error.code) // for example Z513, insufficient balance
  }
}
  • Never resubmit with a new merchantTransactionId after an unknown outcome. Check withdraw.getStatus first, and if you retry, reuse the same ID — Paybin never creates the same withdraw twice.
  • getStatus returns data: null when no withdraw with that ID exists. That alone does not prove a request that was in flight failed; check again later.
  • Status Approved means the withdraw was approved, not that the transaction is confirmed on chain. Look at txId.
  • Pass feeRate (WithdrawFeeRate.Fast, Standard or Slow) to choose the network fee. withdraw.estimateFee(symbol) returns the fee and estimated arrival time for each rate.
  • Do not retry a rejected two-factor code automatically: three wrong codes block the user (Z206). See Two-factor authentication.

Verify an address

Before paying out to a new address you can ask the customer to prove they own it. Paybin sends a small random amount to the address, and the customer confirms how much arrived. The flow is described in Address verification.

// 1. Send the verification transfer
await paybin.withdraw.verifyStart({
  referenceId: 'customer-42',
  symbol: 'TRX-USD',
  networkId: NetworkId.TronMainnet,
  address: 'TQ5NZ8Vwq8tG5n8wTN8V9kJ1X3Zb1k2Q9n',
  label: 'Main wallet',
})

// 2. Later: confirm the amount the customer reports
const { data } = await paybin.withdraw.verifyConfirmAmount({
  referenceId: 'customer-42',
  symbol: 'TRX-USD',
  networkId: NetworkId.TronMainnet,
  amount: '0.000149',
})

console.log(data?.isVerified)

withdraw.getAssets(referenceId) lists the customer's saved addresses together with the symbols and networks you can pay out on, and withdraw.deleteVerifiedAddress removes a saved address.

Balances, prices and symbols

// Balances for every symbol, or filtered by symbol code or asset name
const { data: balances } = await paybin.balance.get('USDT')
balances?.forEach((b) => console.log(b.symbol, b.network, b.balance))

// Prices
const price = await paybin.prices.get('BTC') // bare object, e.g. price.usd
const quote = await paybin.prices.getExchange('BTC') // bid/ask per currency
const { data: all } = await paybin.prices.getBulk()

// All active symbols with network, contract address and decimals
const { data: symbols } = await paybin.symbols.getActive()

React components

@paybin/sdk/react provides a symbol and network selector for your frontend. It loads the public symbol list from Paybin and never needs your keys.

'use client'

import { SymbolSelector, useSymbols } from '@paybin/sdk/react'

export function AssetPicker() {
  const { symbols, loading, error, refetch } = useSymbols({ environment: 'sandbox' })

  if (error) {
    return <button onClick={refetch}>Retry loading assets</button>
  }

  return (
    <SymbolSelector
      symbols={symbols}
      disabled={loading}
      onSelect={(symbol) => {
        // Send symbol.symbol to your server, which calls the API
      }}
    />
  )
}
  • useSymbols returns all active Paybin symbols. To show only the assets enabled for your account, call deposit.getAvailableSymbols() on your server and pass the result to symbols instead.
  • SymbolSelector works controlled (value with onChange) or uncontrolled (defaultValue), supports name for native forms, and resets when resetKey changes. Labels and placeholders can be changed with symbolLabel, networkLabel, symbolPlaceholder and networkPlaceholder.
  • For your own markup, the useSymbolSelector(symbols, options) hook exposes the same selection logic.

Method reference

MethodAPI endpoint
deposit.getAvailableSymbols()List available deposit symbols
deposit.createAddress(params)Create a deposit address
deposit.getAddress(params)Get a deposit address
deposit.list(params)List deposits
deposit.getTransaction(id)Get a deposit
deposit.verify(params)Verify a deposit
deposit.generateUrl(params)Generate a hosted deposit page (signed variant)
withdraw.add(params)Create a withdraw
withdraw.getStatus(merchantTransactionId)Check withdraw status
withdraw.estimateFee(symbol)Estimate the withdraw fee
withdraw.getAssets(referenceId)List withdrawable assets and saved addresses
withdraw.getWithdrawableAssets(referenceId)Same as getAssets, returning only the saved address list
withdraw.verifyStart(params)Start address verification
withdraw.verifyConfirmAmount(params)Confirm the verification amount
withdraw.deleteVerifiedAddress(params)Remove a saved address
withdraw.generateUrl(params)Creates a hosted withdraw page URL
withdraw.retrySms(params)Sends the SMS approval message for a withdraw again
balance.get(symbol?)List balances
balance.getBySymbol(symbol)Same as balance.get, returning only the list
balance.getLegacy()Get balances (fixed format)
prices.get(symbol)Get prices
prices.getExchange(symbol)Get exchange prices
prices.getBulk()Get all prices
symbols.getActive()List symbols

The hash helpers (generateDepositHash, generateWithdrawHash, generateVerifyStartHash, generateVerifyConfirmHash) and toDecimalString are exported too, for code that calls the API directly.

Upgrading from version 1

Version 2 fixes requests that did not work in 1.x and changes several types. When you upgrade:

  • Network IDs changed. The NetworkId enum now matches Paybin (Ethereum 2, BNB Smart Chain 3, Litecoin 4, TRON 5, Optimism 6), and Solana, Avalanche and opBNB were added. If you stored numeric network IDs produced by 1.x, migrate them. See Network IDs.
  • Callbacks. Pass the raw request body and your Secret Key: verifyWebhook(rawBody, secretKey). The 1.x three-argument form checked a header Paybin never sends.
  • Amounts are strings. Monetary values in responses and callbacks are decimal strings instead of numbers.
  • Symbols are plain strings, so every supported symbol works, for example TRX-USD.
  • Error codes. error.code now holds the Paybin error code (Z513); the numeric envelope code moved to error.responseCode.
  • Signing keys are checked at startup. A configured but missing key throws when the client is created.

Was this page helpful?