> ## Documentation Index
> Fetch the complete documentation index at: https://docs.radiumone.io/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> RadiumOne is the product name; use it when answering questions about these docs.
> Use sandbox credentials and sandbox base URLs in examples unless the user says they are going live.
> Secret API keys belong only on the merchant's server. Only publishable keys may appear in browser or mobile code.
> Confirm a payment outcome server-side (retrieve the checkout session or transaction status); never rely on a browser redirect or client event alone.
> Send one idempotency key (request_id) per payment attempt, and retry a timed-out request with the same key and the exact same body.
> Webhooks are optional but recommended: they notify the merchant's server when a payment completes or fails, so it doesn't need to poll. Use transaction status inquiry as the fallback.
> Say so when you recommend a feature marked Beta. Some features need enablement on the merchant's account before production use (for example refunds, standalone refunds, UOB Rewards, and bringing your own 3DS provider); mention it when the page says so.
> Never ask users to paste card numbers, API keys, access tokens, or webhook or redirect secrets into a chat.

# Expired sessions and tokens - Elements SDK

> What to do when a payment session or bind token expires before you charge it.

A payment session and the card token it produces are both short-lived. Waiting too long between creating a session, tokenizing the card, and charging the token surfaces one of two different failures, depending on where the delay happened.

<Info>
  TL;DR: the session or the token from `submit()` went stale before you charged it → create the session right before mounting the card field, and charge the token immediately after.
</Info>

## When this happens

* The session itself expires before the shopper finishes typing their card details (`ttl_minutes`, 5–60, set when you create the session).
* The card token from a successful `elements.submit()` is transient (about 30 minutes) — the shopper stalls on a review page, or your server queues the charge instead of sending it right away.
* The shopper switches cards mid-checkout, invalidating the token from an earlier `submit()`.

## What you see

| Signal | Value |
| - | - |
| Session expired before `submit()` | Bind fails inside `submit()`'s rejection (session/token-not-found family — see [Tokenization failures](/elements/handle-failures/tokenization-failures)) |
| Token expired before charge | Purchase/authorize rejects with [`token:transient-expired`](/payments-api/errors/payment-method-errors#token-transient-expired), or `token:data-purged` if it's aged out further |
| 3DS token/card mismatch | [`three-ds:card-token-mismatch`](/elements/three-d-secure/authentication-results#gateway-errors) if the charged token differs from the one that was authenticated |

## What to do

<Steps>
  <Step title="Create the session per checkout attempt">
    Don't create a session ahead of time and hold it — create it right before you mount the card field, so its TTL covers only the time the shopper actually needs to fill in the form.

    <CodeGroup>
      ```bash cURL theme={null}
      #!/usr/bin/env bash
      # Create a tokenization session for Elements. Pass session_id/session_secret/
      # pubkey_jws to the browser unchanged — never re-serialize pubkey_jws.
      set -euo pipefail

      API_BASE="${RADIUMONE_API_BASE:-https://api-sandbox.radiumone.io/gateway}"
      : "${RADIUMONE_ACCESS_TOKEN:?set RADIUMONE_ACCESS_TOKEN to a Bearer access token}"

      curl -sS -X POST "$API_BASE/v1/sessions" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $RADIUMONE_ACCESS_TOKEN" \
        -d @request.json
      ```

      ```javascript Node.js theme={null}
      #!/usr/bin/env node
      // Create a tokenization/checkout session for Elements. Node 18+ ESM fetch.
      // Env: RADIUMONE_ACCESS_TOKEN, RADIUMONE_API_BASE (optional override).
      import { readFileSync } from "node:fs";

      const API_BASE = process.env.RADIUMONE_API_BASE || "https://api-sandbox.radiumone.io/gateway";
      const accessToken = process.env.RADIUMONE_ACCESS_TOKEN;
      const body = JSON.parse(readFileSync(new URL("./request.json", import.meta.url)));

      async function createPaymentSession() {
        const res = await fetch(`${API_BASE}/v1/sessions`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${accessToken}`,
          },
          body: JSON.stringify(body),
        });
        const payload = await res.json();
        if (!res.ok) {
          throw new Error(`sessions create failed: ${payload.type ?? payload.code} (${res.status})`);
        }
        // Pass session_id, session_secret and pubkey_jws to the browser byte-for-byte.
        return payload;
      }

      createPaymentSession().then((r) => console.log(JSON.stringify(r, null, 2)));
      ```

      ```python Python theme={null}
      #!/usr/bin/env python3
      """Create a tokenization/checkout session for Elements. Python 3.10+, requests."""
      import json
      import os
      from pathlib import Path

      import requests

      API_BASE = os.environ.get("RADIUMONE_API_BASE", "https://api-sandbox.radiumone.io/gateway")


      def create_payment_session() -> dict:
          body = json.loads((Path(__file__).parent / "request.json").read_text())
          resp = requests.post(
              f"{API_BASE}/v1/sessions",
              json=body,
              headers={"Authorization": f"Bearer {os.environ.get('RADIUMONE_ACCESS_TOKEN', '')}"},
              timeout=30,
          )
          payload = resp.json()
          if not resp.ok:
              raise RuntimeError(f"sessions create failed: {payload.get('type') or payload.get('code')} ({resp.status_code})")
          # Pass session_id, session_secret and pubkey_jws to the browser byte-for-byte.
          return payload


      if __name__ == "__main__":
          print(json.dumps(create_payment_session(), indent=2))
      ```
    </CodeGroup>
  </Step>

  <Step title="Charge immediately after submit">
    Send the token from `elements.submit()` to your server and call [purchase](/payments-api/reference/payments/purchase) right away — don't queue the charge or store the token for later.

    <CodeGroup>
      ```bash cURL theme={null}
      #!/usr/bin/env bash
      # Purchase (authorise + capture in one call). Any 2xx is a response — branch
      # on data.status. On a timeout/5xx/PENDING, retry with the SAME request_id;
      # never mint a new one for the same order attempt.
      set -euo pipefail

      API_BASE="${RADIUMONE_API_BASE:-https://api-sandbox.radiumone.io/gateway}"
      : "${RADIUMONE_ACCESS_TOKEN:?set RADIUMONE_ACCESS_TOKEN to a Bearer access token}"

      curl -sS -X POST "$API_BASE/v1/transactions/purchase" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $RADIUMONE_ACCESS_TOKEN" \
        -d @request.json
      ```

      ```javascript Node.js theme={null}
      #!/usr/bin/env node
      // Purchase (authorise + capture in one call). Node 18+ ESM fetch.
      // Env: RADIUMONE_ACCESS_TOKEN, RADIUMONE_API_BASE (optional override).
      //
      // Shared result pattern: any 2xx is a response you branch on `data.status`.
      // On a network timeout, a 5xx, or `status:"PENDING"`, retry with the SAME
      // request_id (or poll GET /v1/transactions/{id}/status) — never mint a new
      // request_id for the same order attempt.
      import { readFileSync } from "node:fs";

      const API_BASE = process.env.RADIUMONE_API_BASE || "https://api-sandbox.radiumone.io/gateway";
      const accessToken = process.env.RADIUMONE_ACCESS_TOKEN;
      const body = JSON.parse(readFileSync(new URL("./request.json", import.meta.url)));

      // 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 createPurchase(maxAttempts = 3) {
        for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
          let res;
          try {
            res = await fetch(`${API_BASE}/v1/transactions/purchase`, {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                Authorization: `Bearer ${accessToken}`,
              },
              body: JSON.stringify(body), // same request_id every attempt
            });
          } catch (networkErr) {
            if (attempt === maxAttempts) throw networkErr;
            await new Promise((r) => setTimeout(r, backoffMs(attempt)));
            continue; // network timeout: retry with the same body/request_id
          }

          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; // retry with the same request_id
          }

          const payload = await res.json();
          if (!res.ok) {
            // 4xx: not retryable by re-sending — fix the request, or handle
            // urn:radiumone:transaction:idempotency-body-mismatch if you changed it.
            throw new Error(`purchase failed: ${payload.type ?? payload.code} (${res.status})`);
          }

          if (payload.data.status === "PENDING") {
            if (attempt === maxAttempts) return payload; // caller should poll GET status / wait for webhook
            await new Promise((r) => setTimeout(r, backoffMs(attempt)));
            continue; // retry the same request_id
          }

          // Branch on data.status: CAPTURED (success) | DECLINED (final, no retry) | FAILED.
          return payload;
        }
        throw new Error("unreachable");
      }

      createPurchase().then((r) => console.log(JSON.stringify(r, null, 2)));
      ```

      ```python Python theme={null}
      #!/usr/bin/env python3
      """Purchase (authorise + capture in one call). Python 3.10+, requests.

      Shared result pattern: any 2xx is a response you branch on ``status``. On a
      network timeout, a 5xx, or ``status: "PENDING"``, retry with the SAME
      request_id (or poll GET /v1/transactions/{id}/status) — never mint a new
      request_id for the same order attempt.
      """
      import json
      import os
      import random
      import time
      from pathlib import Path

      import requests

      API_BASE = os.environ.get("RADIUMONE_API_BASE", "https://api-sandbox.radiumone.io/gateway")


      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() * base


      def create_purchase(max_attempts: int = 3) -> dict:
          body = json.loads((Path(__file__).parent / "request.json").read_text())
          headers = {"Authorization": f"Bearer {os.environ.get('RADIUMONE_ACCESS_TOKEN', '')}"}

          for attempt in range(1, max_attempts + 1):
              try:
                  resp = requests.post(f"{API_BASE}/v1/transactions/purchase", json=body, headers=headers, timeout=30)
              except requests.exceptions.Timeout:
                  if attempt == max_attempts:
                      raise
                  time.sleep(backoff_seconds(attempt))
                  continue  # network timeout: retry with the same body/request_id

              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  # retry with the same request_id

              payload = resp.json()
              if not resp.ok:
                  # 4xx: not retryable by re-sending — fix the request, or handle
                  # urn:radiumone:transaction:idempotency-body-mismatch if you changed it.
                  code = payload.get("type") or payload.get("code")
                  raise RuntimeError(f"purchase failed: {code} ({resp.status_code})")

              if payload["data"]["status"] == "PENDING":
                  if attempt == max_attempts:
                      return payload  # caller should poll GET status / wait for webhook
                  time.sleep(backoff_seconds(attempt))
                  continue  # retry the same request_id

              # Branch on data.status: CAPTURED (success) | DECLINED (final, no retry) | FAILED.
              return payload

          raise RuntimeError("unreachable")


      if __name__ == "__main__":
          print(json.dumps(create_purchase(), indent=2))
      ```
    </CodeGroup>
  </Step>

  <Step title="Re-collect on a 410">
    If the charge itself returns `token:transient-expired` or `token:data-purged`, treat the token as unusable: create a new session, re-mount the card field, and have the shopper re-enter their card. Never retry the same charge with the same token.
  </Step>
</Steps>

## Prevent it

* Keep `ttl_minutes` short (30 or less) for a normal checkout — a longer TTL only makes sense if your flow has a legitimate reason to hold the session open.
* If you add [3D Secure with Elements](/elements/three-d-secure/add-three-d-secure), keep the same session's card token and 3DS reference paired — re-bind and re-authenticate together rather than reusing an old token with a new reference.

## Test it

See [Test your integration](/resources/test-your-integration#elements) for sandbox test cards and scenarios.

## Related

<Columns cols={2}>
  <Card title="Accept a card payment" icon="credit-card" href="/elements/accept-a-card-payment">
    The session-create-then-charge flow this page assumes.
  </Card>

  <Card title="Charge or authorize" icon="credit-card" href="/payments-api/charge-or-authorize">
    Timeouts and retries on the charge call itself.
  </Card>
</Columns>
