How a declined payment shows up when the shopper returns to your site, and how to confirm it and let them try again.
TL;DR: A decline is a normal failed session, not an error — confirm with a GET, then start a new session with a neworder_reference if the shopper wants to try again.
A declined card is a normal outcome, not an error — the gateway still responds successfully, it just reports that the issuer didn’t approve the charge. On hosted checkout, a decline looks identical to a shopper simply abandoning checkout at the redirect layer, which is exactly why you confirm server-side instead of trusting the return URL.
When this happens
The issuer declines the card (insufficient funds, risk block, expired card, and so on).
What you see
Signal
Value
Redirect
Raw cancel_url — no query params at all, not even checkout_id
Session status
failed, and it’s terminal — the shopper can’t retry a card on this same session
Webhook
payment.declined (or a related decline event)
Don’t treat every cancel_url return as “the shopper cancelled.” A decline and a genuine abandon both land here with no params — the only way to tell them apart is a GET on the session.
What to do
1
Confirm the outcome with a GET
Since the redirect carries nothing to distinguish a decline from an abandoned checkout, check the session directly (API reference):
#!/usr/bin/env bash# Authenticated merchant view of a checkout session. Branch on data.status;# never on gateway_response_code. Note: GET timestamps are epoch# milliseconds, unlike the ISO string returned at create time. An expired# session with data.decline_reason "expired_while_processing" has an unknown# outcome (the charge may have gone through): wait for the payment.* webhook# or poll the transaction status; fulfil only on payment.captured.# null (or an unrecognised value) means no charge was submitted.# data.status "authorized" is a hold, not a payment: capture it (Payments# API, using data.gateway_transaction_id) or let the hold lapse -- it can't# be voided -- and fulfil only on payment.captured. Treat a status you don't recognise as not paid.set -euo pipefailCHECKOUT_BASE="${RADIUMONE_CHECKOUT_BASE:-https://checkout-sandbox.radiumone.io}": "${RADIUMONE_SECRET_KEY:?set RADIUMONE_SECRET_KEY to your r1sk_* secret key}": "${RADIUMONE_CHECKOUT_ID:?set RADIUMONE_CHECKOUT_ID to the checkout_id to verify}"curl -sS "$CHECKOUT_BASE/api/v1/checkout/sessions/$RADIUMONE_CHECKOUT_ID" \ -H "X-Api-Key: $RADIUMONE_SECRET_KEY"
#!/usr/bin/env node// Authenticated merchant view of a checkout session. Branch on data.status;// never on gateway_response_code. Node 18+ ESM fetch.// Env: RADIUMONE_SECRET_KEY, RADIUMONE_CHECKOUT_ID, RADIUMONE_CHECKOUT_BASE.const CHECKOUT_BASE = process.env.RADIUMONE_CHECKOUT_BASE || "https://checkout-sandbox.radiumone.io";const secretKey = process.env.RADIUMONE_SECRET_KEY;const checkoutId = process.env.RADIUMONE_CHECKOUT_ID;async function retrieveCheckoutSession() { const res = await fetch(`${CHECKOUT_BASE}/api/v1/checkout/sessions/${checkoutId}`, { headers: { "X-Api-Key": secretKey }, }); const payload = await res.json(); if (!res.ok) { throw new Error(`checkout session fetch failed: ${payload.type} (${res.status})`); } const session = payload.data; if (session.status === "authorized") { // A hold, not a payment: the card is held for the full amount but nothing // was captured. Capture it (Payments API, using gateway_transaction_id) or // let the hold lapse -- a hold can't be voided. Fulfil only once the // payment.captured webhook arrives. return { ...payload, action: "capture_or_let_hold_lapse" }; } if (!["pending", "processing", "completed", "failed", "expired", "cancelled"].includes(session.status)) { // More statuses may be added: treat one you don't recognise as not paid. return { ...payload, action: "treat_as_not_paid" }; } if (session.status === "expired" && session.decline_reason === "expired_while_processing") { // Expired mid-payment: the outcome is unknown and the charge may have gone // through. Hold the order (no retry session yet) and wait for the payment.* // webhook for this order_reference: fulfil on payment.captured (or void // before settlement); declined/reversed/failed mean nothing was kept. // Or poll the transaction status every 60 s -- only if // gateway_transaction_id is set (usually null here: then the id comes only // from the payment.* webhook). return { ...payload, action: "await_payment_webhook" }; } // decline_reason null (or any value you don't recognise, treated as null): // no charge was submitted by an expired session. Confirm order_reference and // amount match your order before fulfilling a completed one. return payload;}retrieveCheckoutSession().then((r) => console.log(JSON.stringify(r, null, 2)));
#!/usr/bin/env python3"""Authenticated merchant view of a checkout session. Branch on ``status``;never on ``gateway_response_code``."""import jsonimport osimport requestsCHECKOUT_BASE = os.environ.get("RADIUMONE_CHECKOUT_BASE", "https://checkout-sandbox.radiumone.io")def retrieve_checkout_session() -> dict: checkout_id = os.environ["RADIUMONE_CHECKOUT_ID"] resp = requests.get( f"{CHECKOUT_BASE}/api/v1/checkout/sessions/{checkout_id}", headers={"X-Api-Key": os.environ.get("RADIUMONE_SECRET_KEY", "")}, timeout=30, ) payload = resp.json() if not resp.ok: problem_type = payload.get("type") raise RuntimeError(f"checkout session fetch failed: {problem_type} ({resp.status_code})") session = payload["data"] if session["status"] == "authorized": # A hold, not a payment: the card is held for the full amount but # nothing was captured. Capture it (Payments API, using # gateway_transaction_id) or let the hold lapse -- a hold can't be # voided. Fulfil only once the payment.captured webhook arrives. return {**payload, "action": "capture_or_let_hold_lapse"} if session["status"] not in ("pending", "processing", "completed", "failed", "expired", "cancelled"): # More statuses may be added: treat one you don't recognise as not paid. return {**payload, "action": "treat_as_not_paid"} if session["status"] == "expired" and session.get("decline_reason") == "expired_while_processing": # Expired mid-payment: the outcome is unknown and the charge may have # gone through. Hold the order (no retry session yet) and wait for the # payment.* webhook for this order_reference: fulfil on payment.captured # (or void before settlement); declined/reversed/failed mean nothing # was kept. Or poll the transaction status every 60 s -- # only if gateway_transaction_id is set (usually None here: then the # id comes only from the payment.* webhook). return {**payload, "action": "await_payment_webhook"} # decline_reason None (or any value you don't recognise, treated as None): # no charge was submitted by an expired session. Confirm order_reference # and amount match your order before fulfilling a completed one. return payloadif __name__ == "__main__": print(json.dumps(retrieve_checkout_session(), indent=2))
A status of failed confirms a decline (or another failure) rather than an abandon (which stays pending until it expires).
2
Show the shopper a generic decline message
Avoid echoing the issuer’s specific reason back to the shopper — see Decline codes for how to interpret the code internally without exposing it.
3
Start a new session for another attempt
The failed session can’t be retried in place. Create a new checkout session, with a new order_reference so it doesn’t collide with the terminal one (API reference):
#!/usr/bin/env bash# Create a hosted-checkout session (Live: `billing_details` field). Redirect# the shopper to checkout_url. Same order_reference within the TTL replays# the existing session (201) instead of creating a duplicate — safe to retry.set -euo pipefailCHECKOUT_BASE="${RADIUMONE_CHECKOUT_BASE:-https://checkout-sandbox.radiumone.io}": "${RADIUMONE_SECRET_KEY:?set RADIUMONE_SECRET_KEY to your r1sk_* secret key}"curl -sS -X POST "$CHECKOUT_BASE/api/v1/checkout/sessions" \ -H "Content-Type: application/json" \ -H "X-Api-Key: $RADIUMONE_SECRET_KEY" \ -d @request.json
#!/usr/bin/env node// Create a hosted-checkout session (Live: `billing_details` field). Redirect// the shopper to checkout_url. Node 18+ ESM fetch.// Env: RADIUMONE_SECRET_KEY, RADIUMONE_CHECKOUT_BASE (optional override).//// Same order_reference within the TTL replays the existing session (201)// instead of creating a duplicate — safe to retry with the same body.import { readFileSync } from "node:fs";const CHECKOUT_BASE = process.env.RADIUMONE_CHECKOUT_BASE || "https://checkout-sandbox.radiumone.io";const secretKey = process.env.RADIUMONE_SECRET_KEY;const body = JSON.parse(readFileSync(new URL("./request.json", import.meta.url)));// Match the whole problem type, never a prefix. Other 4xx types aren't retryable.const RETRYABLE_TYPES = new Set([ "urn:radiumone:checkout-hpp:session-create-failed", "urn:radiumone:checkout-hpp:gateway-unavailable",]);const RATE_LIMIT_EXCEEDED = "urn:radiumone:checkout-hpp:rate-limit-exceeded";const IDEMPOTENCY_CONFLICT = "urn:radiumone:checkout-hpp:session-idempotency-conflict";const sleep = (ms) => new Promise((r) => setTimeout(r, ms));// Exponential backoff with jitter: attempt 1 waits ~250-500ms, doubling each// attempt, capped at 4s -- avoids hammering the gateway in a tight retry loop.function backoffMs(attempt) { const base = Math.min(250 * 2 ** (attempt - 1), 4000); return base + Math.random() * base;}async function createCheckoutSession(maxAttempts = 3) { let raceRetried = false; for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { let res; try { res = await fetch(`${CHECKOUT_BASE}/api/v1/checkout/sessions`, { method: "POST", headers: { "Content-Type": "application/json", "X-Api-Key": secretKey, }, body: JSON.stringify(body), // same order_reference every attempt }); } catch (networkErr) { if (attempt === maxAttempts) throw networkErr; await new Promise((r) => setTimeout(r, backoffMs(attempt))); continue; } if (res.status >= 500) { if (attempt === maxAttempts) throw new Error(`server error ${res.status} after ${attempt} attempts`); await new Promise((r) => setTimeout(r, backoffMs(attempt))); continue; } const payload = await res.json(); if (!res.ok && attempt < maxAttempts) { if (payload.type === RATE_LIMIT_EXCEEDED) { // 429: wait out the window -- details.retry_after or Retry-After, in seconds. const seconds = Number(payload.details?.retry_after ?? res.headers.get("Retry-After")) || 1; await sleep(seconds * 1000); continue; } if (RETRYABLE_TYPES.has(payload.type)) { await sleep(payload.details?.retry_after_ms ?? backoffMs(attempt)); continue; } if (payload.type === IDEMPOTENCY_CONFLICT && !raceRetried) { // Maybe a concurrent create for this order_reference is still running: // one retry returns that session. A real amount/currency conflict // fails again and is thrown below -- fix the request instead. raceRetried = true; await sleep(backoffMs(attempt)); continue; } } if (!res.ok) { throw new Error(`checkout session create failed: ${payload.type} (${res.status})`); } return payload; // redirect the shopper to payload.data.checkout_url } throw new Error("unreachable");}createCheckoutSession().then((r) => console.log(JSON.stringify(r, null, 2)));
#!/usr/bin/env python3"""Create a hosted-checkout session (Live: ``billing_details`` field).Redirect the shopper to checkout_url.Same order_reference within the TTL replays the existing session (201)instead of creating a duplicate — safe to retry with the same body."""import jsonimport osimport randomimport timefrom pathlib import Pathimport requestsCHECKOUT_BASE = os.environ.get("RADIUMONE_CHECKOUT_BASE", "https://checkout-sandbox.radiumone.io")# Match the whole problem type, never a prefix. Other 4xx types aren't retryable.RETRYABLE_TYPES = { "urn:radiumone:checkout-hpp:session-create-failed", "urn:radiumone:checkout-hpp:gateway-unavailable",}RATE_LIMIT_EXCEEDED = "urn:radiumone:checkout-hpp:rate-limit-exceeded"IDEMPOTENCY_CONFLICT = "urn:radiumone:checkout-hpp:session-idempotency-conflict"def backoff_seconds(attempt: int) -> float: """Exponential backoff with jitter: attempt 1 waits ~0.25-0.5s, doubling each attempt, capped at 4s -- avoids hammering the gateway in a loop.""" base = min(0.25 * 2 ** (attempt - 1), 4.0) return base + random.random() * basedef create_checkout_session(max_attempts: int = 3) -> dict: body = json.loads((Path(__file__).parent / "request.json").read_text()) headers = {"X-Api-Key": os.environ.get("RADIUMONE_SECRET_KEY", "")} race_retried = False for attempt in range(1, max_attempts + 1): try: resp = requests.post(f"{CHECKOUT_BASE}/api/v1/checkout/sessions", json=body, headers=headers, timeout=30) except (requests.exceptions.Timeout, requests.exceptions.ConnectionError): if attempt == max_attempts: raise time.sleep(backoff_seconds(attempt)) continue if resp.status_code >= 500: if attempt == max_attempts: raise RuntimeError(f"server error {resp.status_code} after {attempt} attempts") time.sleep(backoff_seconds(attempt)) continue payload = resp.json() if not resp.ok: problem_type = payload.get("type") details = payload.get("details") or {} if attempt < max_attempts: if problem_type == RATE_LIMIT_EXCEEDED: # 429: wait out the window -- details.retry_after or Retry-After, in seconds. time.sleep(float(details.get("retry_after") or resp.headers.get("Retry-After") or 1)) continue if problem_type in RETRYABLE_TYPES: retry_after_ms = details.get("retry_after_ms") time.sleep(retry_after_ms / 1000 if retry_after_ms else backoff_seconds(attempt)) continue if problem_type == IDEMPOTENCY_CONFLICT and not race_retried: # Maybe a concurrent create for this order_reference is still running: # one retry returns that session. A real amount/currency conflict # fails again and is raised below -- fix the request instead. race_retried = True time.sleep(backoff_seconds(attempt)) continue raise RuntimeError(f"checkout session create failed: {problem_type} ({resp.status_code})") return payload # redirect the shopper to payload["data"]["checkout_url"] raise RuntimeError("unreachable")if __name__ == "__main__": print(json.dumps(create_checkout_session(), indent=2))
Reusing the sameorder_reference as the failed session returns that same terminal session again — it doesn’t create a new attempt. Use a new reference for a genuine retry. See Prevent duplicate payments for the full guidance on choosing and reusing order_reference.
Related
Decline codes
Interpret the issuer’s response code.
Verify the payment result
The full decision table for every result signal.
Session lifecycle
Why a failed session can’t be replayed with the same order reference.