Developer SDK

Server-side SDK for Node.js 18+, TypeScript definitions and Next.js helpers.

Install the official release

npm install https://mixpayer.com/downloads/mixpayer-sdk-0.5.0.tgz

Hosted directly by Mixpayer, not yet published in the npm registry. Import the installed package as @mixpayer/sdk.

Download SDK 0.5.0 ↗

Guide and examples

# Mixpayer Merchant SDK

Server-side ESM SDK for Node.js 18 and later. Never expose secret keys in browser bundles.

## Install the official versioned package

```sh
npm install https://mixpayer.com/downloads/mixpayer-sdk-0.5.0.tgz
```

The package is distributed directly by Mixpayer. It is not currently published on the npm registry; do not use `npm install @mixpayer/sdk` without the download URL until a registry release is announced.

```js
import { Mixpayer, verifyWebhook, verifyCheckoutReturn } from '@mixpayer/sdk'
const client = new Mixpayer({ secretKey: process.env.MIXPAYER_SECRET_KEY })
const products = await client.listProducts()
const priceId = products[0].prices[0].id // IDs must match the key environment
const session = await client.createCheckoutSession({
  customerId: 'user_123', priceId, purchaseQuantity: 1, requestId: 'app-order-1001',
  metadata: { appOrderId: '1001' },
  successUrl: 'https://your-app.example/payment/success',
  cancelUrl: 'https://your-app.example/payment/canceled'
})
// Save session.token and session.orderNo, then redirect to session.checkoutUrl.
const latest = await client.getCheckoutSession(session.token) // 200 in any status
```

Use `sk_test_…` for sandbox and `sk_live_…` for live. Both use `https://api.mixpayer.com`; resources, callbacks and signing keys are scoped to the environment. Sandbox product copies have new product and price IDs. Supported sandbox operations are product reads, checkout, payment simulation, subscriptions, renewal simulation, refunds and credit entitlements. Other merchant API resources return `SANDBOX_UNSUPPORTED`, without falling back to live data.

Open the returned sandbox `checkoutUrl` to use the branded plan and billing pages, then select success, decline or cancellation. No real card, charge or payment provider is used. Fixed sandbox prices stay fixed; dynamic amounts follow the saved merchant/customer editing policy; discount codes, currency switching, live tax calculation and metered billing are not simulated.

## Webhook verification

Read the raw request body before JSON parsing. Events are flat JSON: `event.type`, `event.orderNo`, `event.metadata`. There is no `data` wrapper. Save `event.eventId` durably for idempotency; callbacks can arrive more than once or out of order.

```js
const event = verifyWebhook({
  rawBody: await request.text(),
  signature: request.headers.get('x-mixpayer-signature'),
  secret: process.env.MIXPAYER_SECRET_KEY // key for this delivery environment
})
if (event.type === 'payment.succeeded') {
  // Match event.requestId or event.metadata.appOrderId; apply once by eventId.
}
```

Default timestamp tolerance is ±300 seconds. Changing the body or key invalidates the signature. Delivery timeout is 12 seconds, at most 5 attempts, with 1, 2, 4 and 8 minute retry delays. Any 2xx acknowledges receipt. Signatures use fresh timestamps on retry, while event IDs and bodies remain unchanged. Redirects are not followed. Do slow work asynchronously after durable storage.

## Subscription and refund lifecycle

```js
const subs = await client.listSubscriptions()
await client.cancelSubscription(subs[0].id) // at_period_end only
await client.resumeSubscription(subs[0].id) // clears local scheduled cancellation; live mandates may need a new checkout
await client.simulateRenewal(subs[0].id) // sandbox only
await client.refund({ orderNo: 'YOUR_MIXPAYER_ORDER_NO', reason: 'Customer requested refund' })
```

A cancel request sets `cancelAtPeriodEnd=true`, while `status` can remain `active` until period end. The order-based cancellation route remains a compatibility alias; new integrations should use the subscription ID route. Immediate cancellation is not implemented and is rejected explicitly. Sandbox refunds never contact an upstream provider. Live provider restrictions, including no same-day refunds where applicable (0034), remain in force. Do not revoke access from a failed refund request; process the confirmed `refund.succeeded` event with the actual amount.

## Signed return URL

```js
const info = verifyCheckoutReturn({ url: request.url, secret: process.env.MIXPAYER_SECRET_KEY })
const confirmed = await client.getCheckoutSession(info.session)
// Require confirmed.status === 'complete' and confirmed.orderStatus === 'paid', then match your saved order.
```

The signature covers every query parameter except `signature`, including any existing query parameters in your configured URL. Do not append or rewrite query parameters before verification. Return links contain correlation IDs and a timestamp, not secret keys. Only final sessions can generate a signed return URL. A signed browser return does not replace webhook reconciliation or server-side status checks.

## Next.js App Router

```js
import { createWebhookHandler } from '@mixpayer/sdk/nextjs'
export const POST = createWebhookHandler({
  secret: process.env.MIXPAYER_SECRET_KEY,
  onEvent: async event => { /* persist and process idempotently */ }
})
```

Also exported: `createCheckoutHandler({ client, resolveInput })` and `createPortalHandler({ client, resolveInput })`. `resolveInput` must derive authenticated customer identity on your server. Portal remains a live-only resource. Verification failure returns 400; your handler failure returns 500 so delivery retries.

## Errors

`MixpayerError` exposes `status`, `code`, `body`, and `retryAfter`. Respect HTTP 429 `Retry-After`; the limit is 120 requests/minute per site and environment, burst 30. The SDK never silently retries mutating requests. See https://mixpayer.com/docs/api/ and https://mixpayer.com/docs/webhooks/ for the endpoint reference and event bodies.

## Multiple units and volume discounts

`purchaseQuantity` is the number of packs or subscriptions being purchased (a positive integer). It is separate from `price.quantity`, which is the number of uses included in one pack. Omit `purchaseQuantity` for one unit. Products allow one unit until the merchant explicitly enables multiple-unit purchases.

The merchant defines the maximum and increasing quantity thresholds (for example 3+ units at 10% off, 5+ at 20% off). The highest qualifying tier applies to the entire quantity. Quote order: localized unit price × units → volume discount → one eligible code if stacking is enabled → tax. Discounts round down in integer minor units. The server ignores any client-supplied prices or discounts.

A checkout session locks its purchase quantity. Start a new session to change it. Read `purchaseQuantity`, `unitAmountMinor`, `volumeDiscountMinor`, `volumeDiscountPercent` and `entitlementUnits` from sessions, orders and events. Existing orders keep their pricing and entitlement snapshot. Fixed-price subscriptions retain quantity and volume pricing for renewals; a code applies to the first payment only. A new multi-unit checkout creates its own subscription contract. Plan changes on an active multi-unit subscription require a new checkout.

Prepaid credits and uses multiply by purchased units; license products issue one key per unit. Metered usage remains single-unit. Full refunds reclaim the original entitlement snapshot and revoke all license keys for that order; partial money refunds do not automatically revoke a chosen number of packs.


### Dynamic one-time amounts: merchant-set or customer-editable

`customAmountMinor` is an integer in the selected price currency's minor units. It is accepted only from the authenticated merchant API (or an authorized existing session) for one-time prices. It must respect the saved bounds when configured. Subscriptions, meters, localized price overrides, multiple quantities and discount codes are not supported for these amount-based orders. The amount is the final gross total, with applicable tax included. Default receipt policy is payment only; regular fixed-price purchases without an override keep their normal pack entitlement.

The price switch **Allow customers to enter an amount** controls editing:

- **Off:** your server can pass `customAmountMinor`; checkout shows a fixed amount with no input or “choose amount” prompt. If the field is omitted, checkout uses the regular configured price.
- **On:** the passed amount is the initial value. Customers can change it within the configured limits. If omitted, the reference price is the initial value.

```js
const session = await client.createCheckoutSession({
  customerId: 'user_123', priceId: oneTimePriceId,
  customAmountMinor: 2549, // USD 25.49; editing follows the price switch
  metadata: { appOrderId: 'payment-1001' }
})
```

Read `options.customAmountEditable` and `options.customAmountLocked` on the returned session. Editing policy and bounds are saved with that session; changes to a price affect new sessions. Existing explicitly locked sessions remain locked. Hosted checkout updates an editable amount through `POST /api/v1/public/checkout/sessions/{token}/amount`; a browser cannot override a merchant-fixed amount without its authorized session. Public quote requests for a session include `sessionToken`. Payment submission, expiration or completion stops editing. Verify confirmed orders and payment webhooks using `customAmountMinor`, `customGrantMode`, `amountMinor` and `currency`.