Accept payments with PayVAN
One signed JSON API for card payments, two-step authorizations, refunds, subscriptions and payouts. This guide walks you through everything your backend needs, with copy-paste examples at every step.
- Get credentialsShop ID and secret from your dashboard.
- Sign a requestHMAC-SHA256 over a fixed string. How
- Take a paymentHosted page or direct API. Compare
- Handle webhooksVerify, answer 200, then process. Details
201is not "paid". A successful response means we accepted the request. The bank decides after that, and the payment may still need 3-D Secure or end up declined. The same goes for capture, cancel and refund.- The webhook is the source of truth. It tells you the final state of every operation. Reading the payment gives the same answer on demand: use it when a webhook is late or arrives out of order.
- The return URL is for the payer's eyes only. The payer may never come back, or open your success page by hand. Fulfil orders on the webhook or by reading the payment, never on the return.
The API reference lists every endpoint, field and response, generated from the OpenAPI 3.1 specification. You can import it into Postman or Insomnia, or generate a client from it. This guide explains how the pieces fit together.
01Basics#
What you receive
When your account is set up, you get the following for each shop (a shop is one store, app or brand that takes payments):
| Item | What it is for |
|---|---|
| Shop ID | A number that identifies your shop. It is sent in the X-SHOP-ID header and is part of every signature. |
| Secret | The HMAC key. You sign requests with it, and you use the same key to verify our webhooks. Keep it on your server: never ship it to a browser or mobile app. |
| Currency | Each shop works in one currency, which is set when the shop is created. A request in any other currency is rejected before a payment is created. |
| Webhook URL | Where we send payment notifications. You set it in the dashboard. |
Environments
Sandbox and live are fully separate: different credentials, different hosts, no real money in sandbox. Build and test against sandbox, then switch the base URLs and keys.
| Purpose | Sandbox | Live |
|---|---|---|
| Payments API | https://api.sandbox.payvan.net | https://api.payvan.net |
| Hosted checkout | https://pay.sandbox.payvan.net | https://pay.payvan.net |
| Dashboard | https://dash.sandbox.payvan.net | https://dash.payvan.net |
The examples in this guide use the live host. Every path works the same way on both.
Conventions
- JSON in, JSON out. Send
Content-Type: application/jsonand UTF-8. Request bodies may be up to 1 MB. - Field names are case-sensitive and
PascalCase(OrderId,Amount). - Resources and actions. A payment is a resource:
/v1/payments/{id}. Capture, cancel and refund are actions on it (POST /v1/payments/{id}/capture). Reads areGETwith filters in the query string, and lists come as{"Data": [...], "HasMore": …, "NextCursor": …}. - Amounts are decimal strings in major units:
"1499.00"or"1499". Use either no decimal part or exactly two digits after the point."1499.5",1499(a number) and"1e3"are rejected. Currencies with three minor digits (KWD, BHD, …) are not supported yet. For zero-decimal currencies such as JPY, send whole amounts. Responses still show two decimals ("1500.00"). - Currency is a three-letter ISO 4217 code such as
"USD"or"EUR". - OrderId is your reference for the purchase: 1–100 printable characters. Use a unique value per payment attempt. You can look payments up by it later.
- Transaction IDs are ours. They come back as strings (
"3554"). Every operation has one: the payment itself, each capture, each release, each refund, each payout. Every action that moves money is its own operation, with its own amount, outcome and time, failed attempts included. The payment's ID is also itsPaymentId, and every operation carries thePaymentIdof the payment it belongs to. Store the payment's ID: every action on the payment needs it. - Timestamps in responses and webhooks are RFC 3339 in UTC:
"2026-09-01T11:22:05Z".
02Authentication#
Every request carries four headers. If any is missing, or if the signature does not match, the request is rejected with 401 before anything else happens.
| Header | Value |
|---|---|
X-SHOP-ID | Your Shop ID, e.g. 1001. |
X-REQUEST-ID | A unique ID for this request. A UUID v4 is ideal. It is also your idempotency key. |
X-REQUEST-TIMESTAMP | The current time as Unix seconds, e.g. 1789732800. |
X-REQUEST-SIGNATURE | v1= followed by the lowercase hex HMAC-SHA256 of the string below. |
The string to sign
Join seven values with a newline (\n, byte 0x0A), with no trailing newline:
v1
{METHOD}
{PATH}
{SHOP_ID}
{REQUEST_ID}
{TIMESTAMP}
{hex(SHA-256(BODY))}| Part | Rule |
|---|---|
v1 | The literal version label. |
METHOD | Uppercase HTTP method: POST, GET, PATCH or DELETE. |
PATH | The path, plus the query string exactly as you send it: /v1/payments, /v1/payments?OrderId=A-1001. Do not include the scheme or host. |
SHOP_ID, REQUEST_ID, TIMESTAMP | Exactly the values you put in the three headers. |
hex(SHA-256(BODY)) | Lowercase hex SHA-256 of the raw body bytes. For an empty body (e.g. GET), hash the empty string: e3b0c442…b855. The hash is never an empty value. |
Serialize the JSON once, sign that string, and send the same string. Many HTTP clients re-encode a JSON object (key order, spacing, escaping of / or non-ASCII). If you sign one encoding and send another, the hash changes and you get 401 invalid signature.
Examples
SHOP_ID=1001
SECRET='your-secret'
API=https://api.payvan.net
PATH_=/v1/payments
BODY='{"OrderId":"A-1001","Amount":"1499.00","Currency":"USD","Description":"Pro plan"}'
REQUEST_ID=$(uuidgen | tr 'A-Z' 'a-z')
TIMESTAMP=$(date +%s)
BODY_HASH=$(printf '%s' "$BODY" | openssl dgst -sha256 -hex | awk '{print $NF}')
SIGNATURE=$(printf 'v1\nPOST\n%s\n%s\n%s\n%s\n%s' \
"$PATH_" "$SHOP_ID" "$REQUEST_ID" "$TIMESTAMP" "$BODY_HASH" \
| openssl dgst -sha256 -hmac "$SECRET" -hex | awk '{print $NF}')
curl -sS -X POST "$API$PATH_" \
-H "Content-Type: application/json" \
-H "X-SHOP-ID: $SHOP_ID" \
-H "X-REQUEST-ID: $REQUEST_ID" \
-H "X-REQUEST-TIMESTAMP: $TIMESTAMP" \
-H "X-REQUEST-SIGNATURE: v1=$SIGNATURE" \
--data-binary "$BODY"import hashlib, hmac, json, time, uuid
import requests # pip install requests
API = "https://api.payvan.net"
SHOP_ID = "1001"
SECRET = "your-secret"
def payvan(method: str, path: str, payload: dict | None = None) -> requests.Response:
body = b"" if payload is None else json.dumps(payload, separators=(",", ":")).encode()
request_id, timestamp = str(uuid.uuid4()), str(int(time.time()))
message = "\n".join(["v1", method, path, SHOP_ID, request_id, timestamp,
hashlib.sha256(body).hexdigest()])
signature = hmac.new(SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
return requests.request(method, API + path, data=body, headers={
"Content-Type": "application/json",
"X-SHOP-ID": SHOP_ID,
"X-REQUEST-ID": request_id,
"X-REQUEST-TIMESTAMP": timestamp,
"X-REQUEST-SIGNATURE": "v1=" + signature,
}, timeout=30)
r = payvan("POST", "/v1/payments",
{"OrderId": "A-1001", "Amount": "1499.00", "Currency": "USD",
"Description": "Pro plan"})
print(r.status_code, r.json())import { createHash, createHmac, randomUUID } from "node:crypto";
const API = "https://api.payvan.net";
const SHOP_ID = "1001";
const SECRET = process.env.PAYVAN_SECRET;
async function payvan(method, path, payload) {
const body = payload === undefined ? "" : JSON.stringify(payload);
const requestId = randomUUID();
const timestamp = String(Math.floor(Date.now() / 1000));
const bodyHash = createHash("sha256").update(body).digest("hex");
const message = ["v1", method, path, SHOP_ID, requestId, timestamp, bodyHash].join("\n");
const signature = createHmac("sha256", SECRET).update(message).digest("hex");
const res = await fetch(API + path, {
method,
body: body || undefined, // send exactly the string you signed
headers: {
"Content-Type": "application/json",
"X-SHOP-ID": SHOP_ID,
"X-REQUEST-ID": requestId,
"X-REQUEST-TIMESTAMP": timestamp,
"X-REQUEST-SIGNATURE": "v1=" + signature,
},
});
return { status: res.status, body: await res.json() };
}
console.log(await payvan("POST", "/v1/payments",
{ OrderId: "A-1001", Amount: "1499.00", Currency: "USD", Description: "Pro plan" }));<?php
const API = 'https://api.payvan.net';
const SHOP_ID = '1001';
$secret = getenv('PAYVAN_SECRET');
function payvan(string $method, string $path, ?array $payload, string $secret): array {
$body = $payload === null ? '' : json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$requestId = bin2hex(random_bytes(16));
$timestamp = (string) time();
$message = implode("\n", ['v1', $method, $path, SHOP_ID, $requestId, $timestamp, hash('sha256', $body)]);
$signature = hash_hmac('sha256', $message, $secret);
$ch = curl_init(API . $path);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_POSTFIELDS => $body,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'X-SHOP-ID: ' . SHOP_ID,
'X-REQUEST-ID: ' . $requestId,
'X-REQUEST-TIMESTAMP: ' . $timestamp,
'X-REQUEST-SIGNATURE: v1=' . $signature,
],
]);
$response = curl_exec($ch);
return [curl_getinfo($ch, CURLINFO_RESPONSE_CODE), json_decode($response, true)];
}
print_r(payvan('POST', '/v1/payments',
['OrderId' => 'A-1001', 'Amount' => '1499.00', 'Currency' => 'USD', 'Description' => 'Pro plan'], $secret));// Go 1.21+, standard library only.
package main
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
)
const (
api = "https://api.payvan.net"
shopID = "1001"
secret = "your-secret"
)
func payvan(method, path string, payload any) (int, []byte, error) {
var body []byte
if payload != nil {
var err error
if body, err = json.Marshal(payload); err != nil {
return 0, nil, err
}
}
var id [16]byte
rand.Read(id[:])
requestID := hex.EncodeToString(id[:])
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
sum := sha256.Sum256(body)
message := strings.Join([]string{"v1", method, path, shopID, requestID, timestamp,
hex.EncodeToString(sum[:])}, "\n")
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(message))
req, err := http.NewRequest(method, api+path, bytes.NewReader(body))
if err != nil {
return 0, nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-SHOP-ID", shopID)
req.Header.Set("X-REQUEST-ID", requestID)
req.Header.Set("X-REQUEST-TIMESTAMP", timestamp)
req.Header.Set("X-REQUEST-SIGNATURE", "v1="+hex.EncodeToString(mac.Sum(nil)))
resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
out, err := io.ReadAll(resp.Body)
return resp.StatusCode, out, err
}
func main() {
status, body, err := payvan("POST", "/v1/payments", map[string]string{
"OrderId": "A-1001", "Amount": "1499.00", "Currency": "USD", "Description": "Pro plan",
})
fmt.Println(status, string(body), err)
}// Java 17+, no dependencies (java.net.http).
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.time.Instant;
import java.util.HexFormat;
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class PayvanRequest {
static final String API = "https://api.payvan.net";
static final String SHOP_ID = "1001";
static final String SECRET = System.getenv("PAYVAN_SECRET");
static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
static HttpResponse<String> payvan(String method, String path, String json) throws Exception {
byte[] body = json == null ? new byte[0] : json.getBytes(StandardCharsets.UTF_8);
String requestId = UUID.randomUUID().toString();
String timestamp = Long.toString(Instant.now().getEpochSecond());
HexFormat hex = HexFormat.of();
String message = String.join("\n", "v1", method, path, SHOP_ID, requestId, timestamp,
hex.formatHex(MessageDigest.getInstance("SHA-256").digest(body)));
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
String signature = hex.formatHex(mac.doFinal(message.getBytes(StandardCharsets.UTF_8)));
HttpRequest request = HttpRequest.newBuilder(URI.create(API + path))
.timeout(Duration.ofSeconds(30))
.header("Content-Type", "application/json")
.header("X-SHOP-ID", SHOP_ID)
.header("X-REQUEST-ID", requestId)
.header("X-REQUEST-TIMESTAMP", timestamp)
.header("X-REQUEST-SIGNATURE", "v1=" + signature)
.method(method, HttpRequest.BodyPublishers.ofByteArray(body))
.build();
return HTTP.send(request, HttpResponse.BodyHandlers.ofString());
}
public static void main(String[] args) throws Exception {
HttpResponse<String> r = payvan("POST", "/v1/payments",
"{\"OrderId\":\"A-1001\",\"Amount\":\"1499.00\",\"Currency\":\"USD\",\"Description\":\"Pro plan\"}");
System.out.println(r.statusCode() + " " + r.body());
}
}Ready-made helpers with built-in self-tests: payvan_sign.py, payvan-sign.mjs, payvan_sign.php, payvan_sign.go and PayvanSign.java. Each signs requests and verifies webhooks, with no dependencies. Run one directly to check it against the reference vectors below.
Reference vector
Put these inputs into your code. If you get the same signature, your implementation is correct. Our own test suite checks the same values.
SECRET = 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF
METHOD = POST
PATH = /v1/payments
SHOP_ID = 1001
REQUEST_ID = 2f0f2b1c-6c4b-4a1e-9a3d-8b7f0c5e1d42
TIMESTAMP = 1789732800
BODY = {"OrderId":"A-1001","Amount":"1499.00","Currency":"USD"}
hex(SHA-256(BODY)) = e2c70249438f933caea47734fe15eb0b3a28b9dd4b14c2e26ed452f4f99a7562
X-REQUEST-SIGNATURE = v1=429303de742eaefaa085170c872d03d4d9f40ca3457c5507dab76ebaadb6bfdaClock window
We accept X-REQUEST-TIMESTAMP up to 5 minutes before or after our clock. Outside that window you get 401 with our current time in the body, so you can see how far your clock has drifted:
{ "error": "request timestamp outside allowed window", "server_time": 1789733105 }Run NTP on your servers. The timestamp is part of the signature, so a captured request cannot be replayed later.
Rotating your secret
Secrets rotate with no downtime. When we issue a new secret, the old one keeps working for 7 days, and both are valid in that period.
Request a new secret
From this moment both keys are valid.
Deploy it when convenient
Any time within the week. You do not need to coordinate the switch with us.
Tell us you have switched
We revoke the old key right away. If you don't, it expires on its own at the end of the 7 days, and requests still signed with it get
401.
During a rotation, webhooks carry one signature per valid key. See verifying webhooks.
03Idempotency & retries#
Networks fail. Timeouts, dropped connections and restarts happen, and the question is always the same: did my payment go through? X-REQUEST-ID lets you retry safely.
- We store our response for each
X-REQUEST-IDfor 24 hours. If you repeat a request with the same ID in that time, you get the stored response, with the same status code, and nothing is done twice. - Money never moves twice for the same
X-REQUEST-ID, even after 24 hours. A payment, authorization or payout is not created twice for the same ID andOrderId, and a capture, release or refund is not created twice for the same ID and payment: the retry returns the operation that already exists, with201. - If the first request is still running when the retry arrives, you get
409withErrorCode: "REQUEST_IN_PROGRESS"in the usual error format:{"error": "duplicate request in progress", "ErrorCode": "REQUEST_IN_PROGRESS"}. Wait a second and retry again. If the first request died without an answer, this lasts at most 90 seconds. - An ID belongs to one request. The same
X-REQUEST-IDwith a different method, path or body gets422withErrorCode: "IDEMPOTENCY_KEY_REUSED", not someone else's stored response. - Re-sign every retry. Keep
X-REQUEST-IDthe same, but use a freshX-REQUEST-TIMESTAMPand signature. Idempotency is tied to the ID, not to the signature.
New operation → new X-REQUEST-ID. Retry of the same operation → the same X-REQUEST-ID. A timeout is a reason to retry with the old ID, never a reason to create a new payment.
Store the X-REQUEST-ID together with your order before you send the request, so a retry after a crash uses the same one. A retry with a new ID is a new operation: a second refund with a new ID is a second refund. If you lost the ID, read the payment first: its Operations show what already went through.
Rate limits
Requests are limited per Shop ID per calendar minute (600 by default; ask us if you need more). Over the limit you get 429 with ErrorCode: RATE_LIMITED. The counter resets at the start of the next minute.
We send no rate-limit headers: no X-RateLimit-* and no Retry-After. Count your own requests if you run close to the limit. After a 429, wait until the next minute and retry with the same X-REQUEST-ID. A rejected request is not stored, so the retry is processed normally.
04Choose an integration#
There are two ways to take a payment. The key difference is who collects the card details. That decides your PCI DSS scope and how much you have to build.
Hosted checkout Recommended
- Card data never touches your servers, which keeps your PCI DSS scope to a minimum. Which SAQ applies (often SAQ A) depends on the current PCI SSC requirements and your integration; confirm it with your acquirer or assessor
- We handle 3-D Secure, bank redirects and returns
- Apple Pay and Google Pay where enabled
- English, Spanish, Indonesian and Russian
- You build: one API call and a webhook handler
Direct API (host-to-host)
- Requires your own PCI DSS certification
- You run the 3-D Secure steps: iframe, form and confirmation
- Full control over the payment UI
- Wallet tokens (Apple Pay, Google Pay) supported
- You build: form, 3DS, status polling and a webhook handler
If in doubt, use hosted checkout. The direct API is worth it only if you already run a PCI-certified card environment. Building one just to style a form is rarely worth it.
Everything after the payment works the same for both: capture, cancel and refund, reading payments, and webhooks.
05Hosted checkout#
Hosted checkout runs on its own host, pay.payvan.net, and uses the same signature as the payments API.
-
Create a session from your server
POST/v1/checkout/sessionspay.payvan.netrequest{ "PaymentType": "Pay", "Amount": "49.00", "Currency": "USD", "OrderId": "order-1043", "Description": "Pro plan, November", "ExtraData": { "SuccessUrl": "https://shop.example/paid", "DeclineUrl": "https://shop.example/failed", "CancelUrl": "https://shop.example/cart", "ReturnUrl": "https://shop.example/return" }, "CustomerInfo": { "Language": "en", "Email": "payer@example.com" } }201 Created{ "SessionId": "6d0f3c1e-…", "CheckoutUrl": "https://pay.payvan.net/pay/6d0f3c1e-…", "ExpiresAt": "2026-09-01T12:40:00Z" }Field Description PaymentTypeoptionalPay(default) charges right away.Blockonly authorizes the amount. You capture it later. Anything else is rejected withINVALID_PAYMENT_TYPE.PaymentMethodsoptionalOffer only these of your shop's methods on the page, e.g. ["Card", "SBP"]. Not set: every method available to the shop. The list only narrows: a method switched off for the shop stays hidden. A hold allows onlyCard,ApplePayandGooglePay; a subscription onlyCard.AmountrequiredDecimal string, e.g. "49.00".CurrencyrequiredYour shop's currency. OrderIdrequiredYour reference, up to 100 characters. DescriptionrequiredWhat is being paid for. Shown to the payer on the page. ExtraDataoptionalReturn addresses: SuccessUrl,DeclineUrl,CancelUrl, andReturnUrlas the fallback for any that are not set. Each must be an absolutehttps://orhttp://URL. Your own string fields come back in webhooks, as with a direct payment.WebhookUrloptionalSend this payment's webhooks here instead of your shop's webhook URL. RebillFlagoptionaltruesaves the card for later merchant-initiated charges or a subscription.SubscriptionoptionalStart a subscription with this first payment. Requires RebillFlag: trueand anOfferUrl.CustomerInfo.LanguageoptionalPage language: en,es,idorru. If not set, we use your shop default, then the payer's browser language, then English. An unsupported code counts as not set.CustomerInfo.Email,PhoneoptionalIf you already know them, we don't ask the payer again. It is the same flat body as a direct payment (
POST /v1/payments), only without card details: the page collects them.No card data here.This request must not contain
PaymentDetailswith card fields. If it does, it is rejected with400 CARD_DATA_NOT_ALLOWED. This protects your PCI scope. -
Send the payer to
CheckoutUrlUse an HTTP redirect or a link. The page handles the rest: card form, wallets, 3-D Secure, the bank's page and the way back. A session lasts 30 minutes. The exact deadline is in
ExpiresAt. -
Show the result, trust the webhook
When the payment finishes, the payer returns to
SuccessUrl,DeclineUrlorCancelUrl, or toReturnUrlif the specific one is not set.A return is not a confirmation.The payer may close the tab on the bank's page and never come back, or open your success URL by hand. Fulfil the order only on the webhook or by reading the payment. Use the return page only to show the payer a message.
Opening the checkout on your site
Instead of a redirect, you can open the same page over your store, inside your own page or in a popup window, and get its progress in JavaScript. The library is /sdk/checkout.v1.js on the checkout host. It takes only the CheckoutUrl: the session is still created by your server, and your secret never goes to the browser.
<script type="module" src="https://pay.payvan.net/sdk/checkout.v1.js"
integrity="sha256-…" crossorigin="anonymous"></script>
<script type="module">
// Your server calls POST /v1/checkout/sessions and returns CheckoutUrl.
const { url } = await fetch('/create-payment', { method: 'POST' }).then(r => r.json());
const checkout = WebpayCheckout.open({
url,
mode: 'auto', // modal | inline | popup | redirect | auto | fields
container: '#pay', // inline and fields only
onReady() {},
onFinish(e) {}, // { sessionId, outcome }
onClose(e) {}, // { sessionId, reason: 'payer' | 'merchant' | 'fallback' }
onFallback(e) {}, // { sessionId, from, to, reason }
});
const result = await checkout.result;
</script>The current integrity value is at /sdk/checkout.v1.js.sri. Copy it into the tag: with it, the browser refuses a changed file.
| Mode | What the payer sees |
|---|---|
modal | A window over your store. Full screen on a narrow screen. |
inline | A block inside your container element. Its height follows the content. |
popup | A separate browser window. Open it from a click, or the browser blocks it. |
redirect | An ordinary redirect to CheckoutUrl. |
autodefault | modal on desktop, redirect on phones and in in-app browsers. |
fields | Only the card fields, inside your container, with your own pay button. See Card fields in your own form. |
Allow your site first. The page opens in a frame or a popup only on the sites listed in your shop's settings: in the dashboard, shop page, Sites allowed to embed. Enter one origin per line, such as https://shop.example: https:// only, no path, no wildcards, up to 20 sites. http://localhost works for testing on your machine. If the page does not answer within 10 seconds, for example because your site is not listed, the library falls back to a redirect and calls onFallback. Pass fallback: 'none' to stay on your page instead.
- Closing the window does not cancel the payment. The session lives until
ExpiresAt, and you can open the sameCheckoutUrlagain. - While a payment is being processed, Esc and a click outside the window do not close it. The close button stays.
- In a frame on your site (
modal,inline,fields) Google Pay works as on the full page. Apple Pay shows only where the browser allows it inside a frame (Safari 17 and later); usepopuporredirectif every Apple Pay user must see it. - When the bank needs its own page, the whole tab goes there through our address, and the payer comes back to the checkout and then to your return URL, as with a redirect.
onFinish is not a confirmation.
It is a message in the payer's browser, and any script on your page can fake it. Use it to update your UI. Fulfil the order only on the webhook or by reading the payment.
Card fields in your own form
With mode: 'fields' your container gets only the card fields, plus Apple Pay and Google Pay buttons if your shop offers them. There is no amount, no description and no pay or cancel button: those are yours. The card number still lives in our frame. Your page learns only whether the fields are complete.
<div id="card"></div>
<button id="pay" disabled>Place order</button>
<script type="module">
const { url } = await fetch('/create-payment', { method: 'POST' }).then(r => r.json());
const pay = document.getElementById('pay');
const checkout = WebpayCheckout.open({
url,
mode: 'fields',
container: '#card',
onValidity(e) { pay.disabled = !e.complete; }, // { sessionId, complete }
onBusy(e) { if (e.busy) pay.disabled = true; }, // { sessionId, busy }
onFinish(e) {}, // { sessionId, outcome }
});
pay.onclick = () => checkout.submit();
</script>submit()asks the page to pay. It checks the fields itself and shows errors inside the block. The result comes inonStateandonFinish. Enter in a card field does not pay, so you can check your own fields first.- When the bank asks the payer to confirm (3-D Secure), the library lifts the same block into a window over your page and puts it back afterwards. The block keeps its place in your layout meanwhile.
- There is no email field. Send the payer's email in the session request,
CustomerInfo.Email, if you want us to send a receipt. - A session is one payment. After
onFinishreportsdeclined, create a new session to let the payer try again. - Your site must be in Sites allowed to embed, as for
inline.
Validation errors
Checkout rejects a bad request with 400 {"error": "...", "ErrorCode": "..."}:
| Code | Reason |
|---|---|
INVALID_JSON | The body is not valid JSON. |
INVALID_ORDER_ID | Empty, or longer than 100 characters. |
INVALID_AMOUNT | Not a positive decimal string. |
INVALID_CURRENCY | Not a three-letter code, or not your shop's currency. |
INVALID_DESCRIPTION | Description is missing. |
INVALID_PAYMENT_TYPE | PaymentType is neither Pay nor Block. |
INVALID_PAYMENT_METHODS | PaymentMethods is not a list of method names, or names a method a hold or a subscription can't use. |
INVALID_RETURN_URL | A return URL is not an absolute http(s) URL. |
CARD_DATA_NOT_ALLOWED | Card fields were sent to the hosted page. |
SUBSCRIPTION_REQUIRES_REBILL_FLAGINVALID_INTERVALINVALID_OFFER_URLINVALID_START_AT | The Subscription block is incomplete or inconsistent. See subscriptions. |
Payment links
A payment link is an invoice you send to a customer by email or chat. It has its own address and page. Links can be single-use (closed after one successful payment) or reusable, with a fixed amount or an amount the payer enters. They can ask the payer for extra fields and require acceptance of your terms. You create, view and revoke links in the dashboard, with no code needed. There is no API for managing links yet; it is planned. Payments made through a link are ordinary payments: they show up in GET /v1/payments, and their webhooks carry PaylinkCode naming the link.
06Direct card payments#
With the direct API you send the card (or a wallet token) in the request. You need your own PCI DSS certification to do this.
One endpoint creates every payment. The body says how to run it: PaymentType Pay (the default) charges right away, Block puts the amount on hold, and RebillId instead of card details charges a saved card.
{
"PaymentType": "Pay",
"Amount": "49.00",
"Currency": "USD",
"OrderId": "order-1043",
"Description": "Pro plan, November",
"PaymentMethod": "Card",
"RebillFlag": false,
"CustomerInfo": {
"Email": "payer@example.com",
"Phone": "15550100",
"IP": "203.0.113.10",
"Country": "US",
"Language": "en"
},
"PaymentDetails": {
"CardholderName": "JANE DOE",
"CardNumber": "4111111111111111",
"ExpMonth": "12",
"ExpYear": "2030",
"CVC": "123"
},
"ExtraData": {}
}{
"TransactionId": "3554",
"OrderId": "order-1043",
"Amount": "49.00",
"Currency": "USD"
}The payment may need 3-D Secure or a redirect to the bank. Find out the result from the webhook, or by reading the payment (GET /v1/payments/3554): once right away to get the next step, then until it reaches a final state.
Request fields
| Field | Description |
|---|---|
PaymentType | Pay (default) charges right away. Block puts the amount on hold until you capture or cancel it. Anything else gets 400 INVALID_PAYMENT_TYPE. |
Amountrequired | Decimal string. Must not exceed the per-payment cap for your shop. |
Currencyrequired | Your shop's currency. |
OrderIdrequired | Your reference, 1–100 printable characters. |
Description | What is being paid for. |
PaymentMethod | Card, ApplePay or GooglePay. Other methods (local schemes, bank transfers) are enabled per shop. Ask us which ones you can use. |
RebillFlag | true saves the card for later charges. |
CustomerInfo | Payer details: Email, Phone, IP, Country (ISO 3166-1 alpha-2), Language, Address, Town, ZIP. Send the payer's IP whenever you have it: some banks require it, and it improves fraud scoring. For customer profiles and KYC, see Customers. |
PaymentDetails | The card: CardNumber (13–19 digits, passes the Luhn check), ExpMonth (1–12), ExpYear (30 or 2030), CVC (3–4 digits), CardholderName (3–30 Latin letters, spaces, . , -). For wallets, send Token instead. See below. |
ExtraData | Flat object of your own string values. It is stored with the payment and comes back in webhooks as ExtraData. A few names are used by us and are not echoed back: IP, Email, Phone, Country, Town, Address, ZIP, Region, Language, CustomerId, UserAgent, AcceptHeader, WebhookUrl and the checkout return addresses. |
WebhookUrl | Send the webhooks of this payment (and of its captures, releases and refunds) to this absolute http(s) URL instead of your shop's webhook URL. A bad URL gets 400 INVALID_WEBHOOK_URL. |
Subscription | Start a subscription with this payment. |
Authorize now, capture later
Send the same body with "PaymentType": "Block". On success the payment becomes preauthorized: the money is held on the card. Then you either capture it with POST /v1/payments/{id}/capture or release it with POST /v1/payments/{id}/cancel. Use this when you ship goods later or need to confirm stock first.
Charging a saved card
If the first payment was made with RebillFlag: true, its StateDetails contain RebillId. Create a payment with it instead of card details to charge the same card again without the payer present:
{
"RebillId": "3554",
"OrderId": "order-1107",
"Amount": "49.00",
"Currency": "USD",
"Description": "Pro plan, December"
}{
"TransactionId": "3871",
"OrderId": "order-1107",
"Amount": "49.00",
"Currency": "USD"
}Give each charge its own OrderId. Add "PaymentType": "Block" to authorize instead of charging. Don't send PaymentDetails together with RebillId: such a body is rejected with 400 INVALID_REQUEST. For recurring billing on a schedule, use a subscription instead. It handles retries, reminders and payer emails for you.
Saved-card limits can be enabled for your shop: how many charges and what total a saved card allows, and for how long. With limits enabled, a rebill is rejected with 400 SAVED_CARD_LIMIT_REACHED when no charges or amount are left, and with 400 SAVED_CARD_PERMISSION_EXPIRED when the permission to charge the card has run out (the card itself may still be valid). Subscription charges are not limited this way: a subscription follows its own terms.
Call it when the customer removes the card from their account. There is no body; the response is 200 {"RebillId": "3554"}. After that, payments with this RebillId are rejected with 409 SAVED_CARD_INACTIVE.
Apple Pay and Google Pay
Wallet tokens use the same endpoint. Name the wallet in PaymentMethod and pass the token in PaymentDetails.Token exactly as the wallet returned it. Apple Pay gives you an object and Google Pay a string. Do not decode, extend or re-wrap it.
{
"Amount": "49.00", "Currency": "USD", "OrderId": "order-1043",
"Description": "Pro plan, November",
"PaymentMethod": "ApplePay",
"CustomerInfo": { "Email": "payer@example.com", "IP": "203.0.113.10" },
"PaymentDetails": {
"Token": {
"paymentData": { "version": "EC_v1", "data": "…", "signature": "…",
"header": { "ephemeralPublicKey": "…", "publicKeyHash": "…", "transactionId": "…" } },
"paymentMethod": { "displayName": "Visa 1234", "network": "Visa", "type": "debit" },
"transactionIdentifier": "…"
}
}
}{
"Amount": "49.00", "Currency": "USD", "OrderId": "order-1044",
"Description": "Pro plan, November",
"PaymentMethod": "GooglePay",
"PaymentDetails": {
"Token": "{\"protocolVersion\":\"ECv2\",\"signature\":\"…\",\"intermediateSigningKey\":{…},\"signedMessage\":\"…\"}"
}
}Don't send card fields next to a token: a body with both is rejected. Whether a wallet payment needs 3-D Secure depends on the acquiring route behind your shop, not on the wallet alone. Usually the cryptogram in the token is enough and the payment completes without a payer step. The bank or the card scheme may still ask for extra authentication, and then the payment goes to wait_for_3ds or redirect, exactly like a card payment. Handle those states for wallet payments too. Wallets are enabled per shop, because support depends on the acquiring bank behind your payments.
Validation errors
These are checked before a payment is created. You get 400 {"error": "...", "ErrorCode": "..."}:
| ErrorCode | Reason |
|---|---|
INVALID_ORDER_ID | Empty, longer than 100 characters, or contains control characters. |
INVALID_AMOUNT | Not a positive decimal string, or above your shop's cap. |
INVALID_CURRENCY | Not a three-letter code, or not your shop's currency. |
INVALID_CARD_NUMBER | Not 13–19 digits, or fails the Luhn check. |
INVALID_CARD_DATE | Month or year missing or not a valid date. |
INVALID_CARDHOLDER | Not 3–30 Latin letters, spaces, ., , or -. |
INVALID_CVC | Not 3 or 4 digits. |
INVALID_PAYMENT_DETAILS | PaymentDetails is not an object, card fields were sent with a wallet token, or a token was sent with a non-wallet method. |
INVALID_WALLET_TOKEN | Token missing, wrong shape, missing a required field, or larger than 16 KB. |
INVALID_PAYMENT_TYPE | PaymentType is neither Pay nor Block. |
INVALID_REQUEST | A field has the wrong JSON type, or RebillId came together with PaymentDetails. |
INVALID_JSON | The body is not valid JSON. |
An expired card that passes the format check is rejected next, with 400 and ErrorCode: "CARD_EXPIRED".
073-D Secure#
With hosted checkout there is nothing to do: the page handles 3-D Secure. With the direct API, you do not implement the 3DS protocol. You run the step we give you in the payment's StateDetails, then tell us when it is done. A payment has zero, one or two steps.
Browser data for 3DS 2
With the direct API, the payer's browser is yours, so you send its details with the payment. The issuer's risk check runs on them: the fuller they are, the more often a payment passes without a challenge. Collect them in the payer's browser and put them in ExtraData as strings. The payer's IP goes in CustomerInfo.IP. We pass what you send as is and never make values up, so a missing field stays empty. Hosted checkout collects all of this itself.
| ExtraData key | Where to take it |
|---|---|
AcceptHeader | The Accept header of the payer's request to your server. |
UserAgent | navigator.userAgent |
Language | navigator.language. If you also send CustomerInfo.Language, that one is used. |
ColorDepth | screen.colorDepth |
ScreenWidth, ScreenHeight | screen.width, screen.height |
TimeZoneOffset | new Date().getTimezoneOffset(), in minutes |
JavaEnabled | navigator.javaEnabled(): "true" or "false" |
JavaScriptEnabled | "true" when you collected the rest with JavaScript |
const browser = {
UserAgent: navigator.userAgent,
Language: navigator.language || "",
ColorDepth: String(screen.colorDepth),
ScreenWidth: String(screen.width),
ScreenHeight: String(screen.height),
TimeZoneOffset: String(new Date().getTimezoneOffset()),
JavaEnabled: String(typeof navigator.javaEnabled === "function" && navigator.javaEnabled()),
JavaScriptEnabled: "true",
};
// Send it to your backend and merge it into ExtraData, together with the
// Accept header of that request: ExtraData.AcceptHeader = req.headers.accept-
Read the payment and get the step
While the state is wait_for_3ds,
StateDetails.ThreeDSdescribes what to do:StateDetails.ThreeDS{ "Version": "2.2.0", "Step": "method", "MethodUrl": "https://acs.bank.example/method", "MethodData": "eyJ0aHJlZURTU2VydmVyVHJhbnNJRCI6…", "Timeout": 10 }Step What to do in the payer's browser methodPOST a form with one field, threeDSMethodData=MethodData, toMethodUrlin a hidden iframe. The step is complete when the 3DS Method Notification arrives: the ACS posts it to a PayVAN page inside that iframe, and the page sends your page a message. No message withinTimeoutseconds meanstimeout.challengewithCReq3DS 2.x. POST a form with field creq=CReqtoAcsUrlin a visible iframe or window. The payer authenticates with their bank. The ACS posts the result (cres) to a PayVAN page inside that frame, and the page passes it to your page in a message.challengewithPaReq3DS 1.0. POST a form with PaReq,MDand yourTermUrltoAcsUrl. The bank postsPaResandMDback to yourTermUrl.<iframe name="tds-method" style="display:none"></iframe> <form id="tds-method-form" method="POST" action="{MethodUrl}" target="tds-method"> <input type="hidden" name="threeDSMethodData" value="{MethodData}"> </form> <script> const PAYVAN = "https://pay.payvan.net"; // https://pay.sandbox.payvan.net in the sandbox let finished = false; function done(status) { // "completed", "timeout" or "error" if (finished) return; finished = true; clearTimeout(timer); window.removeEventListener("message", onMessage); // The body of POST /v1/payments/{id}/confirm. Your backend signs it and // sends it as is: Step is required, Status is capitalised. fetch("/your-backend/3ds-confirm", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ Step: "method", Status: status }) }); } // The 3DS Method Notification, relayed by the PayVAN page in the iframe. // The iframe's "load" event is not a signal: it fires for any page, // including one that sent no notification. function onMessage(e) { if (e.origin !== PAYVAN) return; const m = e.data; if (!m || m.type !== "webpay:3ds" || m.step !== "method") return; done(m.status); // "completed" } window.addEventListener("message", onMessage); const timer = setTimeout(() => done("timeout"), {Timeout} * 1000); document.getElementById("tds-method-form").submit(); </script><iframe name="tds-challenge" width="400" height="600"></iframe> <form id="tds-challenge-form" method="POST" action="{AcsUrl}" target="tds-challenge"> <input type="hidden" name="creq" value="{CReq}"> </form> <script>document.getElementById("tds-challenge-form").submit();</script> <script> // The ACS posts "cres" to the PayVAN page in the frame, which sends it here: // { type: "webpay:3ds", step: "challenge", status: "completed", cres: "…" } window.addEventListener("message", (e) => { if (e.origin !== "https://pay.payvan.net") return; // the sandbox: pay.sandbox.payvan.net const m = e.data; if (!m || m.type !== "webpay:3ds" || m.step !== "challenge") return; // The body of POST /v1/payments/{id}/confirm, signed and sent by your backend. fetch("/your-backend/3ds-confirm", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ Step: "challenge", CRes: m.cres }) }); }); </script> -
Receive the step's outcome
Both steps end on a PayVAN page inside your iframe, which tells your page with
postMessage. Accept only messages from the PayVAN origin and of typewebpay:3ds. The browser delivers them only to an origin we know, so tell us the origin of the page that opens the frames when your account is set up. For themethodstep, wait forstep: "method"and fall back totimeout; never take the iframe'sloadevent as completion. It fires for whatever page the ACS ends on, and confirming then would send the payment on before the issuer has the fingerprint. -
Tell us the step is done
POST/v1/payments/{id}/confirmrequest — one of{ "Step": "method", "Status": "completed" } { "Step": "challenge", "CRes": "eyJ0aHJlZURTU2Vy…" } { "PaRes": "eJzNWFmTo7gS…", "MD": "3554-a1" }Statusiscompleted(default),timeoutorerror. For themethodstep, a timeout or error is fine: authentication continues without browser fingerprinting. The response is200with the usualTransactionId,OrderId,Amount,Currency. -
Read the payment again
You get either the next step or the outcome. There are never more than two steps.
The redirect state
Some banks and providers take the payer to their own page. Send the payer to RedirectUrl (the same as in the 3DSRedirect webhook) using RedirectMethod. RedirectUrl is our page, not the bank's: it sends the payer on to the bank in the way the bank expects, so a plain browser redirect or a link is enough.
Today RedirectMethod is GET and there are no RedirectParams. If RedirectMethod ever comes as POST, build an auto-submitting form with hidden fields from RedirectParams.
After the bank, the payer comes back through PayVAN to your return URL. The bank never sees your addresses.
Authentication result
Final states include StateDetails.ThreeDSResult with Version, TransStatus, ECI, DsTransId and AcsTransId. The authentication value (CAVV/AAV) is never returned: only the bank needs it.
| TransStatus | Meaning |
|---|---|
Y | Authenticated. |
A | Attempted. Liability shift still applies. |
N | Not authenticated. |
R | Rejected by the issuer. |
U | Authentication unavailable. |
I | Not required (exemption). |
08Capture, cancel, refund#
Three actions work on an existing payment. The payment's ID goes in the path: /v1/payments/{id}/capture, /cancel, /refunds. The amount is optional on all three, and that is the main thing to know about them:
no amount → the whole remaining balance
amount → exactly that amount, if the remaining balance allowsWe track the remaining balance, and it changes after every partial operation. If you ask for more than what remains, you get 400 AMOUNT_MISMATCH, with what is left in Details.AvailableAmount. The body may be empty; if you send Currency, it is checked against your shop's currency.
{ "Amount": "30.00",
"Currency": "USD" }{ "TransactionId": "3551",
"OrderId": "order-1043",
"Amount": "30.00",
"Currency": "USD" }A partial capture closes the authorization: the rest is released, not left on hold. After a partial capture, you can refund up to the captured amount, not the original hold. A capture is a separate operation of type Capture: the response (201) carries its own TransactionId, and its webhook arrives under that ID with the payment's PaymentId.
The response means the capture was accepted, not that the money was taken: the bank answers after it. When it succeeds, the capture operation becomes success with the captured amount, the payment becomes success too, and a Capture webhook arrives. If the bank refuses, the capture operation becomes declined with DeclineCode and DeclineReason, and a Fail webhook arrives under its ID. The payment stays preauthorized: the hold is still there, so you can capture again or cancel it.
A payment has one capture or release in progress at a time. Another one sent before the first has an outcome gets 409 OPERATION_IN_PROGRESS; the operation in progress is in the payment's Operations.
One action stops a payment, whatever state it is in. On a hold (preauthorized) it releases the money, fully or partly. On a payment waiting for the payer (waiting_action) it closes the payment at the payer's request: it becomes declined with DeclineCode: "CANCELLED_BY_USER", and you get a Fail webhook. A captured payment is not cancelled but refunded; cancelling it gets 409 BAD_STATUS_FOR_CANCEL.
{ "Amount": "20.00",
"Currency": "USD" }{ "TransactionId": "3553",
"OrderId": "order-1043",
"Amount": "20.00",
"Currency": "USD" }Note the different TransactionId. A release, partial or full, is a separate operation of type Void, and its webhook arrives under the new ID with PaymentId: "3552". After a partial release the payment stays preauthorized for the remaining 29.00, which you can capture or cancel next; after a full one it becomes voided. Cancelling a payment that waits for the payer moves no money and creates no operation: the payment's own ID comes back with 200.
If the bank refuses a release, the hold is still there. The release operation becomes declined with DeclineCode and DeclineReason, a Fail webhook arrives under its ID, and the payment stays preauthorized as it was.
{ "Currency": "USD" }{ "TransactionId": "3556",
"OrderId": "order-1043",
"Amount": "19.00",
"Currency": "USD" }A refund always creates a separate operation of type Refund with the payment's PaymentId. You can refund in parts until nothing is left. After that, any refund gets AMOUNT_MISMATCH with AvailableAmount: "0.00". All refunds of a payment are listed in its Operations.
The Amount in the response is always the amount actually applied. If you left the amount empty, it is the remaining balance we calculated. Book that value, not the one you sent.
The rule for status codes: 201 when a new operation was created (its TransactionId is in the body), 200 when the payment itself was acted on.
When an action is not allowed
| Action | Allowed from | Otherwise |
|---|---|---|
| Capture | preauthorized | 409 BAD_STATUS_FOR_CHARGE |
| Cancel | preauthorized, waiting_action | 409 BAD_STATUS_FOR_CANCEL |
| Refund | success (captured), not a payout | 409 BAD_STATUS_FOR_REFUND |
| Confirm | wait_for_3ds, redirect (a repeat after the outcome is accepted too) | 409 BAD_STATUS_FOR_CONFIRM |
09Reading payments#
{
"TransactionId": "3554",
"PaymentId": "3554",
"Type": "Pay",
"OrderId": "order-1043",
"TransactionState": "success",
"StateDetails": {
"Amount": "49.00",
"Currency": "USD",
"RemainingAmount": "19.00",
"CardMasked": "411111******1111",
"RRN": "123456789012",
"RebillId": "3554",
"DateTime": "2026-09-01T11:22:05Z"
},
"Operations": [
{ "TransactionId": "3556", "PaymentId": "3554", "Type": "Refund",
"OrderId": "order-1043", "TransactionState": "success",
"StateDetails": { "Amount": "30.00", "Currency": "USD", "DateTime": "2026-09-02T08:10:00Z" } }
]
}The payment's own state says where it stands, and RemainingAmount is what can still be captured, cancelled or refunded. Operations lists every capture, release and refund of the payment, failed attempts included, oldest first, each with its own ID, amount, state and time; it is empty if there are none. This one read is enough to reconcile a payment.
Read the payment, and act on it, by its own ID. The ID of a capture, a release, a refund or a payout is not a payment ID: reading it as a payment, or capturing, cancelling or refunding by it, gets 404 PAYMENT_NOT_FOUND. Every operation carries the PaymentId to use instead.
One operation of any kind by the TransactionId from a response or a webhook: a payment, a capture, a release, a refund or a payout. Type says which (Pay, Block, Capture, Void, Refund, Payout), and PaymentId points to the payment. An unknown ID returns 404 with ErrorCode: "TRANSACTION_NOT_FOUND".
{
"Data": [
{ "TransactionId": "3554", "PaymentId": "3554", "Type": "Pay", "OrderId": "order-1043",
"TransactionState": "success", "StateDetails": { "Amount": "49.00", "Currency": "USD", "…": "…" } }
],
"HasMore": false
}Your payments, newest first, without their operations (read a payment for those). All filters are optional and go in the query string:
| Parameter | Meaning |
|---|---|
OrderId | Payments for this order. An order can have several: a declined attempt and a retry, for example. Use it to recover after a lost response. |
From, To | Created in this period, both ends included. RFC 3339; a date with an offset (2026-09-01T00:00:00Z) is taken as is, one without an offset is read in TimeZone. |
TimeZone | IANA name for dates without an offset. Default UTC. |
States | Comma-separated state names from the table below, e.g. success,declined. Empty means all. |
Limit | Page size, 1–100. Default 20. |
Cursor | When HasMore is true, pass the page's NextCursor here for the next page. |
An unknown parameter is rejected with 400 INVALID_REQUEST rather than ignored: a typo in a filter would otherwise return everything. Sign the path together with the query string, exactly as you send it.
States
TransactionState is always one of these ten values:
| State | Meaning | Final |
|---|---|---|
| success | Money captured, or refunded (for a refund operation). | yes |
| preauthorized | Amount on hold, waiting for capture or cancel. | yes* |
| voided | Hold released. | yes |
| pending | In progress. No final answer from the bank yet. | no |
| wait_for_3ds | Waiting for you to run a 3DS step. | no |
| redirect | Send the payer to the bank's page. | no |
| waiting_action | Waiting for the payer to act: scan a QR code, send a transfer, confirm in an app — what to show is in Display; or enter details the provider needs — which ones is in Collect. | no |
| declined | Declined by the bank or by fraud checks, or timed out. | yes |
| cancelled_by_user | Reserved. A payer's cancellation currently arrives as declined with DeclineCode: "CANCELLED_BY_USER". | yes |
| abandoned | The payer left and did not come back. | yes |
* final for the authorization step. It moves on when you capture or cancel it.
pending is not a decline.
A payment also stays pending when the connection to the bank dropped and we are still finding out what happened. Never cancel or retry such a payment on your side. Wait for a final state or a webhook. We set a final state only when the bank's answer is certain.
What StateDetails contains
The fields depend on the state. A field not listed for a state never appears in it. Empty values are left out.
| State | Fields |
|---|---|
| success, preauthorized, voided, pending | Amount, Currency, ProcessingAmount, ProcessingCurrency, RemainingAmount, CardMasked, RRN, RebillId, DateTime, ReceiptLink, ThreeDSResult |
| preauthorized after a refused capture or full release | The fields above, plus DeclineCode and DeclineReason: why the bank refused. The refused operation itself is declined in Operations. |
| declined, cancelled_by_user | DeclineCode, DeclineReason, CardMasked, ThreeDSResult (declined only) |
| wait_for_3ds | ThreeDS, AcsUrl, PaReq, MD, RebillId |
| redirect | RedirectUrl, RedirectMethod, RedirectParams, QrCodeString, RebillId |
| waiting_action | The fields of success, plus Display: what to show the payer, or Collect: what to ask the payer, and PayerUrl: our page that does it |
ProcessingAmount/ProcessingCurrencydiffer fromAmountwhen the bank processed the payment in another currency. Your money is alwaysAmount.DateTimeis the creation time of the operation, RFC 3339 in UTC:2026-09-01T11:22:05Z.- Payments made through hosted checkout never expose 3DS, redirect,
DisplayorCollectdetails: the page handles them.
Showing a Display step
Some payment methods do not send the payer anywhere. The provider gives a QR code, an address and an exact amount to transfer, or a link that opens the payer's app, and the payment waits in waiting_action. Display tells you what to show:
| Field | Meaning |
|---|---|
Kind | qr, credentials or instructions |
Payload.Qr | Text to encode as a QR code. You draw the code. |
Payload.Link | HTTPS link that opens the payer's app. Make it the main button on phones. |
Payload.Address, Payload.Memo | Where to transfer, and the tag the transfer must carry. Without the tag the money is not matched. |
Payload.Amount, Payload.AmountCurrency | Exact amount to transfer and its currency. May differ from Amount: you invoice in your currency, the payer pays in another. |
Payload.Network | Network to transfer on. A transfer on another network does not arrive. |
Payload.Text | Instructions in words. |
ExpiresAt | Until when the step is valid, RFC 3339 in UTC. |
Show the values as text. Do not settle the payment by the timer: money sent in the last second still arrives, and the final state comes in a webhook.
Rather not draw the screen yourself? Send the payer to PayerUrl: our page shows the same QR code, details and app link, updates itself and shows the result. It needs no JavaScript and works in any browser. You get a WaitingAction webhook when the step starts, with Display and PayerUrl; States=waiting_action in the payments list finds payments that wait on this step.
Asking the payer for details: Collect
Some providers will not start a payment without details of the payer — a name, an email or a phone, a date of birth. Then the payment waits in waiting_action with Collect instead of Display, and no money has moved yet:
"Collect": { "Fields": ["FirstName", "LastName"], "AnyOf": [["Email", "Phone"]] }
Fields are all required; of each AnyOf group, at least one is. Ask the payer and send the answers, flat, in the same spelling as CustomerInfo:
POST /v1/payments/{id}/payer-data
{ "FirstName": "Remi", "LastName": "Terr", "Phone": "+44 7700 900123" }
Details you sent earlier count, so send only what is missing. Not enough is 400 PAYER_DATA_INCOMPLETE naming what is missing; a value in a wrong format is 400 INVALID_PAYER_DATA. Once accepted, the payment goes on to the provider and the outcome comes in a webhook. If the provider fails and the payment moves on to another one that needs more, you get another WaitingAction with only the new fields. Without the details in time (30 minutes by default) the payment is declined with DeclineCode: "PAYER_DATA_TIMEOUT".
The same PayerUrl asks the fields on our page if you would rather not draw the form. To skip the step altogether, send FirstName, LastName, Email and Phone in CustomerInfo when you create the payment.
Use reads as the backup path. The main path is the webhook, which comes to you without a polling loop. Read the payment while you guide a payer through 3DS, and when a webhook seems late.
10Webhooks#
When an operation changes state, we POST a JSON notification to the URL configured for your shop.
| Event | When |
|---|---|
Payment | Payment completed (a one-step payment). |
Block | Amount authorized (on hold). |
Capture | A hold captured, fully or partly. TransactionId is the capture operation, Amount is what was captured. |
Refund | Refund completed. |
Void | Hold released, fully or partly. |
Payout | Payout completed. |
Fail | Declined, rejected by fraud checks, timed out, cancelled by the payer, or expired with no payment attempt. Also a capture or release the bank refused: then TransactionId is that operation and the payment stays on hold. DeclineCode and DeclineReason say which. |
Abandoned | The payer left without finishing. |
3DS | The operation is waiting for a 3DS step (direct API: carries AcsUrl, PaReq, MD). |
3DSRedirect | The payer must go to the bank's page (direct API: carries RedirectUrl, RedirectMethod). |
WaitingAction | The payment waits for the payer on a Display step — a QR code, a transfer, an app — or for details the provider needs (direct API: carries Display or Collect, and PayerUrl). |
Subscription | A subscription changed. See subscription webhooks. |
{
"Event": "Payment",
"TransactionId": "3554",
"PaymentId": "3554",
"OrderId": "order-1043",
"ShopId": "1001",
"Amount": "49.00",
"Currency": "USD",
"DateTime": "2026-09-01T11:22:05Z",
"Description": "Pro plan, November",
"CardMasked": "411111******1111",
"ExpirationDate": "12/30",
"CardholderName": "JANE DOE",
"RRN": "123456789012",
"Email": "payer@example.com",
"ExtraData": { "plan": "pro" },
"IsTest": false
}PaymentIdis in every webhook: the payment the operation belongs to. For a capture, a release or a refund it is the original payment; for the payment itself and for a payout it equalsTransactionId.GET /v1/payments/{PaymentId}shows the payment with all its operations.FailaddsDeclineReason, a reason you can show the payer, andDeclineCodewhen the code is known: the same fields as in the payment'sStateDetails.- For
Capture,RefundandVoid,Amountis the amount of that operation: the captured, refunded or released part, not the original payment.RemainingAmountis what can still be refunded (or is still on hold). ExtraDatais the object you sent with the payment, values as strings. For a payment through a payment link,PaylinkCodenames the link.Email,Phone,Description, card andRRNfields appear only when known.DateTimeis the creation time of the operation, RFC 3339 in UTC, the same as inStateDetails.IsTestistruefor sandbox operations andfalsefor live ones.
Verifying the signature
Always verify. Without it, anyone who finds your webhook URL can mark orders as paid. Each webhook has these headers:
| Header | Value |
|---|---|
X-SHOP-ID | Your Shop ID. |
X-WEBHOOK-ID | The notification ID. The same on every delivery attempt of one notification. Use it to drop duplicates. |
X-WEBHOOK-TIMESTAMP | Unix seconds when this attempt was sent. |
X-WEBHOOK-SIGNATURE | One or more v1-webhook=<hex> values, separated by commas. |
The signature is built like the request signature, with the same secret, a different label, and the full URL instead of the path:
v1-webhook
POST
{URL} ← the full URL we posted to, exactly as configured, e.g. https://shop.example/hooks/payvan
{SHOP_ID}
{WEBHOOK_ID}
{TIMESTAMP}
{hex(SHA-256(BODY))} ← the raw body as receivedThe separate label means a webhook signature can never be passed off as a request signature, or the other way round. During a key rotation the header carries one signature per valid key:
v1-webhook=<signature with the new key>,v1-webhook=<signature with the old key>So always parse the header as a list, even outside rotations, when it simply has one entry. Accept the webhook if any entry matches. Compare in constant time, and reject timestamps more than 5 minutes off.
# Flask example. verify_webhook() is in payvan_sign.py.
from flask import Flask, request
from payvan_sign import verify_webhook
app = Flask(__name__)
WEBHOOK_URL = "https://shop.example/hooks/payvan" # exactly as configured with PayVAN
@app.post("/hooks/payvan")
def payvan_hook():
raw = request.get_data() # raw bytes, before any JSON parsing
if not verify_webhook([SECRET], WEBHOOK_URL, request.headers, raw):
return "", 401
enqueue(request.headers["X-WEBHOOK-ID"], raw) # process asynchronously
return "", 200// Express example. verifyWebhook() is in payvan-sign.mjs.
import express from "express";
import { verifyWebhook } from "./payvan-sign.mjs";
const app = express();
const WEBHOOK_URL = "https://shop.example/hooks/payvan"; // exactly as configured with PayVAN
app.post("/hooks/payvan", express.raw({ type: "*/*" }), (req, res) => {
const ok = verifyWebhook({ secrets: [process.env.PAYVAN_SECRET], url: WEBHOOK_URL,
headers: req.headers, rawBody: req.body });
if (!ok) return res.sendStatus(401);
queue.push({ id: req.get("X-WEBHOOK-ID"), body: req.body.toString() }); // process later
res.sendStatus(200);
});<?php
$secrets = [getenv('PAYVAN_SECRET')];
$url = 'https://shop.example/hooks/payvan'; // exactly as configured with PayVAN
$raw = file_get_contents('php://input');
$ts = (int) ($_SERVER['HTTP_X_WEBHOOK_TIMESTAMP'] ?? 0);
$message = implode("\n", ['v1-webhook', 'POST', $url,
$_SERVER['HTTP_X_SHOP_ID'] ?? '', $_SERVER['HTTP_X_WEBHOOK_ID'] ?? '', (string) $ts, hash('sha256', $raw)]);
$ok = false;
foreach (explode(',', $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '') as $part) {
[$label, $sig] = array_pad(explode('=', trim($part), 2), 2, '');
if ($label !== 'v1-webhook') continue;
foreach ($secrets as $secret) {
if (hash_equals(hash_hmac('sha256', $message, $secret), $sig)) $ok = true;
}
}
if (!$ok || abs(time() - $ts) > 300) { http_response_code(401); exit; }
queue_push($_SERVER['HTTP_X_WEBHOOK_ID'], $raw); // process asynchronously
http_response_code(200);// net/http example (Go 1.22+). VerifyWebhook() is in payvan_sign.go.
package main
import (
"io"
"net/http"
"os"
"time"
)
const webhookURL = "https://shop.example/hooks/payvan" // exactly as configured with PayVAN
func payvanHook(w http.ResponseWriter, r *http.Request) {
raw, err := io.ReadAll(r.Body) // raw bytes, before any JSON parsing
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if !VerifyWebhook([]string{os.Getenv("PAYVAN_SECRET")}, webhookURL, r.Header, raw, 5*time.Minute) {
w.WriteHeader(http.StatusUnauthorized)
return
}
enqueue(r.Header.Get("X-WEBHOOK-ID"), raw) // process asynchronously
w.WriteHeader(http.StatusOK)
}
func main() {
http.HandleFunc("POST /hooks/payvan", payvanHook)
http.ListenAndServe(":8080", nil)
}// JDK HttpServer example, no framework. verifyWebhook() is in PayvanSign.java.
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class PayvanHook {
static final String WEBHOOK_URL = "https://shop.example/hooks/payvan"; // exactly as configured with PayVAN
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/hooks/payvan", exchange -> {
byte[] raw = exchange.getRequestBody().readAllBytes(); // raw bytes, before any JSON parsing
Map<String, String> headers = exchange.getRequestHeaders().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().get(0)));
boolean ok = PayvanSign.verifyWebhook(List.of(System.getenv("PAYVAN_SECRET")),
WEBHOOK_URL, headers, raw, 300);
if (ok) {
enqueue(exchange.getRequestHeaders().getFirst("X-WEBHOOK-ID"), raw); // process asynchronously
}
exchange.sendResponseHeaders(ok ? 200 : 401, -1);
exchange.close();
});
server.start();
}
static void enqueue(String id, byte[] body) {}
}SECRET = 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF
URL = https://shop.example/hooks/payvan
SHOP_ID = 1001
WEBHOOK_ID= wh_7f3a9c
TIMESTAMP = 1789732860
BODY = {"Event":"Payment","TransactionId":"3554","OrderId":"A-1001","Amount":"1499.00","Currency":"USD"}
hex(SHA-256(BODY)) = e4059a1235bec02f30805b18a7f74c775ef86656b1ce3ef7fd7d0550c0c65d3d
X-WEBHOOK-SIGNATURE = v1-webhook=8d1f0f9a2207241e640bd28aef00de33aca990e7087b06df38a09917d995b4b6Delivery and retries
Any response other than 2xx, a timeout or a network error counts as a failure. We retry after 30 seconds, then double the delay each time up to 6 hours, for up to 12 attempts. The last attempt comes about 14½ hours after the first one. If your endpoint is down longer than that, catch up with GET /v1/payments, or send the missed notifications again from the dashboard.
To send a notification again, open the payment in the dashboard and press Send again under its last attempt in Notifications. Our support can do the same for you. This makes one more attempt, which shows up in the same list; if it fails too, press again. Notifications of one payment can be resent once a minute. A resent notification is the same notification: the same body and the same X-WEBHOOK-ID, with a fresh timestamp and signature. If your handler already processed it, deduplication on X-WEBHOOK-ID drops it, as it should.
Reply 200 as soon as the signature checks out, and do the work in your own queue. Each attempt waits at most 30 seconds for your answer. A slow handler turns into a retry, so your handler must be idempotent: the same notification can arrive more than once. Deduplicate on X-WEBHOOK-ID.
Webhooks can arrive out of order, for example Refund before a delayed Payment retry. If order matters, read the payment instead of relying on arrival order. We can give you the IP addresses webhooks come from, for an allowlist. Sandbox and live use different addresses.
11Subscriptions#
A subscription charges a saved card on a schedule: an amount, a period and an optional number of charges. We run the charges and retries. You get a webhook for every step, and you can change, pause or cancel the subscription at any time.
Add a Subscription block and RebillFlag: true to a direct payment or to a checkout session: the body is the same. The first payment is the first period. The next charge is one interval after it, or at StartAt. If the first payment fails, the subscription is cancelled automatically.
"RebillFlag": true,
"Subscription": {
"OrderId": "sub-1043",
"AccountId": "user-77",
"Amount": "9.99",
"Currency": "USD",
"Description": "Basic plan",
"Interval": { "Unit": "month", "Count": 1 },
"MaxCycles": 12,
"OfferUrl": "https://shop.example/terms"
}{
"TransactionId": "3554",
"OrderId": "order-1043",
"Amount": "9.99",
"Currency": "USD",
"SubscriptionId": "8812"
}OfferUrl links to the terms the payer accepts, and hosted checkout requires it. Card schemes need proof of consent for recurring charges, and this is it.
{
"RebillId": "3554",
"OrderId": "sub-1044",
"AccountId": "user-77",
"Amount": "9.99",
"Currency": "USD",
"Description": "Basic plan",
"Interval": { "Unit": "month", "Count": 1 },
"StartAt": "2026-10-01T09:00:00Z",
"MaxCycles": 12,
"TimeZone": "America/New_York",
"WebhookUrl": "https://shop.example/hooks/subs",
"Payer": { "Email": "payer@example.com" }
}{
"SubscriptionId": "8812",
"OrderId": "sub-1044",
"RebillId": "3554",
"Status": "active",
"Amount": "9.99",
"Currency": "USD",
"Interval": { "Unit": "month", "Count": 1 },
"TimeZone": "America/New_York",
"PaidCycles": 0,
"MaxCycles": 12,
"NextChargeAt": "2026-10-01T09:00:00Z",
"CreatedAt": "2026-09-15T12:00:00Z"
}StartAt is required here: it is the date of the first charge on the saved card. Unit is day, week, month or year, and Count is 1–366. All timestamps are RFC 3339 with an offset. Calendar steps are counted in TimeZone (default UTC) from the first charge date: a subscription started on 31 January charges on 28 February, then 31 March.
Managing a subscription
| Request | Body or query | Effect |
|---|---|---|
GET /v1/subscriptions/{id} | — | The subscription, or 404 SUBSCRIPTION_NOT_FOUND. |
GET /v1/subscriptions | one of ?OrderId=, ?AccountId=, ?RebillId= | Returns {"Data": [...], "HasMore": false}, up to 100 subscriptions. HasMore means more matched: narrow the filter. |
PATCH /v1/subscriptions/{id} | any of Amount, Description, Interval, StartAt, MaxCycles, EndsAt | A new amount applies from the next period. A new Interval or StartAt rebuilds the schedule from the next period. |
POST /v1/subscriptions/{id}/pause | — | No charges until resumed. |
POST /v1/subscriptions/{id}/resume | optional ResumeAt | Without ResumeAt, charging continues on the next date of the original schedule. Paused periods are not charged. |
POST /v1/subscriptions/{id}/cancel | optional Reason | Always possible, even during a charge. Reason is merchant (default) or payer if the customer asked. The payer gets a different email in each case. |
Subscription statuses
| Status | Meaning |
|---|---|
pending | Waiting for the first payment. |
active | Charging on schedule. The next date is NextChargeAt. |
past_due | The current period is unpaid. CurrentCycle shows attempts, the last decline reason, and NextAttemptAt or CardUpdateDeadline. |
paused | Paused. |
completed | All MaxCycles paid, or EndsAt reached. |
cancelled | Ended. The reason is in CancelReason: merchant, payer, operator, mandate_revoked, first_payment_failed, unpaid or card_unusable. |
When a charge fails
Each period gets up to three attempts, and the third failure cancels the subscription (unpaid). The decline reason decides the retry timing: for insufficient funds we retry after 1 day and then 3 days, for technical errors after 1 hour and then 6 hours. Cards reported stolen, invalid or expired are not retried. Instead the subscription waits for the payer to add a new card until the third attempt's date, then cancels (card_unusable). If the outcome of a charge is unknown, we don't retry until the bank answers.
Each charge has its own order number, <subscription OrderId>-<period number>, so you can match it in your books.
Subscription webhooks
These go to the subscription's WebhookUrl, or to your shop's webhook URL if it is not set. They use the same signature and retries. Event is Subscription, the kind is in Type, and the body carries the subscription object at that moment plus Details.
| Type | When |
|---|---|
created, activated | Subscription created, or its first payment succeeded. |
cycle_paid | A period was paid (Details.CycleNo, TransactionId). |
past_due, awaiting_card | A period is unpaid: waiting for a retry or a new card (DeclineCategory, NextAttemptAt). |
recovered | An overdue period was paid by a retry. |
attempt_failed | An attempt never reached the bank, e.g. the card had expired. Bank declines come as a Fail webhook for the charge. |
cycle_skipped | A period was skipped without a charge. |
changed, paused, resumed | The subscription was changed. |
cancelled, completed | The subscription ended. |
The money itself is still reported by operation webhooks: Payment and Fail for each charge. Subscription webhooks describe the subscription's state. If emails are enabled for your shop, we also write to the payer: on sign-up, a few days before each charge, on payment, on failure and on cancellation.
Subscription errors
| Code | HTTP | Reason |
|---|---|---|
SUBSCRIPTION_NOT_FOUND | 404 | No such subscription for your shop. |
SUBSCRIPTION_EXISTS | 409 | A subscription with this OrderId already exists. |
SUBSCRIPTION_BAD_STATUS | 409 | Not allowed in the current status, e.g. changing a completed one. |
SUBSCRIPTION_ATTEMPT_IN_FLIGHT | 409 | Resume while a charge started before the pause is still running. Retry later. |
SAVED_CARD_NOT_FOUNDSAVED_CARD_INACTIVE | 404 409 | No saved card, or it was removed. |
SUBSCRIPTION_REQUIRES_REBILL_FLAG | 400 | Subscription block without RebillFlag: true. |
INVALID_INTERVALINVALID_START_ATINVALID_ENDS_ATINVALID_MAX_CYCLESINVALID_TIME_ZONE | 400 | The terms can't be parsed or contradict each other. |
12Customers & KYC#
If the payer has an account with you, send its ID in CustomerInfo.CustomerId. We use it to build the customer's history: first deposit, number of deposits and payouts, and the cards they used. You can also declare that you have verified the customer and their card. You run the checks and we don't take documents: we store your declaration and use it for routing. For example, a verified customer with a good history can be routed to a channel without 3DS. Routing rules with such conditions are configured in the dashboard.
"CustomerInfo": {
"CustomerId": "u-81723",
"FirstName": "Jane",
"LastName": "Doe",
"BirthDate": "1990-04-12",
"Citizenship": "US",
"KycVerified": true,
"CardKycVerified": true,
"RoutingGroup": "vip",
"Email": "payer@example.com",
"IP": "203.0.113.10"
}| Field | Meaning |
|---|---|
CustomerId | Your ID for the payer: 1–64 printable ASCII characters, no leading or trailing spaces. It is shared across all your shops, so a customer verified on one is verified on all. |
KycVerified | You have verified this customer. It stays in force until you revoke it, so later payments can omit it. Send false to revoke. |
CardKycVerified | You have verified that this payment's card belongs to the customer. It applies only to payments with a card. |
RoutingGroup | Your segment label for routing rules, up to 64 characters with no spaces. An empty string removes it. |
FirstNameLastNameBirthDateCitizenship | Profile. The date is YYYY-MM-DD and citizenship is ISO 3166-1 alpha-2. Sending an empty value does not erase the stored one. |
Document | {"Type": "…", "Number": "…"}. Needed by methods that require an ID document (for example PIX or local bank transfers). The type code comes from the provider's list. |
BankAccount | Number, Name, Type (SAVINGS/CHECKING), Bank, BankCode, Branch, BranchCode. For payouts and transfers without a card. |
History | The customer's history with you before PayVAN: FirstDepositAt, DepositsCount, DepositsAmount, PayoutsCount, PayoutsAmount, Currency. We pass it to the bank. It does not feed routing rules: trust is earned only by operations that go through us. |
KycVerified, CardKycVerified or RoutingGroup without CustomerId are rejected, because there is nothing to attach them to. Errors are 400 with ErrorCode: CUSTOMER_ID_REQUIRED, INVALID_CUSTOMER_ID, INVALID_BIRTH_DATE, INVALID_CITIZENSHIP, INVALID_ROUTING_GROUP, INVALID_DOCUMENT, INVALID_BANK_ACCOUNT or INVALID_HISTORY. The same applies to payouts.
Customers outside a payment
You can read a customer's record, or declare KYC later, for example when verification finishes after the payment. Customers are shared across your shops, so you can sign with any of your shops' keys.
{
"CustomerId": "u-81723",
"FirstName": "Jane",
"RoutingGroup": "vip",
"KycVerified": true,
"KycChangedAt": "2026-09-28T06:12:40Z",
"FirstSeenAt": "…", "LastSeenAt": "…",
"History": {
"FirstDepositAt": "2026-09-02T10:15:00Z",
"DepositsCount": 5, "PayoutsCount": 1,
"Amounts": [{ "Kind": "deposit",
"Currency": "USD", "Amount": "610.00" }],
"Shop": { "DepositsCount": 2,
"PayoutsCount": 0, "FirstDepositAt": "…" }
},
"Cards": [{ "CardMasked": "400000******0002",
"ExpMonth": 12, "ExpYear": 30,
"CardKycVerified": true,
"DepositsCount": 4, "FirstDepositAt": "…" }]
}KycVerified and CardKycVerified are null if you never declared them. History counts successful operations through us, across all your shops and for the requesting shop alone (Shop). An unknown customer returns 404 CUSTOMER_NOT_FOUND. URL-encode the CustomerId in the path: team/u-1 becomes team%2Fu-1.
| Request | Query or body | Effect |
|---|---|---|
GET /v1/customers | KycVerified, RoutingGroup, FirstDepositFrom, FirstDepositTo, OnlyThisShop, Cursor, Limit in the query string | Returns {"Data": [...], "HasMore": true, "NextCursor": "…"}. Pass NextCursor as Cursor to get the next page. Limit is up to 200 (default 50). Dates are YYYY-MM-DD UTC, inclusive. KycVerified=false finds customers you declared unverified, not everyone else. An empty RoutingGroup= finds customers with no group. |
PATCH /v1/customers/{CustomerId} | KycVerified, RoutingGroup, Cards[{CardMasked, CardKycVerified}] | Declare without a payment. Returns the updated customer. A card is identified by its mask: first six and last four digits with any number of asterisks between them (400000***0002). The request is applied in full or not at all. |
PATCH /v1/customers/{CustomerId} errors: 404 CUSTOMER_NOT_FOUND, 404 CARD_NOT_FOUND, 409 CARD_AMBIGUOUS (two cards share the mask, so declare card KYC in that card's next payment instead), and 400 for NOTHING_TO_CHANGE, INVALID_CARD_MASKED, INVALID_CARD_KYC_VERIFIED, INVALID_ROUTING_GROUP and TOO_MANY_CARDS (more than 20).
13Payouts & balance#
{
"Amount": "120.00",
"Currency": "USD",
"OrderId": "payout-77",
"Description": "Seller payout, October",
"PayoutMethod": "Card",
"CustomerInfo": {
"Email": "seller@example.com",
"Country": "US",
"IP": "203.0.113.20"
},
"PayoutDetails": {
"CardholderName": "JOHN ROE",
"CardNumber": "4111111111111111",
"ExpMonth": "12",
"ExpYear": "2030",
"BankName": "EXAMPLE BANK"
}
}{
"TransactionId": "4102",
"OrderId": "payout-77",
"Amount": "120.00",
"Currency": "USD"
}PayoutDetails is the recipient's card, not a payer's. PayoutMethod defaults to Card, which is currently the only method. The cardholder name is optional for payouts. If you send it, it must be well-formed. The outcome arrives as a Payout or Fail webhook; GET /v1/payouts/{id} reads it on demand.
A payout uses your payout balance. Validation errors are the same as for payments (INVALID_AMOUNT, INVALID_CARD_NUMBER and so on), plus INVALID_PAYOUT_METHOD.
A payout above the available balance is rejected right away, before anything is created: 400 INSUFFICIENT_PAYOUT_BALANCE, with your Balance in Details. Check GET /v1/balance first to avoid it.
{
"error": "Payout amount is bigger than the available payout balance",
"ErrorCode": "INSUFFICIENT_PAYOUT_BALANCE",
"Details": { "Amount": "120.00", "Balance": "75.40", "Currency": "USD" }
}201 still does not mean the payout went out.
A payout that fits the balance is accepted, and the bank decides after that. It can also be declined right after acceptance when our fee or another payout sent at the same moment takes the rest of the balance: the state becomes declined with DeclineCode: LIMITS_REACHED, and a Fail webhook arrives. Keep the payout pending after 201 and close it only on the Payout or Fail webhook, or on GET /v1/payouts/{id}.
{ "Balance": "12540.00", "Currency": "USD" }A signed GET with an empty body. This endpoint can be restricted to your server IPs, which we agree when your account is set up. If the balance can't be read, you get 409 BALANCE_UNAVAILABLE.
14Errors#
Every error response has the same shape: error, a message for people, ErrorCode, a stable UPPER_SNAKE code for your program, and Details when there is more to say. Check the HTTP status first, then branch on ErrorCode.
{ "error": "invalid signature", "ErrorCode": "INVALID_SIGNATURE" }
{ "error": "request timestamp outside allowed window", "ErrorCode": "STALE_TIMESTAMP",
"server_time": 1789733105 }
{ "error": "Amount is bigger than the charged amount", "ErrorCode": "AMOUNT_MISMATCH",
"Details": { "Amount": "60.00", "AvailableAmount": "19.00" } }| HTTP | Code | What happened / what to do |
|---|---|---|
| 400 | INVALID_* | A field failed validation. Fix the request. Don't retry it unchanged. |
| 400 | INVALID_JSON | The body is not valid JSON. |
| 400 | INVALID_REQUEST | A field has the wrong JSON type, e.g. "RebillFlag": "true". The message names the field: RebillFlag must be true or false. Wrong-typed amounts, currencies and order IDs get their own code, e.g. "Amount": 49 → INVALID_AMOUNT. |
| 400 | AMOUNT_MISMATCH | More than the remaining balance. The remainder is in Details.AvailableAmount. |
| 400 | INSUFFICIENT_PAYOUT_BALANCE | The payout is bigger than your payout balance. No payout is created; the balance is in Details.Balance. |
| 401 | MISSING_HEADERSUNKNOWN_SHOPINVALID_TIMESTAMPINVALID_SIGNATURE | Authentication failed. Check the headers, the Shop ID, and how you build the string to sign. |
| 401 | STALE_TIMESTAMP | Your clock is off by more than 5 minutes. Our time is in server_time. |
| 403 | IP_NOT_ALLOWED | The endpoint is limited to your server IPs (e.g. /v1/balance). |
| 400 | CARD_EXPIRED | The card has expired. |
| 400 | SAVED_CARD_LIMIT_REACHED | Saved-card limits are enabled for your shop, and the card has no charges or amount left (rebill). |
| 400 | SAVED_CARD_PERMISSION_EXPIRED | Saved-card limits are enabled for your shop, and the permission to charge the card has run out (rebill). Not the card's own expiry. |
| 404 | TRANSACTION_NOT_FOUND | No such operation for your shop. |
| 404 | PAYMENT_NOT_FOUND | No such payment for your shop. Also for an action by the ID of a capture, a release, a refund or a payout: it is not a payment ID, use its PaymentId. |
| 404 | PAYOUT_NOT_FOUND | No such payout for your shop (GET /v1/payouts/{id} with the ID of something else). |
| 404 | NOT_FOUND | No such endpoint. |
| 404 | SAVED_CARD_NOT_FOUND | No saved card on that RebillId. |
| 409 | BAD_STATUS_FOR_CHARGEBAD_STATUS_FOR_CANCELBAD_STATUS_FOR_REFUNDBAD_STATUS_FOR_CONFIRM | The payment exists, but its state doesn't allow this action (e.g. refunding a hold, capturing a captured payment). Details.Status is its status. Read the payment before retrying. |
| 409 | OPERATION_IN_PROGRESS | Another capture or release of this payment has no outcome yet. Wait for its webhook, or read the payment, then retry. |
| 409 | REQUEST_IN_PROGRESS | A request with the same X-REQUEST-ID is still running. Retry shortly with the same ID. |
| 422 | IDEMPOTENCY_KEY_REUSED | This X-REQUEST-ID was already used for a different request. Use a new ID for a new operation. |
| 409 | SAVED_CARD_INACTIVE | The saved card was removed or is not active. |
| 409 | BALANCE_UNAVAILABLE | The payout balance could not be read (/v1/balance). |
| 413 | BODY_TOO_LARGE | Body larger than 1 MB. |
| 429 | RATE_LIMITED | Rate limit exceeded. Back off and retry with the same ID. |
| 503 | OPERATION_NOT_STARTED | A capture or release was accepted but could not be started; nothing went to the bank. Retry with the same X-REQUEST-ID: you get the same operation, now started. |
| 5xx | INTERNAL_ERROR | Temporary problem on our side. Retry with the same X-REQUEST-ID. |
If no response arrived, the payment may still have gone through. Retry with the same X-REQUEST-ID: within 24 hours you get the stored response, and at any time later the operation is still not created twice. Never create a second payment just because the first one timed out.
15Sandbox & go-live#
The sandbox talks to a bank emulator. You choose the scenario with the test card's CVC and expiry month. Any cardholder name works. Use a future expiry year.
Basic card 4111 1111 1111 1111
CVC picks the flow
600–999: no 3-D Secure500–599: redirect to the bank's page000–499: 3-D Secure challenge (AcsUrl+PaReq)
Month picks the outcome
01–06: success07–12: declined
For holds (POST /v1/payments with "PaymentType": "Block"), the month also decides what happens next:
| ExpMonth | Hold | Capture | Cancel |
|---|---|---|---|
01 | ok | fails | ok |
02 | ok | ok | fails |
03 | ok | fails | fails |
04–06 | ok | ok | ok |
07–12 | declined | — | — |
3-D Secure 2 card 4017 3400 0000 0003
| CVC | Flow |
|---|---|
111 | method step, then a challenge. |
222 | method step, then frictionless (no challenge). |
333 | challenge only. |
With expiry 06/30 the payment succeeds. Any other expiry gives a decline after authentication. Use this card to test your 3DS handling end to end.
Refunds have no card, so they always succeed in sandbox. To test refund declines, ask for more than the remaining balance and you get AMOUNT_MISMATCH.
Go-live checklist
- The signature matches on a body with non-ASCII text and nested objects.
- A retry with the same
X-REQUEST-IDdoes not create a second payment. - After a timeout, you retry with the same
X-REQUEST-ID, or look the order up withGET /v1/payments?OrderId=…, before creating anything new. - Your server clocks are synced (NTP). The window is 5 minutes.
- The webhook signature is verified, the header is parsed as a list, and
200goes back right away. - The same webhook delivered twice does not fulfil the order twice (deduplicate on
X-WEBHOOK-ID). - Orders are fulfilled on the webhook or by reading the payment, never on the payer's return.
pendingis treated as “in progress”, not as a failure.- Partial refunds reduce your stored balance by the
Amountin our response. - Live credentials are stored in a secrets manager, not in code or in the browser.