Skip to content

MagenPay Developer Docs

Build crypto checkout in minutes. Start with a single POST or drop in our pre-built UI.

⌘K
Get started

Introduction

The MagenPay API is built on REST. It uses standard HTTP verbs, returns JSON, and authenticates via bearer tokens. Use the official Node.js SDK, or any HTTP client in any language.

API base URL
All endpoints are served from https://api.magenpay.com. Use https://api.sandbox.magenpay.com for the sandbox environment.

Quickstart

Three steps and you're charging customers in crypto.

  1. 1

    Get a merchant token

    Create an account at client.magenpay.com, confirm your email and set up two-factor authentication. Then copy your token from Settings → API & Webhooks, or request one with POST /v1/auth.

  2. 2

    Create a payment

    POST a payment request — receive a checkout URL.

  3. 3

    Listen for webhooks

    When payment confirms on-chain, we POST to your webhook endpoint with a signed payload.

Node.js SDK

npm · magenpay

The official SDK wraps every endpoint on this page, with TypeScript types and readable errors. It has no runtime dependencies and supports Node.js 18 and later, with both import and require.

terminal
BASH
npm install magenpay
magenpay.js
import { MagenPay } from 'magenpay'

const magenpay = new MagenPay({
  token: process.env.MAGENPAY_TOKEN,         // Settings → API & Webhooks
  merchantId: process.env.MAGENPAY_MERCHANT, // merchant UUID, portal → Merchants
})

Create a payment

An order waits 30 minutes for payment, then expires. Order creation is never retried automatically, so a timeout cannot create a second order. Reads are retried after network errors.

checkout.js
JAVASCRIPT
const order = await magenpay.orders.create({
  amount: 125.5,
  network: 'BEP20',
  symbol: 'USDT',
  redirectUrl: 'https://shop.example.com/thank-you',
  references: ['INV-1001'], // up to 4 of your own values
})

// Send the customer to the hosted payment page…
res.redirect(order.paymentUrl)
// …or show order.address and order.qrCode yourself.

const latest = await magenpay.orders.retrieve(order.paymentId)
latest.status // 'pending' | 'paid' | 'expired' | 'cancelled'

await magenpay.orders.list()                   // newest first
await magenpay.orders.cancel(order.paymentId)  // only while pending

Handle webhooks

Before your code runs, the SDK asks the MagenPay API for the order and checks that its status, transaction and merchant match the webhook. A webhook that MagenPay does not confirm is rejected with 400. Use the returned order, not the request body, for amounts.

server.js
JAVASCRIPT
import express from 'express'

const app = express()

const onMagenPay = magenpay.webhooks.handler(async ({ event, order }) => {
  if (event.type === 'payment.paid') {
    // Idempotent: the same webhook can arrive more than once.
    await db.orders.markPaidOnce(order.references[0], {
      paymentId: order.paymentId,
      amount: order.amount,
      txHash: order.txHash,
    })
  }
  if (event.type === 'payment.expired' || event.type === 'payment.cancelled') {
    await db.orders.release(order.references[0])
  }
})

app.post('/webhooks/magenpay', express.json(), onMagenPay)
any-framework.js
JAVASCRIPT
// Other frameworks (Fastify, Next.js, Hono…)
const { event, order } = await magenpay.webhooks.verify(body, { headers })
Response codes
The handler answers 200 when your code succeeded, 400 when the webhook is not genuine, and 500 when your code threw, so MagenPay delivers it again.

Errors

Every error extends MagenPayError and has code, status and raw.

ClassWhen
MagenPayAuthErrorToken missing, wrong or revoked, or the account is suspended.
MagenPayConnectionErrorNetwork failure or timeout.
MagenPayWebhookErrorThe webhook is not genuine or does not match the order.
MagenPayErrorAnything else, e.g. invalid_request, order_not_found, order_not_cancellable.
errors.js
JAVASCRIPT
import { MagenPayAuthError, MagenPayError } from 'magenpay'

try {
  await magenpay.orders.create({ amount: 10, network: 'BEP20', symbol: 'USDT' })
} catch (err) {
  if (err instanceof MagenPayAuthError) {
    // token revoked or account blocked: get a new token
  } else if (err instanceof MagenPayError) {
    console.error(err.code, err.message) // e.g. invalid_request
  }
  throw err
}

The full reference, including options such as timeoutMs and maxRetries, is in the package README.

Authentication

All requests authenticate with a bearer token in the Authorization header.

request.sh
BASH
Authorization: Bearer YOUR_MERCHANT_TOKEN
Keep your token secret
Never commit a merchant token to source control or expose it client-side. Use server-to-server requests only — and rotate immediately if you suspect a leak.
Changed on 12 November 2026
Two-factor authentication is now required on every account, and all tokens issued before 12 November 2026 have been revoked. Sign in at client.magenpay.com, finish the 2FA setup, then get a new token as described below and replace it on your servers. Your calls to /v1/create-order and the other endpoints do not change. Only issuing a token needs the 2FA code.

Get an API token

Before you can get a token, your account needs a confirmed email address and two-factor authentication. Both are set up the first time you sign in to the portal. Then use either option:

  • Portal: sign in at client.magenpay.com and copy the token shown under Settings → API & Webhooks.
  • API: call POST /v1/auth with your email, password and the current 6-digit code from your authenticator app in otp. Backup codes are not accepted here.
POST /v1/auth
get-token
curl -X POST https://api.magenpay.com/v1/auth \
  -H "Content-Type: application/json" \
  -d '{
    "email": "you@example.com",
    "password": "YOUR_PASSWORD",
    "otp": "123456"
  }'
200 OK
JSON
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
HTTPCodeMeaning
401—Wrong email or password.
401mfa_requiredotp is missing or wrong. Codes change every 30 seconds, and each code works only once.
403email_unverifiedThe email address is not confirmed yet. Sign in to the portal to get a new link.
403mfa_setup_required2FA is not set up yet. Sign in to the portal once to set it up.
429mfa_locked5 wrong codes in 15 minutes. Wait 15 minutes and try again.

Token lifetime

A token does not expire on a timer. Store it once and send it with every request. These actions revoke every token on the account, including the one your servers use:

  • Signing out other devices from Security in the portal.
  • Resetting your password with a reset link.
  • A 2FA reset by MagenPay support, for example after you lose your phone.

After any of these, your requests get 401. Get a new token and update your servers.

Test vs live tokens

Sandbox tokens are prefixed with test_ — production tokens with live_. Both look like UUIDs.

API reference

Create order

Create a new payment order. The response contains a checkout URL you can redirect the customer to, plus an on-chain address they can pay directly.

POST /v1/create-order

Body parameters

FieldTypeDescription
amount* numberAmount to charge in the chosen currency.
currency* stringUSDT · BNB · ETH · TRX
network* stringBEP20 · TRC20 · ERC20
redirect stringURL to redirect the customer to after payment.
reference1 stringYour internal order ID (max 80 chars).
expires_in integerSeconds until expiration (default 1800).

* required

Request

create-order
curl -X POST https://api.magenpay.com/v1/create-order \
  -H "Authorization: Bearer $MERCHANT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "amount":     100,
    "currency":   "USDT",
    "network":    "BEP20",
    "redirect":   "https://shop.example/return",
    "reference1": "order-1234"
  }'

Response

200 OK
JSON
{
  "id":          12345,
  "payment_id":  "pay_abc123xyz",
  "status":      "NEW",
  "amount":      100,
  "currency":    "USDT",
  "network":     "BEP20",
  "address":     "0x1234567890abcdef1234567890abcdef12345678",
  "expires_at":  "2025-04-22T15:30:00Z",
  "checkout_url":"https://pay.magenpay.com/c/pay_abc123xyz",
  "created_at":  "2025-04-22T15:00:00Z"
}

Retrieve order

GET /v1/get-order?payment_id={'{'}id{'}'}
get-order
BASH
curl https://api.magenpay.com/v1/get-order?payment_id=pay_abc123xyz \
  -H 'Authorization: Bearer $MERCHANT_TOKEN'

List orders

Returns up to 100 orders per page, sorted by created_at descending.

GET /v1/get-order-transaction

Cancel order

POST /v1/cancel-order
One-way operation
A cancelled order cannot be reactivated. The customer will see an "Order cancelled" message at the checkout URL.
Webhooks

Webhooks

When a payment confirms on-chain we send a JSON payload to your merchant_webhook URL. Webhooks are signed, retried, and idempotent.

Event payload

POST /your-webhook
JSON
{
  "event":       "order.paid",
  "id":          12345,
  "payment_id":  "pay_abc123xyz",
  "status":      "PAID",
  "amount":      100,
  "currency":    "USDT",
  "network":     "BEP20",
  "txid":        "0xabcdef...",
  "block_number":42_000_000,
  "confirmed_at":"2025-04-22T15:02:18Z"
}

Signature verification

Every request includes an X-MagenPay-Signature header with the HMAC-SHA256 of the raw body. Always compare in constant time.

verify.{js|py}
import crypto from 'node:crypto'

function verify(rawBody, header, secret) {
  const expected = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex')
  return crypto.timingSafeEqual(
    Buffer.from(header),
    Buffer.from(`sha256=${expected}`)
  )
}

Retries & idempotency

  • ✓ Retried with exponential backoff for up to 72 hours on non-2xx responses.
  • ✓ Each delivery includes Idempotency-Key — your handler should be safe to retry.
  • ✓ Failures surface in Dashboard → Webhooks with full request/response history.

Errors

Errors return a stable machine-readable code plus a human-readable message.

HTTPCodeMeaning
400 invalid_request Required field missing or malformed.
401 unauthorized Token missing, malformed, or revoked.
404 not_found Resource does not exist or is not yours.
409 conflict State transition not allowed (e.g. cancel a paid order).
429 rate_limited Too many requests. Inspect Retry-After.
500 server_error Transient — safe to retry with idempotency.

Rate limits

Default: 100 req / minute / token. Bursts up to 200 are allowed via token bucket. We expose the standard headers:

response headers
BASH
X-RateLimit-Limit:     100
X-RateLimit-Remaining: 87
X-RateLimit-Reset:     1714053600

Testing & sandbox

The sandbox at api.sandbox.magenpay.com mirrors production but settles testnet stablecoins. Use it to test integration end-to-end before going live.

Auto-fund testnet
Sandbox merchants receive 10,000 USDT-testnet on signup. Need more? Ping us.

Changelog

  • 2026-11-12
    Node.js SDK. npm install magenpay creates orders, reads their status and confirms every webhook with the API. Read the guide.
  • 2026-11-12
    Two-factor authentication required. Every account must set up 2FA. POST /v1/auth now requires otp, and /v1/register has been removed (sign up in the portal). All tokens issued before this date were revoked. Get a new token.
  • 2025-04-22
    Polygon & Arbitrum live. Two new low-fee networks now selectable in network.
  • 2025-04-08
    Webhook v2. Signed payloads + idempotency keys. Migration guide on the blog.
  • 2025-01-15
    v1 stabilized. Initial public release of the REST API.