Handle errors
Tell a decline from a mistake in your request, and decide in code what to retry, fix, or show the customer.
The API returns a 4xx or 5xx status and an error object when a request
fails. A decline is one of these failures. The request worked, but the payment
didn't. Decide in code what to do with each, and look up the codes themselves
in Errors.
Branch on status, type, and code
Read the HTTP status first, then error.type and error.code. Error messages
are written for developers and can change without notice, so don't match on
message text in code.
| Status | error.type | error.code | What your code does |
|---|---|---|---|
2xx | None | None | Read the object's status. pending or requires_authentication, for example, means the payment isn't finished. |
400 | payment_method_error | card_declined (see decline_code) | Handle the decline. |
400 | invalid_request_error | invalid_parameters, merchant_conflict, and others | Fix the request. When present, params lists the fields that failed validation. |
400 | idempotency_error | invalid_parameters | The idempotency key was used for another endpoint or request body. Send a new key with a new request. |
401 | invalid_request_error | invalid_key, invalid_token, and others | Stop and check the API key and its target environment. |
403 | invalid_request_error | resource_not_allowed, network_not_allowed, merchant_required, and others | Stop and update the key or request based on error.code. See Manage API keys. |
404 | invalid_request_error | resource_missing | Check the ID and confirm it belongs to the same environment and workspace as the key. |
408 | None | None | The request timed out before finishing. Check whether the object was created, or retry later with the same idempotency key. |
409 | idempotency_error | request_in_progress | Wait, then retry with the same key. |
422 | invalid_request_error | Varies | The object or your account can't complete this operation in its current state. Retrieve the object before retrying. |
429 | invalid_request_error | request_in_progress | Another bulk query is running. Wait for Retry-After, then retry. |
500 | api_error | Varies | Check whether the object was created before sending the request again, and use a new key only if it wasn't. |
502, 504 | None | None | Gateway error or upstream timeout. Wait, then retry with the same key and body. |
503 | api_error | unavailable | Wait for Retry-After (or a few seconds if omitted), then retry with the same key and body. |
Handle declines
A declined or blocked charge, hold, refund, or payout returns 400 with the
type payment_method_error, and the object is still created:
- The object's ID is in the field named after it:
charge,hold,refund, orpayout. Save it. Retrieve it to see whether itsstatusisfailedorblocked. decline_codeis the reason, and can be null. The error codes have a message for each that you can show the customer.- Retrying with the same idempotency key returns the same decline response. A new payment attempt (for example, with another card) requires a new idempotency key.
Read errors safely
These examples create a charge and read a decline or an error from the response.
export async function createCharge(charge, idempotencyKey) {
const response = await fetch('https://api.sandbox.pay.com/v1/charges', {
method: 'POST',
headers: {
Authorization: `Basic ${Buffer.from(`:${process.env.PAY_COM_API_KEY}`).toString('base64')}`,
'Content-Type': 'application/json',
'idempotency-key': idempotencyKey,
},
body: JSON.stringify(charge),
});
const text = await response.text();
let body = {};
try {
body = JSON.parse(text);
} catch {}
if (response.ok) return { declined: false, id: body.id, status: body.status };
const error = body.error ?? body;
if (error.type === 'payment_method_error') {
return { declined: true, id: error.charge, reason: error.decline_code };
}
const requestId = response.headers.get('x-paycom-request-id');
throw new Error(`Pay.com ${response.status} ${error.code ?? ''}: ${error.message ?? text} (request ${requestId})`);
}import os
import requests
def create_charge(charge, idempotency_key):
response = requests.post(
"https://api.sandbox.pay.com/v1/charges",
auth=("", os.environ["PAY_COM_API_KEY"]),
headers={"idempotency-key": idempotency_key},
json=charge,
timeout=60,
)
try:
body = response.json()
except ValueError:
body = {}
if response.ok:
return {"declined": False, "id": body["id"], "status": body["status"]}
error = body.get("error", body)
if error.get("type") == "payment_method_error":
return {"declined": True, "id": error.get("charge"), "reason": error.get("decline_code")}
request_id = response.headers.get("x-paycom-request-id")
message = error.get("message", response.text)
raise RuntimeError(f"Pay.com {response.status_code} {error.get('code', '')}: {message} (request {request_id})")Log what support needs
Log the status, type, code, the object's ID, and the x-paycom-request-id
response header. That header identifies the request in Pay.com. The header is
absent if the request was rejected before reaching the API (for example, due to
an unknown key or malformed JSON). Never log the key, the Authorization
header, or card details.