Skip to main content
Unlisted page
This page is unlisted. Search engines will not index it, and only users having a direct link can access it.

Server-to-Server Payments

This page is for merchants certified PCI-DSS who collect card data on their own systems and charge it through the Avenia API with a direct call, with no Avenia payment page in between. If you are not certified, or would rather keep card data out of your systems, use the hosted checkout.

Sandbox only

Server-to-server payments are available in the sandbox only for now. We ask for your PCI-DSS Attestation of Compliance (AOC) before production, not for the sandbox.

How it works​

 Your server                Encryption relay           Avenia API              Card networks
----------- ---------------- ---------- -------------
POST /v2/account/
acquiring/payments
card in clear ---> encrypts the card ---> validates, screens
fields for risk, authorizes --> issuer
<-- result
<------------------------------- { id, status, redirectUrl? }

if redirectUrl: send the cardholder's browser there for 3D Secure

webhook <------------------------------- ACQUIRING-PAYMENT-CAPTURED
  • One call goes through the relay: creating the payment. The relay is operated for Avenia by Evervault, a PCI-DSS Level 1 provider. It encrypts the card number and the security code before the request reaches the Avenia API, so Avenia's systems never see a card number in clear, and neither do our logs. Every other call (refunds, webhooks, disputes, reads) goes to the Avenia API directly.
  • The API refuses card data that did not come through the relay. A readable card number sent straight to the API is rejected with 400, and nothing is stored.
  • The answer is synchronous: approved, refused, or "needs 3D Secure" with a URL for the cardholder.
  • The webhook is still the source of truth for the final state, especially after 3D Secure.

Requirements​

  • A valid PCI-DSS AOC, SAQ D or a Report on Compliance, before production.
  • A browser in your flow for 3D Secure. Creating the payment is a pure API call, but when the issuer asks for a challenge the cardholder must complete it in a browser, redirected to the URL we return.
  • The cardholder's device data (IP, user agent, screen, language, time zone, colour depth). It is mandatory: see the device block.
  • A JSON canonicalization library (RFC 8785) on your server, to sign the payment request.
  • The relay URL, which Avenia gives you when it enables the route, and the domains of your success and cancel pages, registered in your configuration.

Environment​

Sandbox
API base URL (every call except creating a payment)https://api.sandbox.avenia.io:10952
Relay URL (creating a payment)https://<relay-host>, given by Avenia
Webhook signing keyGET https://api.sandbox.avenia.io:10952/v2/public-key

The relay keeps the same paths: the payment is POST https://<relay-host>/v2/account/acquiring/payments.

Two API keys, because of the relay​

Requests are signed with an API key: the signing string, headers and key types are the ones of the authentication page. A payment sent through the relay reaches Avenia from the relay's IP addresses, not yours, so an API key whose allowlist holds only your own ranges cannot create payments. Use two keys:

KeyUsed forAllowlist
Payments keyPOST /v2/account/acquiring/payments, through the relayThe relay's addresses (below)
Your usual keyEvery other call (refunds, webhooks, disputes, reads)Your own outbound ranges

Add these to the payments key's allowlist, one /32 per address:

34.199.158.122/32
52.48.156.228/32
54.161.131.154/32
54.216.126.127/32
168.100.164.1/32
168.100.164.2/32
168.100.164.3/32
168.100.164.4/32
168.100.164.5/32
168.100.164.6/32
168.100.164.7/32
168.100.164.8/32
168.100.164.9/32
168.100.165.1/32
168.100.165.2/32
168.100.165.3/32
168.100.165.4/32
168.100.165.5/32
168.100.165.6/32
168.100.165.7/32
168.100.165.8/32
168.100.165.9/32

This list is the relay provider's, not Avenia's, and it can change. Check it against Evervault's FAQ (docs.evervault.com/more/faq) before you create the key and whenever payments start failing with 401.

Keep the payments key for payments only: anyone holding it and its private key could call from the relay's addresses. If you already call the Avenia API with a key, keep it as your usual key and create only the payments key (POST /v2/auth/api-keys, see API Keys Management).

Sending card data​

The card number and the security code go inside card.encrypted, in clear, as strings. The relay encrypts exactly card.encrypted.number and card.encrypted.securityCode, and nothing else. The expiry and the holder name stay readable, beside encrypted:

JSON
"card": {
"encrypted": {
"number": "4507990000000002",
"securityCode": "123"
},
"expirationMonth": 12,
"expirationYear": 2030,
"holderName": "MARIA SILVA"
}
FieldRules
card.encrypted.numberDigits only, no spaces.
card.encrypted.securityCode3 or 4 digits.
card.expirationMonthInteger 1 to 12 (a number, not a string).
card.expirationYearFour-digit integer, for example 2030.
card.holderNameThe name printed on the card.
  • Nothing else under card.encrypted. It is the relay's selector ($.card.encrypted.*): a field you add there gets encrypted, and the acquirer cannot read an encrypted month or name.
  • Never put card data anywhere else (the reference, a header).
  • A readable card number is refused. A body that contains anything that looks like a card number (13 to 19 digits, Luhn-valid, spaces or hyphens allowed), anywhere in it, is refused before it reaches any Avenia service with 400 {"error": "card data must be encrypted before it reaches this API"}. It means the request bypassed the relay, or the card sits outside card.encrypted. For the same reason, keep long digit strings that could pass for a card number out of externalId.
  • Your PCI obligations do not change. The relay protects Avenia's side. On yours, never store the security code, never log card numbers (mask them as 450799******0002), and send them only over TLS to the relay.

Signing the payment request​

On POST /v2/account/acquiring/payments the relay replaces the card fields with encrypted values and may re-serialize the JSON on the way, so the bytes you sent are not the bytes Avenia receives and the raw body cannot be signed. On this route only, the body part of the signed string is:

the request body with the card.encrypted object removed, in JSON canonical form (RFC 8785, "JCS"): keys sorted, no whitespace, numbers and strings in canonical form.

A payment that pays a saved card has no card: sign the whole body. A whole number beyond 2^53 cannot be signed exactly, and such a body is refused. The rest of the string does not change: timestamp + METHOD + pathAndQuery + canonicalBodyWithoutCardEncrypted. Everything else in the body stays signed (quote token, reference, payer, URLs, holder name and device); the encrypted card fields are vouched for by the relay.

You still send the full body, with card.encrypted in clear, to the relay URL. Never send it to the API host. On every other route, sign the exact bytes you send, as the authentication page describes.

Send each field once

A body that repeats a key ignoring case (amount and Amount) is refused. On this route the refusal happens during authentication, so it comes back as 401 {"error":"UnauthorizedError"}.

Python
import base64, copy, json, os, time

import requests
import rfc8785 # pip install rfc8785
from cryptography.hazmat.primitives import serialization

RELAY_URL = "https://<relay-host>"
API_KEY = os.environ["AVENIA_PAYMENTS_API_KEY"]
with open("avenia_payments_private.pem", "rb") as f:
private_key = serialization.load_pem_private_key(f.read(), password=None)


def create_payment(payment, query=""): # query: "" or "?subAccountId=..."
path = "/v2/account/acquiring/payments" + query

# 1. Copy the body and remove card.encrypted: the relay vouches for it.
signed_part = copy.deepcopy(payment)
signed_part.get("card", {}).pop("encrypted", None) # a savedCard payment has no card

# 2. Canonical form (RFC 8785): rfc8785.dumps returns bytes.
timestamp = str(int(time.time() * 1000))
message = (timestamp + "POST" + path).encode() + rfc8785.dumps(signed_part)

# Ed25519 key. For RSA: private_key.sign(message, padding.PKCS1v15(), hashes.SHA256())
signature = base64.b64encode(private_key.sign(message)).decode()

# 3. Send the FULL body, card included, to the relay.
body = json.dumps(payment, separators=(",", ":"))
return requests.post(
RELAY_URL + path,
data=body.encode(),
headers={
"Content-Type": "application/json",
"X-API-Key": API_KEY,
"X-API-Timestamp": timestamp,
"X-API-Signature": signature,
},
)

Create a payment​

Endpoint​

POSThttps://<relay-host>/v2/account/acquiring/payments

Signed as above, with the payments key. The payment is made by your main account; add ?subAccountId={sub-account-id} to make it for a sub-account.

Parameters​

Body: required

FieldTypeDescription
quoteTokenstringThe quoteToken of a card sale quote of the account that sells, as on a checkout session: the sale's amount is the quote's inputAmount, it is paid in the quote's output currency, and one token opens one payment: it is the idempotency key of this call, see retries. There is no amount field. Over your account's monthly volume limit, the call is refused with 400 InvalidFieldError: amount is invalid and the reason in extraInfo. A sandbox account's per-payment limit is R$ 5,000.00 ("5000.00").
currencystringBRL. Any other currency is refused with 400 only BRL is accepted as the sale currency.
countrystringBR.
languagestringA BCP 47 tag, for example pt-BR, en-US or es-ES. Drives the 3D Secure challenge screen.
payerEmailstringA bare address (a@b.com, not Name <a@b.com>). Card networks require it.
payerNamestringThe customer's name.
payerTaxIdstringThe customer's CPF or CNPJ, digits only.
successUrlstringhttps:// only, on your registered domains (otherwise 400 naming successUrl). Where the cardholder lands after a 3D Secure challenge, whatever its outcome.
cancelUrlstringhttps:// only, on your registered domains (otherwise 400 naming cancelUrl). Echoed back in the answer; no redirect of ours uses it on this route.
deviceobjectThe cardholder's device: see the device block.
cardobjectRequired, unless you send savedCard. Send exactly one of card and savedCard.

Body: optional

FieldTypeDescription
externalIdstringYour own order reference, up to 68 characters. Not unique, and not part of the request compared on a repeat: it is only stored and returned on reads and webhooks, so you can match the payment to your order.
installmentsintegerHow many installments the cardholder chose, 1 up to maxInstallments in GET /config. Absent or 1 is a single payment. See installments.
saveCardobject{"customerReference": "...", "cardholderConsented": true}: keeps the card for future charges. See Saved Cards.
savedCardobject{"savedCardId": "...", "customerReference": "..."}: pays a card the customer saved earlier, instead of card. See Saved Cards.
beneficiaryWalletIdstringWhere this sale is paid, as a ticket's beneficiaryWalletId for a blockchain output: the id of one of your beneficiary wallets, on the chain of the output of the sale's quote. Required when that output is on a blockchain. When it is INTERNAL, leave it out: the sale is paid to your account's balance. See settling a sale to a wallet.

The whole body must be under 4 KB. Send only the fields in these tables. A field the request does not have, at any level (card, savedCard, device, saveCard), is refused with 400 InvalidFieldError: <field> is invalid and "extraInfo": "not a field of this request", instead of being ignored.

The device block​

It describes the cardholder's device as your checkout observed it. Issuers use it for risk scoring and 3D Secure; without real values they challenge more and approve less. All seven fields are required, and a partial block is refused with the missing field named (400 InvalidFieldError: device.<field> is invalid).

FieldRulesIn the browser
ipAddressThe cardholder's public IP (IPv4 or IPv6). Not your server's IP.from the request to your server
userAgentNon-empty.navigator.userAgent
screenWidth, screenHeightIntegers greater than 0.screen.width, screen.height
languageA BCP 47 tag.navigator.language
timeZoneOffsetMinutesBetween -840 and 720, with the sign of getTimezoneOffset(): positive west of UTC (Brazil is 180).new Date().getTimezoneOffset()
colorDepthOne of 1, 4, 8, 15, 16, 24, 30, 32, 48.screen.colorDepth

For a mobile app, take the equivalent values from the device.

Request body​

JSON
{
"externalId": "order-10045",
"quoteToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.XXXX.XXXX",
"currency": "BRL",
"country": "BR",
"language": "pt-BR",
"payerEmail": "customer@example.com",
"payerName": "Maria Silva",
"payerTaxId": "12345678901",
"successUrl": "https://shop.example.com/orders/10045/thanks",
"cancelUrl": "https://shop.example.com/orders/10045/payment-failed",
"beneficiaryWalletId": "76971925-a1ca-423f-badf-0b3f2b03c51c",
"card": {
"encrypted": { "number": "4507990000000002", "securityCode": "123" },
"expirationMonth": 12,
"expirationYear": 2030,
"holderName": "MARIA SILVA"
},
"device": {
"ipAddress": "203.0.113.10",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15",
"screenWidth": 1512,
"screenHeight": 982,
"language": "pt-BR",
"timeZoneOffsetMinutes": 180,
"colorDepth": 30
}
}

For this request, the body part of the signed string is the same body without card.encrypted, in canonical form (shortened here for reading):

{"card":{"expirationMonth":12,"expirationYear":2030,"holderName":"MARIA SILVA"},"country":"BR","currency":"BRL","externalId":"order-10045","language":"pt-BR","payerEmail":"customer@example.com","quoteToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.XXXX.XXXX"}

Response​

201 Created:

JSON
{
"id": "e4b8d1a2-6c3f-4a9e-b7d5-1f2e3a4b5c6d",
"status": "CAPTURED",
"subStatus": "",
"failureCode": "",
"successUrl": "https://shop.example.com/orders/10045/thanks",
"cancelUrl": "https://shop.example.com/orders/10045/payment-failed",
"savedCardId": "",
"quote": {
"outputCurrency": "USDC",
"outputPaymentMethod": "POLYGON",
"outputAmount": "26.504629",
"rate": "5.4",
"pairName": "USDCBRL",
"inputFee": "4.875",
"conversionFee": "1.5",
"markupFee": "0",
"outFee": "0.4",
"gasFee": "0.1",
"expiresAt": "2026-10-08T15:05:00Z"
},
"receivables": [
{ "installmentNumber": 1, "expectedDate": "2026-11-09", "amount": "137.62", "expectedAmount": "25.133967" }
],
"beneficiaryWalletId": "76971925-a1ca-423f-badf-0b3f2b03c51c",
"walletAddress": "0x4c7e2a91d3b05f68e1a2c4d6b8f0a3e5c7d9b1f2",
"walletChain": "POLYGON"
}

Store id: it is the payment id for refunds and support. The answer has no redirectUrl unless the payment needs 3D Secure.

FieldMeaning
idThe payment id.
status, subStatusThe state of the payment: see the table below and Errors and Decline Codes.
failureCodeWhy a payment ended BLOCKED, DECLINED or ERROR; "" on any other status.
redirectUrlPresent when status is PENDING_3DS.
successUrl, cancelUrlEchoed back from the request.
savedCardIdFilled only when the payment saved the card.
quoteThe quote the sale was opened from, which is its whole price: the MDR (inputFee), the rate, the conversion fees and the main account's markup (markupFee), in the currency you are paid in (outputCurrency). See the price of a sale.
receivablesWhat each installment is expected to deliver: installmentNumber, expectedDate, amount in BRL and expectedAmount in the quote's outputCurrency.
beneficiaryWalletId, walletAddress, walletChainThe wallet this payment is paid to, with the address and chain it had when the payment was created; all "" when it is paid to your account's balance. A repeat of the request returns the same ones.

quote can be absent and receivables empty when they could not be read at that moment: GET /payments/{payment-id} returns them.

statusMeaningWhat to do
CAPTUREDPaid.Confirm the order (the webhook follows).
AUTHORIZEDApproved, capture still pending.Wait for ACQUIRING-PAYMENT-CAPTURED.
PENDING_3DSThe issuer wants a challenge. redirectUrl is present.See 3D Secure.
PENDING_PROVIDER, PENDING_REVIEWStill being decided.Wait for the webhook.
DECLINEDRefused by the issuer or by fraud screening. subStatus and failureCode say how.Offer another card, with a new quote.

Refused by Avenia​

JSON
{ "error": "the payment was refused" }

402. The payment did not go through and no money moved: Avenia refused it, for example by its risk rules before it reached the issuer. The answer gives no reason, on purpose. Offer the customer another card, with a new quote. When the risk rules refused it, ACQUIRING-PAYMENT-BLOCKED follows. A payment that could not be completed, on our side or at the acquirer, is not a 402: it answers 500 InternalError: please contact us, which you can repeat with the same quoteToken (see retries). Prepaid cards are refused with 400 prepaid cards are not accepted.

Retries and idempotency​

The quoteToken is the idempotency key: one token opens one payment.

You sendYou get
A new quoteToken201 and a new payment
The same one, with the same request, after the first call succeeded200 and the same payment, so you can recover its id after a timeout
The same one, while the first call is still running409 an authorization for this quoteToken is already running: wait a few seconds and repeat
The same one, after a 3D Secure challenge started200 with the same redirectUrl
The same one, after it was paid409 this quoteToken has already been paid, or 200 with the payment that paid it
The same one, with the same request, after its quote expired200 and the same payment, as for any repeat: an expired quoteToken does not stop a repeat from being recognized. An expired token not used before gets 400 InvalidFieldError: quoteToken is invalid.
A payment that starts after its quote expired409 QUOTE_EXPIRED: the quote of this sale has expired; quote the sale again. Nothing was charged: quote again and send the new quoteToken. The error body has no code field, so match the QUOTE_EXPIRED: prefix of error.
The same one, with the same request but another externalId200 and the same payment: it keeps the first request's externalId.
The same one, with other terms (payer, URLs, installments, beneficiaryWalletId and so on)409 this quoteToken already opened a sale with different terms; send the same request to retry it, or quote the sale again for a new one
A quoteToken that already opened a checkout session409 this quoteToken already opened a sale with different terms; send the same request to retry it, or quote the sale again for a new one: one token opens one sale, on one entry point.

externalId is not a key: payments made from different quotes may carry the same externalId, or none.

After a refusal, quote again and send the new quoteToken for the next attempt. A repeat does not update anything: the card and the device block are not compared, and a different card in the repeat is ignored. A repeat is a new request: sign it again with a fresh timestamp.

The same applies to a 400 that comes after the session exists: an installments the account does not offer, a prepaid card, a quote whose markup went above your workspace's cap, or an amount above your per-payment or monthly limit. The session was already created with the first request's terms, so the corrected request is a request with other terms: repeating the same quoteToken answers 409. Fix the request, quote again and send it with the new quoteToken.

It is safe to repeat any 5xx or a timeout with the same quoteToken and body: you get the existing result back, never a second charge. Do not repeat a 4xx without fixing the request.

3D Secure​

When status is PENDING_3DS, the answer has a redirectUrl:

JSON
{
"id": "e4b8d1a2-6c3f-4a9e-b7d5-1f2e3a4b5c6d",
"status": "PENDING_3DS",
"redirectUrl": "https://...",
"successUrl": "https://shop.example.com/orders/10045/thanks",
"cancelUrl": "https://shop.example.com/orders/10045/payment-failed"
}

Redirect the cardholder's browser to redirectUrl: a full-page navigation, not a popup. An iframe is not supported: at the end of the challenge your successUrl would load inside the frame, and many sites forbid being framed.

The cardholder completes the bank's challenge. Then:

  • the cardholder is sent to your successUrl, whether the challenge passed or failed, with no parameters added (put your order id in that URL);
  • you receive ACQUIRING-PAYMENT-CAPTURED, or ACQUIRING-PAYMENT-DECLINED or ACQUIRING-PAYMENT-EXPIRED.

Reaching successUrl does not mean the payment was approved. Your page should show "confirming your payment" and decide the order's fate from the webhook. A cardholder who closes the tab never reaches it; the webhook still arrives (EXPIRED if the challenge was abandoned).

3D Secure only runs when the sale asks for it: when the payment saves a card, when it pays a saved card with the cardholder present, or when your account is set to require it on every sale. In the sandbox, see the 3D Secure test cards.

Installments​

installments splits a credit card payment. Absent or 1 is a single payment. A number above your account's maxInstallments, or any number above 1 on a card Avenia can tell is debit, is refused with 400 InvalidFieldError: installments is invalid before anything is charged. You finance the installments: the cardholder pays no interest and you receive each installment's share as it falls due (see Settlement and Schedule). The payment's installments and paymentMethod (CREDIT or DEBIT) are on every read and event.

Read a payment​

GEThttps://api.sandbox.avenia.io:10952/v2/account/acquiring/payments/{payment-id}

Sent to the API base URL with your usual key. It returns the payment with the fields its events carry, plus its refunds. Use it when you missed an event, or to check a refund's state at any time. A payment of another account or sub-account, or one that does not exist, answers 404.

JSON
{
"id": "e4b8d1a2-6c3f-4a9e-b7d5-1f2e3a4b5c6d",
"userId": "a91d3c47-5e20-4f8b-9c16-7d2e0b4a8f13",
"checkoutSessionId": "3f6a9c2e-8b1d-4e7f-a05c-6d2b9e4f1a87",
"externalId": "order-10045",
"status": "PARTIALLY_REFUNDED",
"subStatus": "",
"amount": "150",
"currency": "BRL",
"country": "BR",
"installments": 1,
"paymentMethod": "CREDIT",
"authorizedAmount": "150",
"capturedAmount": "150",
"refundedAmount": "10",
"chargedBackAmount": "0",
"disputeWindowClosesAt": "2027-04-08T15:02:12Z",
"createdAt": "2026-10-08T15:02:11.482Z",
"capturedAt": "2026-10-08T15:02:12Z",
"savedCardId": "",
"card": { "brand": "VISA", "last4": "0002" },
"declineBucket": "",
"failureCode": "",
"refunds": [
{
"id": "9a7b4c1e-2d3f-4a5b-8c6d-7e8f9a0b1c2d",
"amount": "10",
"reason": "REQUESTED_BY_CUSTOMER",
"status": "SUCCEEDED",
"externalId": "refund-1001",
"approvalExpiresAt": "",
"createdAt": "2026-10-09T10:00:00Z",
"updatedAt": "2026-10-09T10:00:05Z",
"failureCode": ""
}
],
"beneficiaryWalletId": "",
"walletAddress": "",
"walletChain": "",
"quote": { "outputCurrency": "BRLA", "outputPaymentMethod": "INTERNAL", "inputFee": "4.875", "markupFee": "0", "...": "..." },
"receivables": [
{ "installmentNumber": 1, "expectedDate": "2026-11-09", "...": "..." }
]
}
FieldMeaning
userIdThe account the sale belongs to: your account, or the sub-account it was made for.
checkoutSessionIdThe checkout session the payment was made in.
capturedAtWhen the payment was captured; "" while it is not.
cardThe card's network brand and its last4 digits. Both are "" when unknown, for example on a payment refused before the card was read. The full card number is never returned.

refunds lists every refund asked of the payment, oldest first. A refund's status is PENDING_APPROVAL, PENDING, SUCCEEDED or FAILED: see Refunds. Its failureCode says why a FAILED refund failed, when the cause is one you can act on, and is "" otherwise: see refund failure codes.

Go-live checklist​

Server-to-server payments are sandbox-only for now. When production opens, we will ask you to confirm that you:

  • sent your AOC to Avenia;
  • send card data only to the relay URL, only under card.encrypted, and keep card numbers and security codes out of your logs, metrics and error reports;
  • use a dedicated payments key whose allowlist holds the relay's addresses, and your usual key for everything else;
  • sign the payment over the canonical body without card.encrypted, and every other call over the exact body, with your clock synced over NTP;
  • fill the device block from the cardholder's real device, never from your server;
  • use a new quoteToken per attempt, and repeat timeouts with the same one and the same body;
  • handle 3D Secure (redirect to redirectUrl, then a successUrl page that waits for the webhook), including a cardholder who abandons it;
  • verify the webhook Signature on the raw body, answer 2xx quickly and deduplicate on event.id (Webhooks);
  • fulfil orders only on ACQUIRING-PAYMENT-CAPTURED, and handle ACQUIRING-PAYMENT-REFUNDED for a payment you did not refund;
  • reconcile periodically with the events API and the reads;
  • if you save cards: collect and record the cardholder's agreement, then saved a card, listed it, paid it with the cardholder present, charged it without the cardholder and revoked it.