PayPal

PayPal sandbox: from first login to a captured test order

PayPal's developer docs are thorough and spread across a dozen pages. This is the path through them in the order you'll need it: the sandbox accounts you get for free, the credentials, a token, an order you create and capture in Python, how to make it fail on purpose, webhooks, and the switch to live. With the sandbox material from chapter 10.

Steps, limits and test values are from PayPal's developer docs, checked on 14 November 2026. PayPal renames dashboard menus often; the API endpoints change far less.

The PayPal sandbox is PayPal's test environment: "a self-contained, virtual testing environment that simulates the live PayPal production environment", where transactions are mock and touch no real accounts (PayPal). You get to it through the developer dashboard at developer.paypal.com, and it has its own API host, api-m.sandbox.paypal.com, and its own buyer site, www.sandbox.paypal.com.

From PayPal's developer docs, checked 14 November 2026.

1. Sandbox accounts

The first time you log in to the developer dashboard, PayPal creates two sandbox accounts for you: a personal account that plays the buyer and a business account that plays the seller, and the business one comes with sandbox API credentials (PayPal). Make more under Testing Tools > Sandbox Accounts: pick the type and country, and optionally set the email, password, PayPal balance, bank account and cards. Personal accounts get emails like sb-...@personal.example.com.

Make a buyer for each country you sell to, so you test in the currencies your customers will actually pay in.

2. REST credentials

In the dashboard, open Apps & Credentials, find the Default Application under REST API apps (or Create App), and copy the client ID and secret (PayPal). Sandbox and live credentials are separate; the code below reads them from environment variables so the secret never lands in the repository.

3. An access token

Every REST call carries an OAuth 2.0 bearer token. POST to /v1/oauth2/token with your client ID and secret as Basic auth and grant_type=client_credentials. PayPal returns the token and expires_in, the number of seconds it's valid; when it lapses, ask again (PayPal). PayPal's sample response shows 31668 seconds, which is 31668 / 3600 = 8.8 hours, but read the field rather than hard-coding a lifetime.

4. Create, approve, capture

Orders v2 is three steps (Orders v2 API):

  1. Create. POST /v2/checkout/orders with intent set to CAPTURE (take the money once approved) or AUTHORIZE (hold it now, capture later).
  2. Approve. The response carries a link with rel of approve, or payer-action in some flows. Send the buyer there and log in as your sandbox personal account. In production the JavaScript SDK buttons do this step.
  3. Capture. POST /v2/checkout/orders/{id}/capture.

Send a PayPal-Request-Id header on both calls. PayPal documents it as the idempotency key, so a retried request with the same ID doesn't create a second order or capture. Use an ID derived from your own order, not a fresh random one per attempt, or the retry gets a new key and the protection is gone.

Then check the right status. An order can be COMPLETED with a declined payment inside it; PayPal's schema says to check purchase_units[].payments.captures[].status before you fulfil. A capture can be COMPLETED, PENDING or DECLINED, among others. With AUTHORIZE, PayPal says authorizations are best captured within three days and can be captured for up to 29 days.

The whole loop in Python, sandbox host, credentials from the environment:

import os

import requests

BASE = "https://api-m.sandbox.paypal.com"  # live: https://api-m.paypal.com


def get_token():
    resp = requests.post(
        f"{BASE}/v1/oauth2/token",
        auth=(os.environ["PAYPAL_CLIENT_ID"], os.environ["PAYPAL_CLIENT_SECRET"]),
        data={"grant_type": "client_credentials"},
        timeout=15,
    )
    resp.raise_for_status()
    body = resp.json()
    # Cache both. Ask again when expires_in seconds have nearly passed.
    return body["access_token"], body["expires_in"]


def create_order(token, our_order_id, amount, currency="USD"):
    resp = requests.post(
        f"{BASE}/v2/checkout/orders",
        headers={
            "Authorization": f"Bearer {token}",
            # Same ID on a retry, so a timeout can't create a second order.
            "PayPal-Request-Id": f"create-{our_order_id}",
        },
        json={
            "intent": "CAPTURE",
            "purchase_units": [{
                "reference_id": our_order_id,
                "amount": {"currency_code": currency, "value": amount},
            }],
        },
        timeout=15,
    )
    resp.raise_for_status()
    order = resp.json()
    approve = next(link["href"] for link in order["links"]
                   if link["rel"] in ("approve", "payer-action"))
    return order["id"], approve  # send the buyer to approve


def capture(token, paypal_order_id):
    resp = requests.post(
        f"{BASE}/v2/checkout/orders/{paypal_order_id}/capture",
        headers={
            "Authorization": f"Bearer {token}",
            "PayPal-Request-Id": f"capture-{paypal_order_id}",
            "Prefer": "return=representation",  # minimal omits the captures
        },
        json={},
        timeout=15,
    )
    resp.raise_for_status()
    order = resp.json()
    first = order["purchase_units"][0]["payments"]["captures"][0]
    return first["status"]  # COMPLETED means money; PENDING means wait


if __name__ == "__main__":
    token, _ = get_token()
    order_id, url = create_order(token, "ord_1001", "25.00")
    print("Approve as your sandbox personal account:", url)
    input("Press Enter once approved... ")
    print(capture(token, order_id))

Two things in there that the quickstarts skip. The capture asks for Prefer: return=representation, because the default minimal response only carries the order's ID, status and links, not the captures. And a PENDING capture isn't money yet: wait for the PAYMENT.CAPTURE.COMPLETED webhook.

5. Make it fail on purpose

  • Card declines. Pay by card in the sandbox with a test card such as 4012 8888 8888 1881 and put a trigger in the First Name or Name on Card field: CCREJECT-IF for insufficient funds, CCREJECT-EC for an expired card, CCREJECT-CVV_F for a failed CVC, and others. Triggers are case-sensitive (PayPal).
  • API errors. Add a PayPal-Mock-Response header with {"mock_application_codes": "<error name>"} to force a specific error from a REST call; PayPal's capture example uses DUPLICATE_INVOICE_ID (PayPal).

6. Sandbox webhooks

Subscribe a listener URL to your sandbox app's events, in the app's settings or through the Webhooks Management API, and record the Webhook ID it's given: you need it to verify every delivery. The listener must be HTTPS on port 443 (PayPal), and an app can have up to 10 webhook URLs (PayPal). Real sandbox transactions through that app then fire real events.

The webhooks simulator in the dashboard is quicker, and more limited. It posts a mock event to any HTTPS listener on port 443, usually within about a minute. Mock events aren't linked to any app, don't appear in the event viewer, can't be resent, and can't be verified by posting back to verify-webhook-signature; only self-verification works, using the literal string WEBHOOK_ID as the webhook ID (PayPal). Use the simulator to test your parser, and a real sandbox order to test everything else. PayPal webhooks vs IPN has the signature check in Flask.

7. Going live

  • You need a verified Business or Premier PayPal account to get live credentials (PayPal).
  • Create the app on the Live tab of Apps & Credentials, and swap the sandbox host for https://api-m.paypal.com. Sandbox credentials and app IDs don't work in production.
  • Subscribe your live webhooks separately, on the live app. A live endpoint has its own Webhook ID.
  • Sandbox doesn't model the business side: holds, limitations and real fees. Price it with the PayPal fee calculator, and read PayPal account holds before launch day rather than after.

Keeping sandbox and live credentials apart, so development can't charge anyone. From chapter 10.

Sandbox vs Live Environment

PayPal gives you two environments. Sandbox processes fake payments and charges nobody, so that's where development and testing live. Switch to live credentials only when you're ready for real money.

// Sandbox credentials (for testing) - these process fake transactions
const SANDBOX_CLIENT_ID = 'your-sandbox-client-id';

// Live credentials (for production) - these process real money
const LIVE_CLIENT_ID = 'your-live-client-id';

// Environment selection based on your app's environment
// This ensures you never accidentally charge real money during development
const CLIENT_ID = process.env.NODE_ENV === 'production' 
    ? LIVE_CLIENT_ID       // Production: real payments
    : SANDBOX_CLIENT_ID;   // Development: fake payments

The checklist to run before switching to live credentials. From chapter 10.

Sandbox Testing

Run the full checklist in sandbox before you switch to live credentials:

  • Create test accounts (buyer and seller) - PayPal provides fake accounts with test funds.
  • Use sandbox API credentials - separate from your live credentials.
  • Test all payment flows - success, failure, cancellation, webhooks.
  • Test edge cases - insufficient funds, expired cards, disputes.

Questions

How do I get a PayPal sandbox account?

Log in to the PayPal developer dashboard at developer.paypal.com. On first login PayPal creates a default personal (buyer) and business (seller) sandbox account, and the business one comes with sandbox API credentials. Create more under Testing Tools > Sandbox Accounts.

Where do I find my PayPal client ID and secret?

In the developer dashboard under Apps & Credentials. Use the Default Application under REST API apps or create a new app, then copy the client ID and secret. Sandbox and live apps have separate credentials.

How long does a PayPal access token last?

PayPal returns the lifetime in seconds in the expires_in field. Its sample response shows 31668 seconds, about 8.8 hours. Cache the token, read expires_in, and request a new one when it lapses.

How do I test a declined payment in the PayPal sandbox?

Pay by card with a sandbox test card and put a trigger like CCREJECT-IF (insufficient funds) in the First Name or Name on Card field. For REST API errors, send a PayPal-Mock-Response header with mock_application_codes set to the error name.

Can I verify PayPal simulator webhooks?

Only by self-verification, using the string WEBHOOK_ID as the webhook ID. Mock events from the simulator can't be verified by posting back to verify-webhook-signature, aren't linked to an app, and can't be resent. Real sandbox transactions send real, verifiable events.

What the book adds

What chapters 10 and 39 add

  • The PayPal Checkout SDK, front end and back end
  • A PayPal client with token caching, refunds and subscriptions
  • Subscriptions, and the plan-before-subscription setup order
  • The seven webhook events to subscribe to first
  • PayPal's retries and ordering next to four other providers

30-day money-back · Instant PDF and EPUB

All 42 chapters