Skip to content

· 12 min read · Nadeera Silva

Payments

PayPal Sandbox Test Cards: Trigger and Handle Declines

PayPal sandbox test cards and CCREJECT triggers to force a decline, plus how to catch a DECLINED capture and INSTRUMENT_DECLINED in your code.

A hand lifts a blank white payment card out of a small oak sandbox tray beside a teal dish, an amber lamp and a laptop with an abstract checkout form, standing for PayPal sandbox card testing.

If you are searching for PayPal sandbox test cards, you probably already have the happy path working and now need to prove what happens when a card fails. That is where most PayPal integrations I review are weakest. The sandbox can produce a declined card on demand, but the decline does not always arrive as an error: PayPal can return an order with status COMPLETED while the capture inside it says DECLINED. This post lists the test cards and the CCREJECT triggers, explains the two shapes a decline can take, and shows tested Node, browser and curl code that handles both.

Quick answer

In the PayPal sandbox, use a test Visa such as 4012888888881881 with any future expiry and CVV, and type a rejection trigger like CCREJECT-IF (insufficient funds) in the first name or name-on-card field to force a card decline. After capture, check purchase_units[0].payments.captures[0].status and processor_response.response_code, not just the order status, and send Prefer: return=representation so those fields come back. If the capture call fails with INSTRUMENT_DECLINED, return that to the browser and call actions.restart() so the buyer can choose another way to pay.

What this means for your app or business

  • The real risk is shipping goods you were not paid for. If your code treats "order completed" as "paid", a declined card can still unlock a download, a booking or a shipment. PayPal's own sample response shows exactly this combination.
  • The opposite failure loses sales. If a decline shows a generic error and the PayPal popup closes, the buyer has no easy way to try another card or their PayPal balance, so many simply leave.
  • Testing it costs nothing. Sandbox accounts, test cards and decline triggers are free, and none of this needs a live card.
  • The fix is small. In most projects it is a few hours: one capture handler on the server, one branch in onApprove, and a webhook for payments that are still pending.
  • When to get help. If you sell through PayPal and cannot say what your checkout does with a declined card, ask a developer to run the tests below before your next release.

Which PayPal sandbox test cards should I use?

PayPal's card testing page lists static numbers for Expanded Checkout (card fields) and saved payment methods. Use a future expiry date and a 3-digit CVV, or 4 digits for American Express. These are a selection:

Card typeTest number
Visa4012888888881881
Visa4005519200000004
Mastercard2223000048400011
American Express371449635398431
Diners Club36461510000039
JCB3636500000000260

The same page has a credit card generator if you need cards for a specific country, and PayPal says generated cards can also be added to a sandbox account.

How do I make a PayPal sandbox card declined on purpose?

Type a rejection trigger into the First Name or Name on Card field and pay with a Visa test number such as 4012 8888 8888 1881. PayPal says the triggers are case-sensitive, and every rejection returns the AVS code as globally unavailable (G) and the CVV code as not processed (P).

What it simulatesTrigger (name on card)processor_response.response_codeMeaning
Card refusedCCREJECT-REFUSED0500DO_NOT_HONOR
Fraudulent cardCCREJECT-SF9500SUSPECTED_FRAUD, do not retry the same card
Card expiredCCREJECT-EC5400EXPIRED_CARD
Luhn check failsCCREJECT-IRC5180INVALID_OR_RESTRICTED_CARD, do not retry the same card
Insufficient fundsCCREJECT-IF5120INSUFFICIENT_FUNDS
Lost or stolenCCREJECT-LS9520LOST_OR_STOLEN, do not retry the same card
Card not validCCREJECT-IA1330INVALID_ACCOUNT
Generic bank declineCCREJECT-BANK_ERROR5100GENERIC_DECLINE
CVV check failsCCREJECT-CVV_F00N7CVV2_FAILURE_POSSIBLE_RETRY_WITH_CVV

Why does PayPal say COMPLETED when the card was declined?

Because the order and the capture are two different objects. PayPal's card testing page shows a sample where the order status is COMPLETED, but purchase_units[0].payments.captures[0].status is DECLINED and processor_response.response_code is 5400. The capture status reference defines DECLINED as "The funds could not be captured", and lists COMPLETED, PENDING, FAILED, PARTIALLY_REFUNDED and REFUNDED as the other values. Only COMPLETED means the money reached the seller.

There is a second trap on top of this. The capture endpoint defaults to Prefer: return=minimal, which returns only the order id, status and links. PayPal's v1 to v2 upgrade guide (updated 29 October 2026) warns that you need Prefer: return=representation to get the capture details. With the default, the only status your code sees is the order's COMPLETED.

What does INSTRUMENT_DECLINED mean, and why does actions.restart() matter?

The second shape is a hard error. The Orders v2 error list describes INSTRUMENT_DECLINED as "The instrument presented was either declined by the processor or bank, or it can't be used for this payment." It comes back as an UNPROCESSABLE_ENTITY error, which PayPal's API responses page maps to HTTP 422.

The funding failure guide says that when you call the Orders API from your own server, you must restart the payment yourself by calling actions.restart() in onApprove, which reopens PayPal so the buyer can pick a different funding source. Only actions.order.capture() in the browser does this automatically.

This is easy to break without noticing. In PayPal's own standard integration sample (last commit 25 March 2025), the browser code checks for INSTRUMENT_DECLINED correctly, but the Node server catches the SDK error and returns a generic HTTP 500. In @paypal/paypal-server-sdk 2.5.0, a 422 from capture is thrown as an ApiError, so the issue name never reaches the browser and actions.restart() is never called. Whatever server you use, pass the issue name through.

Decision flow after a PayPal capture: COMPLETED is paid, DECLINED inside a COMPLETED order is a card decline, PENDING waits for a webhook, and a 422 INSTRUMENT_DECLINED calls actions.restart()
Check the capture inside the order, not the order status, and restart only on INSTRUMENT_DECLINED.

How do I handle a declined capture on the server?

I call the REST API with fetch here so every header is visible. The capture asks for the full representation, sends a PayPal-Request-Id so a retry after a timeout does not capture twice (see idempotency), and only sends the mock header in the sandbox.

// paypal.js: capture a PayPal order and turn the response into one clear outcome.
import { randomUUID } from 'node:crypto';

export const PAYPAL_BASE = process.env.PAYPAL_API_BASE ?? 'https://api-m.sandbox.paypal.com';

// Card-testing page: "Try using another card. Do not retry the same card."
const DO_NOT_RETRY_SAME_CARD = new Set(['9500', '5180', '9520']);

export async function getAccessToken({ clientId, clientSecret, base = PAYPAL_BASE, fetchImpl = fetch }) {
  const res = await fetchImpl(`${base}/v1/oauth2/token`, {
    method: 'POST',
    headers: {
      Authorization: 'Basic ' + Buffer.from(`${clientId}:${clientSecret}`).toString('base64'),
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: 'grant_type=client_credentials',
  });
  if (!res.ok) throw new Error(`PayPal OAuth failed with HTTP ${res.status}`);
  return (await res.json()).access_token;
}

export async function captureOrder(orderId, {
  accessToken,
  requestId = randomUUID(), // reuse the same value when you retry after a timeout
  mockCode,                 // sandbox only, for example 'INSTRUMENT_DECLINED'
  base = PAYPAL_BASE,
  fetchImpl = fetch,
}) {
  const headers = {
    Authorization: `Bearer ${accessToken}`,
    'Content-Type': 'application/json',
    Prefer: 'return=representation', // the default (minimal) hides the capture status
    'PayPal-Request-Id': requestId,
  };
  if (mockCode) {
    if (!base.includes('sandbox')) throw new Error('PayPal-Mock-Response only works in the sandbox');
    headers['PayPal-Mock-Response'] = JSON.stringify({ mock_application_codes: mockCode });
  }
  const res = await fetchImpl(`${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/capture`, {
    method: 'POST',
    headers,
  });
  const body = await res.json().catch(() => ({}));
  return { httpStatus: res.status, body };
}

export function classifyCapture(httpStatus, body = {}) {
  if (httpStatus >= 400) {
    const issue = body.details?.[0]?.issue ?? body.name ?? 'UNKNOWN_ERROR';
    return {
      outcome: issue === 'INSTRUMENT_DECLINED' ? 'restart' : 'failed',
      issue,
      debugId: body.debug_id,
    };
  }
  const capture = body.purchase_units?.[0]?.payments?.captures?.[0];
  if (!capture) {
    // Order status alone is not proof of payment. Fetch the order or send Prefer: return=representation.
    return { outcome: 'unknown', issue: 'NO_CAPTURE_IN_RESPONSE', orderStatus: body.status };
  }
  const responseCode = capture.processor_response?.response_code;
  switch (capture.status) {
    case 'COMPLETED':
      return { outcome: 'paid', captureId: capture.id, amount: capture.amount };
    case 'PENDING':
      return { outcome: 'pending', captureId: capture.id, reason: capture.status_details?.reason };
    case 'DECLINED':
    case 'FAILED':
      return {
        outcome: 'declined',
        captureId: capture.id,
        responseCode,
        tryAnotherCard: DO_NOT_RETRY_SAME_CARD.has(responseCode),
      };
    default:
      return { outcome: 'unknown', issue: `CAPTURE_STATUS_${capture.status}`, captureId: capture.id };
  }
}

The Express route turns each outcome into a small, stable response for the browser:

// server.js: Express 5 route the PayPal buttons call from onApprove.
import express from 'express';
import { getAccessToken, captureOrder, classifyCapture } from './paypal.js';

export function createApp({ fetchImpl = fetch } = {}) {
  const app = express();
  app.use(express.json());

  app.post('/api/orders/:orderId/capture', async (req, res) => {
    try {
      const accessToken = await getAccessToken({
        clientId: process.env.PAYPAL_CLIENT_ID,
        clientSecret: process.env.PAYPAL_CLIENT_SECRET,
        fetchImpl,
      });
      const { httpStatus, body } = await captureOrder(req.params.orderId, {
        accessToken,
        mockCode: process.env.PAYPAL_MOCK_CAPTURE, // leave unset outside tests
        fetchImpl,
      });
      const result = classifyCapture(httpStatus, body);
      console.log('paypal capture', req.params.orderId, httpStatus, JSON.stringify(result));

      switch (result.outcome) {
        case 'paid':
          // Mark the order paid here (and only here), keyed by result.captureId.
          return res.json({ status: 'PAID', captureId: result.captureId });
        case 'pending':
          return res.status(202).json({ status: 'PENDING', reason: result.reason });
        case 'restart':
          return res.status(422).json({ error: 'INSTRUMENT_DECLINED', debugId: result.debugId });
        case 'declined':
          return res.status(402).json({
            error: 'CARD_DECLINED',
            responseCode: result.responseCode,
            tryAnotherCard: result.tryAnotherCard,
          });
        default:
          return res.status(502).json({ error: result.issue, debugId: result.debugId });
      }
    } catch (err) {
      console.error('paypal capture failed', err);
      return res.status(500).json({ error: 'CAPTURE_REQUEST_FAILED' });
    }
  });
  return app;
}

if (import.meta.url === `file://${process.argv[1]}`) {
  createApp().listen(process.env.PORT ?? 8080);
}

How do I handle INSTRUMENT_DECLINED in onApprove?

On the browser side, onApprove only has to read that response. actions.restart() handles the PayPal funding failure, and a card decline gets a message that matches the code:

// client.js: PayPal JavaScript SDK v5 buttons. Only onApprove is shown in full.
function showMessage(text) {
  document.querySelector('#result-message').textContent = text;
}

async function onApprove(data, actions) {
  const res = await fetch(`/api/orders/${data.orderID}/capture`, { method: 'POST' });
  const result = await res.json();

  if (result.error === 'INSTRUMENT_DECLINED') {
    // The PayPal funding source failed: reopen PayPal so the buyer can pick another one.
    return actions.restart();
  }
  if (result.error === 'CARD_DECLINED') {
    showMessage(result.tryAnotherCard
      ? 'Your bank declined this card. Please use a different card.'
      : 'Your bank declined the payment. Check the card details or try another card.');
    return;
  }
  if (result.status === 'PENDING') {
    showMessage('Your payment is being reviewed. We will email you when it clears.');
    return;
  }
  if (result.status === 'PAID') {
    return actions.redirect(`${window.location.origin}/thank-you`);
  }
  showMessage('Sorry, the payment could not be completed. Please try again.');
}

window.paypal.Buttons({
  createOrder: async () => {
    const res = await fetch('/api/orders', { method: 'POST' });
    return (await res.json()).id;
  },
  onApprove,
}).render('#paypal-button-container');

Keep the buyer message generic. The response code is for your logs and support team, not for the checkout page.

How do I force INSTRUMENT_DECLINED with PayPal-Mock-Response?

PayPal's negative testing feature (marked beta) lets you force API errors in the sandbox only. The request headers page says you add a PayPal-Mock-Response header with a mock_application_codes value equal to the error code, and lists "Capture payment for order" among the supported Orders v2 calls. Approve a sandbox order in the popup first, then:

#!/usr/bin/env bash
# Force INSTRUMENT_DECLINED on a sandbox capture. Needs an approved sandbox ORDER_ID.
set -euo pipefail
BASE="${PAYPAL_API_BASE:-https://api-m.sandbox.paypal.com}"

ACCESS_TOKEN=$(curl -s "$BASE/v1/oauth2/token" \
  -u "$PAYPAL_CLIENT_ID:$PAYPAL_CLIENT_SECRET" \
  -d grant_type=client_credentials | jq -r .access_token)

curl -s -X POST "$BASE/v2/checkout/orders/$ORDER_ID/capture" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Prefer: return=representation" \
  -H 'PayPal-Mock-Response: {"mock_application_codes": "INSTRUMENT_DECLINED"}'

To run the whole browser flow with the forced error, start the server with PAYPAL_MOCK_CAPTURE=INSTRUMENT_DECLINED and approve a normal sandbox payment. You should see the PayPal popup open again instead of an error page.

How do I verify the fix?

  1. Pay with 4012888888881881 and a normal name. The server logs outcome: "paid" and the browser reaches the thank-you page.
  2. Pay again with the name CCREJECT-EC. The log shows outcome: "declined" with responseCode: "5400", the order is not marked paid, and the buyer sees the decline message.
  3. Repeat with CCREJECT-SF. The message asks for a different card because 9500 should not be retried.
  4. Start the server with PAYPAL_MOCK_CAPTURE=INSTRUMENT_DECLINED and pay with a sandbox PayPal account. The popup reopens through actions.restart().
  5. Log in to the sandbox business account and check that only the first payment appears as received.

On my side, I ran 14 unit and route tests with node --test, using PayPal's own declined sample response as a fixture, plus a mocked 422 INSTRUMENT_DECLINED and a minimal response that only says COMPLETED. All passed, and the curl script sent the exact mock header to a local stand-in server. A live sandbox run still needs your sandbox client ID and secret.

How do I stop declined payments slipping through again?

  • Send Prefer: return=representation on every capture.
  • Decide "paid" from captures[0].status === 'COMPLETED', never from the order status.
  • Store processor_response.response_code and debug_id with the order for support.
  • Pass INSTRUMENT_DECLINED from server to browser and call actions.restart().
  • Send a PayPal-Request-Id and reuse it when you retry a timed-out capture.
  • Subscribe to PAYMENT.CAPTURE.COMPLETED, PAYMENT.CAPTURE.PENDING and PAYMENT.CAPTURE.DECLINED from the webhook event list so pending payments get settled later.
  • Add the CCREJECT triggers and the mock header test to your release checklist.

The same habits apply to other gateways. My Stripe 3D Secure test cards guide covers payments stuck waiting for authentication, and the PayHere sandbox test cards post covers decline testing for Sri Lankan checkouts. If you are a Sri Lankan freelancer setting up PayPal to get paid rather than to charge customers, read PayPal in Sri Lanka for freelancers instead.

Frequently asked questions

What are the PayPal sandbox test card numbers?

PayPal's card testing page lists static numbers such as Visa 4012888888881881 and 4005519200000004, Mastercard 2223000048400011 and American Express 371449635398431. Use any future expiry date and a 3-digit CVV, or 4 digits for American Express.

How do I make a card decline in the PayPal sandbox?

Pay with a Visa test card such as 4012888888881881 and type a rejection trigger like CCREJECT-IF or CCREJECT-EC in the first name or name on card field. The triggers are case-sensitive and each one returns a different processor response code.

Why is my PayPal order COMPLETED when the card was declined?

The order and the capture are separate objects, and PayPal's own sample shows an order with status COMPLETED whose capture status is DECLINED. Decide whether you were paid from purchase_units[0].payments.captures[0].status, not from the order status.

What does INSTRUMENT_DECLINED mean in PayPal?

It is an Orders API error meaning the processor or bank declined the payment method, or it cannot be used for this payment. When you capture on your server, return the error to the browser and call actions.restart() so the buyer can choose another funding source.

What is the PayPal-Mock-Response header?

It is a sandbox-only negative testing header that forces an API error. Send it as a JSON value with mock_application_codes set to an error code such as INSTRUMENT_DECLINED on a supported call like capture order.

Why does my PayPal capture response not include the capture status?

The capture endpoint defaults to Prefer: return=minimal, which returns only the order id, status and links. Send Prefer: return=representation to get purchase_units with the capture status and processor response.

What does PayPal processor response code 5400 mean?

5400 means EXPIRED_CARD. In the sandbox you can trigger it by entering CCREJECT-EC as the name on the card.

Sources

  1. Card testing (PayPal Developer, 2026-06-25)
  2. Handle funding failures (PayPal Developer, 2026-10-14)
  3. Negative testing (PayPal Developer, 2026-10-14)
  4. Negative testing: request headers (PayPal Developer, 2026-10-14)
  5. Orders v2 errors (PayPal Developer)
  6. Capture payment for order (Orders v2) (PayPal Developer)
  7. capture_status (Orders v2) (PayPal Developer)
  8. processor_response (Orders v2) (PayPal Developer)
  9. Card decline errors (PayPal Developer, 2026-10-14)
  10. Payments API v1 to v2 integration upgrade guide (PayPal Developer, 2026-10-29)
  11. API responses (PayPal Developer, 2026-06-07)
  12. Idempotency (PayPal Developer, 2026-08-11)
  13. Webhook event names (PayPal Developer, 2026-09-10)
  14. paypal-examples/docs-examples: standard-integration (PayPal on GitHub, 2025-03-25)
  15. @paypal/paypal-server-sdk 2.5.0 (npm)
  16. express 5.3.0 (npm)
SharePost on XLinkedIn

Comments

Share a question or note about this article.

Loading comments…