PayPal Checkout with Orders v2, verified webhooks and refunds

Accept PayPal (and cards via PayPal) with the Orders v2 API: OAuth client-credentials tokens, create and capture orders server-side, render PayPal buttons, verify webhooks with verify-webhook-signature, check order/capture status and issue refunds.

Provider
PayPal
Level
Intermediate
Stacks
Node.js (Express), Python (FastAPI), PHP, React
Code maturity
Sandbox-ready
Last verified
25 Nov 2026

Introduction

PayPal's current online-checkout API is Orders v2. An *order* describes what the buyer is paying for; the buyer approves it in a PayPal window (or with a card via PayPal), and your server then captures it to move the money.

This guide uses the REST API directly (no server SDK) so you can see every request:

  • get an OAuth 2.0 access token with your client ID and secret,
  • create an order and capture it from your server,
  • render PayPal buttons in the browser,
  • verify webhooks with POST /v1/notifications/verify-webhook-signature,
  • check status and refund a capture.

Tip: PayPal also publishes official server SDKs (the Standard Checkout page uses their ordersCreate / ordersCapture methods). The REST calls shown here are what those SDKs send.

What Orders v2 does

  • POST /v2/checkout/orders — create an order with intent: "CAPTURE" (take money immediately after approval) or "AUTHORIZE" (hold, capture later).
  • The buyer approves the order in the PayPal popup → order status APPROVED.
  • POST /v2/checkout/orders/{id}/capture — your server captures; the response contains purchase_units[0].payments.captures[0] with a capture id and status.
  • Webhooks such as PAYMENT.CAPTURE.COMPLETED tell you about the final state, including captures that were PENDING at first.

Order statuses in the spec: CREATED, SAVED, APPROVED, VOIDED, COMPLETED, PAYER_ACTION_REQUIRED. Capture statuses: COMPLETED, DECLINED, PARTIALLY_REFUNDED, PENDING, REFUNDED, FAILED.

Countries and availability

PayPal operates in many countries, but receiving payments, currencies and withdrawal options differ by country, and some countries only allow sending. Check PayPal's country pages and the currency codes reference for the country your business account is registered in before you build.

Warning: Merchant eligibility and fees are country-specific and change; this guide doesn't list them. Confirm on PayPal's site for your country.

Payment methods

With the JavaScript SDK buttons, buyers can pay with a PayPal balance or linked funding sources, and — where eligible — Pay Later, Venmo (US) and debit/credit cards through PayPal's guest checkout. Which buttons appear depends on the buyer's country, currency and your account. Advanced card fields (hosted card fields on your own page) are a separate integration not covered here.

When to use it

  • Your buyers already trust or prefer PayPal (common for cross-border e-commerce and digital goods).
  • You want a wallet + guest card option without handling card data.
  • You need a server-controlled order/capture flow with clear status codes.

When not to use it

  • Your customers mainly pay with local methods PayPal doesn't offer in your market (mobile money, local bank transfer schemes).
  • You need subscription billing → PayPal has a separate Subscriptions API (not covered here).
  • Your business country can't receive PayPal payments.

Example scenarios

  • International digital shop: buyers abroad pay with PayPal; your server captures and the webhook delivers the licence key.
  • Freelance invoice page: a client pays a fixed invoice amount; the order carries your invoice_id so refunds and reconciliation are easy.
  • Pending captures: a capture returns PENDING (e.g. under review); you hold the order and wait for PAYMENT.CAPTURE.COMPLETED or PAYMENT.CAPTURE.DENIED.

Registration

  • Sign in to the PayPal Developer Dashboard with a PayPal account.
  • Under Apps & Credentials, create a REST app in *Sandbox*. This gives a client ID and secret.
  • For live payments you need a PayPal Business account; create a separate app in *Live*.

Sandbox

  • Sandbox API base URL: https://api-m.sandbox.paypal.com; live: https://api-m.paypal.com.
  • The dashboard creates sandbox business and personal (buyer) accounts; log in to the popup with the personal account to approve test payments.
  • The dashboard also has a webhooks simulator that sends mock events to a URL.

Credentials

  • Client ID — identifies your app. It's public: it goes in the JS SDK script URL / React provider.
  • Client secret — server only; used to obtain access tokens.
  • Webhook ID — returned when you subscribe a webhook URL in your app; required for verification.

Security: The client secret never goes into frontend code or mobile apps. Sandbox and live use different credentials — keep them in separate environment configs.

Environment configuration

Placeholders only — load real values from your secret manager or .env that is not committed:

.env.example

PAYPAL_BASE_URL=https://api-m.sandbox.paypal.com
PAYPAL_CLIENT_ID=replace_with_sandbox_client_id
PAYPAL_CLIENT_SECRET=replace_with_sandbox_secret
# From the webhook you registered for this app (sandbox and live differ)
PAYPAL_WEBHOOK_ID=replace_with_webhook_id

Authentication (OAuth 2.0 client credentials)

POST /v1/oauth2/token with HTTP Basic auth (client_id:client_secret), Content-Type: application/x-www-form-urlencoded and body grant_type=client_credentials. The response's access_token is used as Authorization: Bearer ...; expires_in gives its lifetime in seconds. Cache the token and refresh shortly before expiry — don't fetch a new one per request.

paypal.js — cached token + API helper (Node 18+ fetch) · Node.js (Express)

const BASE = process.env.PAYPAL_BASE_URL;
let cached = { token: null, expiresAt: 0 };

export async function getAccessToken() {
  if (cached.token && Date.now() < cached.expiresAt - 60_000) return cached.token;
  const basic = Buffer.from(`${process.env.PAYPAL_CLIENT_ID}:${process.env.PAYPAL_CLIENT_SECRET}`).toString("base64");
  const res = await fetch(`${BASE}/v1/oauth2/token`, {
    method: "POST",
    headers: { Authorization: `Basic ${basic}`, "Content-Type": "application/x-www-form-urlencoded" },
    body: "grant_type=client_credentials",
  });
  if (!res.ok) throw new Error(`PayPal auth failed: ${res.status}`);
  const data = await res.json();
  cached = { token: data.access_token, expiresAt: Date.now() + data.expires_in * 1000 };
  return cached.token;
}

export async function paypal(path, { method = "GET", body, requestId, rawBody } = {}) {
  const headers = { Authorization: `Bearer ${await getAccessToken()}`, "Content-Type": "application/json" };
  if (requestId) headers["PayPal-Request-Id"] = requestId; // idempotency
  const res = await fetch(`${BASE}${path}`, { method, headers, body: rawBody ?? (body && JSON.stringify(body)) });
  const data = res.status === 204 ? null : await res.json();
  if (!res.ok) {
    const err = new Error(data?.name || `PayPal ${res.status}`);
    Object.assign(err, { status: res.status, details: data?.details, debugId: data?.debug_id });
    throw err;
  }
  return data;
}

paypal_client.py — cached token (httpx) · Python (FastAPI)

import os, time
import httpx

BASE = os.environ["PAYPAL_BASE_URL"]
_cache = {"token": None, "exp": 0.0}

async def get_access_token() -> str:
    if _cache["token"] and time.time() < _cache["exp"] - 60:
        return _cache["token"]
    async with httpx.AsyncClient(timeout=15) as c:
        r = await c.post(
            f"{BASE}/v1/oauth2/token",
            auth=(os.environ["PAYPAL_CLIENT_ID"], os.environ["PAYPAL_CLIENT_SECRET"]),
            data={"grant_type": "client_credentials"},
        )
    r.raise_for_status()
    data = r.json()
    _cache.update(token=data["access_token"], exp=time.time() + data["expires_in"])
    return _cache["token"]

async def paypal(method: str, path: str, json=None, content=None, request_id=None) -> dict:
    headers = {"Authorization": f"Bearer {await get_access_token()}", "Content-Type": "application/json"}
    if request_id:
        headers["PayPal-Request-Id"] = request_id
    async with httpx.AsyncClient(timeout=30) as c:
        r = await c.request(method, f"{BASE}{path}", headers=headers, json=json, content=content)
    if r.status_code >= 400:
        raise RuntimeError(f"PayPal {r.status_code}: {r.text[:300]}")
    return r.json() if r.content else {}

Backend: create and capture orders

Two endpoints on your server: create (called when the buyer clicks the button) and capture (called after approval). The server sets the amount from your database.

Amounts in Orders v2 use the Money object: { currency_code: "USD", value: "20.00" }. value is a decimal string with the number of decimals the currency requires (e.g. no decimals for JPY) — not minor units. Store minor units internally and format at the edge.

Send a PayPal-Request-Id header on POSTs so a retried request doesn't create or capture twice.

routes.js — create + capture (Express) · Node.js (Express)

import express from "express";
import { paypal } from "./paypal.js";

export const router = express.Router();
const toValue = (minor, decimals = 2) => (minor / 10 ** decimals).toFixed(decimals);

router.post("/api/paypal/orders", express.json(), async (req, res) => {
  const order = await db.orders.createPending({ userId: req.user.id, sku: req.body.sku }); // price from DB
  try {
    const created = await paypal("/v2/checkout/orders", {
      method: "POST",
      requestId: `create-${order.id}`,
      body: {
        intent: "CAPTURE",
        purchase_units: [{
          reference_id: order.id,
          custom_id: order.id,
          amount: { currency_code: order.currency, value: toValue(order.amountMinor) },
        }],
      },
    });
    await db.orders.update(order.id, { paypalOrderId: created.id });
    res.json({ id: created.id });
  } catch (e) {
    console.error("paypal create failed", e.status, e.debugId);
    res.status(502).json({ error: "Could not create PayPal order" });
  }
});

router.post("/api/paypal/orders/:id/capture", async (req, res) => {
  const order = await db.orders.findByPaypalOrderId(req.params.id);
  if (!order || order.userId !== req.user.id) return res.sendStatus(404);
  try {
    const result = await paypal(`/v2/checkout/orders/${encodeURIComponent(req.params.id)}/capture`, {
      method: "POST",
      requestId: `capture-${order.id}`,
    });
    const capture = result.purchase_units?.[0]?.payments?.captures?.[0];
    await recordCapture(order, capture); // idempotent; see Confirmation
    res.json({ status: result.status, captureStatus: capture?.status });
  } catch (e) {
    const issue = e.details?.[0]?.issue;
    if (issue === "INSTRUMENT_DECLINED") return res.status(422).json({ restart: true });
    if (issue === "ORDER_ALREADY_CAPTURED") return res.json({ status: "COMPLETED" });
    console.error("paypal capture failed", e.status, issue, e.debugId);
    res.status(502).json({ error: "Capture failed" });
  }
});

orders.py — create + capture (FastAPI) · Python (FastAPI)

from fastapi import APIRouter, HTTPException
from .paypal_client import paypal

router = APIRouter()

def to_value(minor: int, decimals: int = 2) -> str:
    return f"{minor / 10 ** decimals:.{decimals}f}"

@router.post("/api/paypal/orders")
async def create_order(body: dict):
    order = orders.create_pending(sku=body["sku"])  # amount comes from your DB
    created = await paypal("POST", "/v2/checkout/orders", request_id=f"create-{order.id}", json={
        "intent": "CAPTURE",
        "purchase_units": [{
            "reference_id": order.id,
            "custom_id": order.id,
            "amount": {"currency_code": order.currency, "value": to_value(order.amount_minor)},
        }],
    })
    orders.update(order.id, paypal_order_id=created["id"])
    return {"id": created["id"]}

@router.post("/api/paypal/orders/{paypal_order_id}/capture")
async def capture_order(paypal_order_id: str):
    order = orders.find_by_paypal_order_id(paypal_order_id)
    if not order:
        raise HTTPException(404)
    result = await paypal("POST", f"/v2/checkout/orders/{paypal_order_id}/capture",
                          request_id=f"capture-{order.id}")
    capture = result["purchase_units"][0]["payments"]["captures"][0]
    record_capture(order, capture)  # idempotent
    return {"status": result["status"], "captureStatus": capture["status"]}

paypal.php — token, create, capture (plain PHP + cURL) · PHP

<?php
function paypal_token(): string {
    static $tok = null, $exp = 0;
    if ($tok && time() < $exp - 60) return $tok;
    $ch = curl_init(getenv('PAYPAL_BASE_URL') . '/v1/oauth2/token');
    curl_setopt_array($ch, [
        CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERPWD => getenv('PAYPAL_CLIENT_ID') . ':' . getenv('PAYPAL_CLIENT_SECRET'),
        CURLOPT_POSTFIELDS => 'grant_type=client_credentials',
        CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
    ]);
    $data = json_decode(curl_exec($ch), true);
    if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) throw new RuntimeException('PayPal auth failed');
    [$tok, $exp] = [$data['access_token'], time() + (int) $data['expires_in']];
    return $tok;
}

function paypal_api(string $method, string $path, ?string $body = null, ?string $requestId = null): array {
    $headers = ['Authorization: Bearer ' . paypal_token(), 'Content-Type: application/json'];
    if ($requestId) $headers[] = 'PayPal-Request-Id: ' . $requestId;
    $ch = curl_init(getenv('PAYPAL_BASE_URL') . $path);
    curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers, CURLOPT_POSTFIELDS => $body ?? '']);
    $raw = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $data = $raw ? json_decode($raw, true) : [];
    if ($code >= 400) throw new RuntimeException('PayPal ' . $code . ' ' . ($data['debug_id'] ?? ''));
    return $data;
}

// create-order.php (amount from your DB, never from $_POST)
// $order = find_pending_order(...);
// $created = paypal_api('POST', '/v2/checkout/orders', json_encode([
//     'intent' => 'CAPTURE',
//     'purchase_units' => [[ 'custom_id' => $order['id'],
//         'amount' => ['currency_code' => 'USD', 'value' => number_format($order['amount_minor'] / 100, 2, '.', '')] ]],
// ]), 'create-' . $order['id']);
// capture: paypal_api('POST', '/v2/checkout/orders/' . rawurlencode($id) . '/capture', null, 'capture-' . $order['id']);

Frontend: PayPal buttons

The buttons call your server for both steps: createOrder returns the PayPal order ID from your create endpoint, and onApprove asks your server to capture.

React: the official @paypal/react-paypal-js package now documents the v6 SDK components under the @paypal/react-paypal-js/sdk-v6 entry point (PayPalProvider + PayPalOneTimePaymentButton). In v6, environment ("sandbox" / "production") is a required prop — the client ID no longer selects the environment. The older v5 components (PayPalScriptProvider, PayPalButtons) are documented in a separate README in the same repo.

Plain HTML (v5): the Standard Checkout page still loads https://www.paypal.com/sdk/js?client-id=...&components=buttons and renders paypal.Buttons({...}).render('#paypal-button-container'); in v5 the approval callback receives data.orderID.

PayPalCheckout.jsx — v6 components (react-paypal-js) · React

import { PayPalProvider, PayPalOneTimePaymentButton } from "@paypal/react-paypal-js/sdk-v6";

// The client ID is public; the environment must match the credentials you use server-side.
const CLIENT_ID = process.env.REACT_APP_PAYPAL_CLIENT_ID;

export default function PayPalCheckout({ sku, onPaid }) {
  return (
    <PayPalProvider
      clientId={CLIENT_ID}
      environment="sandbox"
      components={["paypal-payments"]}
      pageType="checkout"
    >
      <PayPalOneTimePaymentButton
        createOrder={async () => {
          const res = await fetch("/api/paypal/orders", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ sku }), // identifier only
          });
          if (!res.ok) throw new Error("Could not create order");
          const { id } = await res.json();
          return { orderId: id };
        }}
        onApprove={async ({ orderId }) => {
          // Must return/await the capture so the SDK waits for it.
          const res = await fetch(`/api/paypal/orders/${orderId}/capture`, { method: "POST" });
          if (!res.ok) throw new Error(`Capture failed: ${res.status}`);
          const data = await res.json();
          onPaid?.(data); // UI only — fulfilment happens server-side
        }}
      />
    </PayPalProvider>
  );
}

Warning: The v6 React components are newer than most tutorials online. The props above come from the official README on 2026-11-25; check it again if your package version differs (the README is for the 10.x line).

Initiating the payment

Initiation is the create-order call. Useful purchase_units fields:

  • reference_id — your identifier for the purchase unit (needed when there are several).
  • custom_id — your order ID; it's echoed back in captures and webhook resources, which makes webhook-to-order matching easy.
  • invoice_id — must be unique per payment in your account if you use it.
  • amount.breakdown + items — optional itemisation; totals must add up or the API returns a validation error.

curl — create an order (sandbox)

curl -X POST "$PAYPAL_BASE_URL/v2/checkout/orders" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -H "PayPal-Request-Id: create-order_123" \
  -d '{"intent":"CAPTURE","purchase_units":[{"custom_id":"order_123","amount":{"currency_code":"USD","value":"20.00"}}]}'

Confirmation

The capture response is authoritative for that request, but read it carefully:

  • Order status: COMPLETED and capture status: COMPLETED → paid. Check that the captured amount.value and currency_code match your order and that custom_id is your order ID.
  • Capture status: PENDING → money not yet available (status_details.reason explains why, e.g. PENDING_REVIEW). Don't deliver yet; wait for PAYMENT.CAPTURE.COMPLETED or PAYMENT.CAPTURE.DENIED.
  • DECLINED / FAILED → not paid.

Write recordCapture() so it is idempotent (unique index on capture ID) because both the capture response and the webhook will report the same capture.

recordCapture — idempotent, amount-checked · Node.js (Express)

export async function recordCapture(order, capture) {
  if (!capture) return;
  const expected = (order.amountMinor / 100).toFixed(2);
  if (capture.amount?.value !== expected || capture.amount?.currency_code !== order.currency) {
    await alertStaff("PayPal amount mismatch", { orderId: order.id, captureId: capture.id });
    return;
  }
  // Unique index on paypal_capture_id: a second call updates status instead of duplicating.
  await db.payments.upsert({ paypalCaptureId: capture.id }, { orderId: order.id, status: capture.status });
  if (capture.status === "COMPLETED") {
    const first = await db.orders.markPaidOnce(order.id); // UPDATE ... WHERE status <> 'paid'
    if (first) await deliver(order);
  }
}

Webhooks and signature verification

Subscribe your URL to events in your app settings (e.g. PAYMENT.CAPTURE.COMPLETED, PAYMENT.CAPTURE.DENIED, PAYMENT.CAPTURE.PENDING, PAYMENT.CAPTURE.REFUNDED, PAYMENT.CAPTURE.REVERSED, CHECKOUT.ORDER.APPROVED). Each delivery carries transmission headers: PAYPAL-TRANSMISSION-ID, PAYPAL-TRANSMISSION-TIME, PAYPAL-TRANSMISSION-SIG, PAYPAL-CERT-URL and PAYPAL-AUTH-ALGO.

Postback verification: call POST /v1/notifications/verify-webhook-signature with auth_algo, cert_url, transmission_id, transmission_sig, transmission_time, your webhook_id and the webhook_event. The response is { "verification_status": "SUCCESS" | "FAILURE" }. PayPal's guide stresses that the event must be passed back exactly as received — so the examples splice the raw body into the request instead of re-serialising a parsed object.

Self-verification (no extra API call): build transmissionId|transmissionTime|webhookId|crc32(rawBody) (CRC32 in decimal), download and cache the certificate from the cert URL, and verify the SHA256 signature. Mock events from the webhooks simulator cannot be verified by postback; with self-verification they use the literal webhook ID WEBHOOK_ID.

webhook.js — postback verification + idempotent processing · Node.js (Express)

import express from "express";
import { paypal } from "./paypal.js";

export const webhookRouter = express.Router();

webhookRouter.post("/webhooks/paypal", express.raw({ type: "application/json" }), async (req, res) => {
  const raw = req.body.toString("utf8");
  const h = (name) => req.get(name) || "";
  // Splice the raw event in so it reaches PayPal byte-for-byte.
  const verifyBody =
    `{"auth_algo":${JSON.stringify(h("paypal-auth-algo"))},` +
    `"cert_url":${JSON.stringify(h("paypal-cert-url"))},` +
    `"transmission_id":${JSON.stringify(h("paypal-transmission-id"))},` +
    `"transmission_sig":${JSON.stringify(h("paypal-transmission-sig"))},` +
    `"transmission_time":${JSON.stringify(h("paypal-transmission-time"))},` +
    `"webhook_id":${JSON.stringify(process.env.PAYPAL_WEBHOOK_ID)},` +
    `"webhook_event":${raw}}`;

  let verified = false;
  try {
    const r = await paypal("/v1/notifications/verify-webhook-signature", { method: "POST", rawBody: verifyBody });
    verified = r.verification_status === "SUCCESS";
  } catch (e) {
    return res.sendStatus(500); // PayPal will retry; don't treat as verified
  }
  if (!verified) return res.sendStatus(400);

  const event = JSON.parse(raw);
  if (!(await db.webhookEvents.tryInsert(`paypal:${event.id}`))) return res.sendStatus(200);

  const resource = event.resource || {};
  if (event.event_type.startsWith("PAYMENT.CAPTURE.")) {
    const order = await db.orders.get(resource.custom_id);
    // Re-read the capture so we act on current state, not on event order.
    if (order) await recordCapture(order, await paypal(`/v2/payments/captures/${resource.id}`));
  }
  res.sendStatus(200);
});

webhook.py — postback verification (FastAPI) · Python (FastAPI)

import json, os
from fastapi import APIRouter, Request, Response
from .paypal_client import paypal

router = APIRouter()

@router.post("/webhooks/paypal")
async def paypal_webhook(request: Request):
    raw = (await request.body()).decode("utf-8")
    h = request.headers
    meta = {
        "auth_algo": h.get("paypal-auth-algo", ""),
        "cert_url": h.get("paypal-cert-url", ""),
        "transmission_id": h.get("paypal-transmission-id", ""),
        "transmission_sig": h.get("paypal-transmission-sig", ""),
        "transmission_time": h.get("paypal-transmission-time", ""),
        "webhook_id": os.environ["PAYPAL_WEBHOOK_ID"],
    }
    # json.dumps(meta)[:-1] drops the closing brace so the raw event can be appended unchanged.
    body = json.dumps(meta)[:-1] + ',"webhook_event":' + raw + "}"
    try:
        result = await paypal("POST", "/v1/notifications/verify-webhook-signature", content=body)
    except RuntimeError:
        return Response(status_code=500)
    if result.get("verification_status") != "SUCCESS":
        return Response(status_code=400)

    event = json.loads(raw)
    if not webhook_events.try_insert(f"paypal:{event['id']}"):
        return Response(status_code=200)
    if event["event_type"].startswith("PAYMENT.CAPTURE."):
        capture = await paypal("GET", f"/v2/payments/captures/{event['resource']['id']}")
        order = orders.get(capture.get("custom_id"))
        if order:
            record_capture(order, capture)
    return Response(status_code=200)

webhook.php — postback verification (plain PHP) · PHP

<?php
require __DIR__ . '/paypal.php';

$raw = file_get_contents('php://input');
$h = fn(string $k) => $_SERVER['HTTP_' . strtoupper(str_replace('-', '_', $k))] ?? '';
$meta = [
    'auth_algo' => $h('paypal-auth-algo'),
    'cert_url' => $h('paypal-cert-url'),
    'transmission_id' => $h('paypal-transmission-id'),
    'transmission_sig' => $h('paypal-transmission-sig'),
    'transmission_time' => $h('paypal-transmission-time'),
    'webhook_id' => getenv('PAYPAL_WEBHOOK_ID'),
];
$body = substr(json_encode($meta, JSON_UNESCAPED_SLASHES), 0, -1) . ',"webhook_event":' . $raw . '}';

try {
    $result = paypal_api('POST', '/v1/notifications/verify-webhook-signature', $body);
} catch (Throwable $e) {
    http_response_code(500); exit;
}
if (($result['verification_status'] ?? '') !== 'SUCCESS') { http_response_code(400); exit; }

$event = json_decode($raw, true);
if (!claim_event('paypal:' . $event['id'])) { http_response_code(200); exit; } // unique key in your DB
if (str_starts_with($event['event_type'], 'PAYMENT.CAPTURE.')) {
    $capture = paypal_api('GET', '/v2/payments/captures/' . rawurlencode($event['resource']['id']));
    record_capture($capture); // idempotent, checks custom_id + amount
}
http_response_code(200);

Security: If you implement self-verification, only download certificates from PayPal-owned HTTPS hosts (check the cert URL's hostname) and cache them. Never skip verification because a request "looks" like PayPal's.

Tip: Use the webhook only as a trigger: re-read the capture or order from the API before changing state. Events can arrive out of order or more than once.

Checking status

  • GET /v2/checkout/orders/{id} → order status (CREATED, SAVED, APPROVED, VOIDED, COMPLETED, PAYER_ACTION_REQUIRED).
  • GET /v2/payments/captures/{capture_id} → capture status (COMPLETED, DECLINED, PARTIALLY_REFUNDED, PENDING, REFUNDED, FAILED).
  • GET /v2/payments/refunds/{refund_id} → refund status.

Run a reconciliation job for orders stuck in APPROVED (buyer approved but your capture call failed) — capture them or let them expire, but don't leave them ambiguous.

Refunds

POST /v2/payments/captures/{capture_id}/refund. An empty body refunds the full remaining amount; for a partial refund send amount: { value, currency_code }. Optional fields include note_to_payer, invoice_id and custom_id. Refund statuses: CANCELLED, FAILED, PENDING, COMPLETED. Always send a PayPal-Request-Id tied to your refund record.

Refund a capture (staff only) · Node.js (Express)

router.post("/admin/orders/:id/refund", requireStaff, express.json(), async (req, res) => {
  const order = await db.orders.get(req.params.id);
  const payment = order && (await db.payments.findCompleted(order.id));
  if (!payment) return res.status(409).json({ error: "Nothing to refund" });

  const minor = req.body.amountMinor == null ? null : Number.parseInt(req.body.amountMinor, 10);
  if (minor !== null && (!Number.isInteger(minor) || minor <= 0 || minor > order.amountMinor)) {
    return res.status(400).json({ error: "Invalid amount" });
  }
  const row = await db.refunds.create({ orderId: order.id, amountMinor: minor, by: req.user.id });
  const body = minor === null ? {} : { amount: { value: (minor / 100).toFixed(2), currency_code: order.currency } };
  const refund = await paypal(`/v2/payments/captures/${payment.paypalCaptureId}/refund`, {
    method: "POST",
    requestId: `refund-${row.id}`,
    body: { ...body, note_to_payer: "Refund for your order" },
  });
  await db.refunds.update(row.id, { paypalRefundId: refund.id, status: refund.status });
  res.json({ status: refund.status });
});

Error handling

Errors return JSON with name, message, debug_id and a details array of { issue, description }. Log debug_id — PayPal support asks for it.

  • INSTRUMENT_DECLINED on capture — the funding source failed (wrong billing address, limit exceeded, issuer declined). PayPal recommends restarting the payment so the buyer can choose another option (with v5 buttons, actions.restart() in onApprove).
  • ORDER_ALREADY_CAPTURED — a retry raced a successful capture; treat as success after reading the order.
  • ORDER_NOT_APPROVED — capture attempted before buyer approval.
  • 401 — expired/invalid token; refresh and retry once.
  • 422 UNPROCESSABLE_ENTITY — business-rule violations (amount/breakdown mismatch, invalid currency decimals, duplicate invoice_id).
  • 5xx / timeouts — retry with the same PayPal-Request-Id.

Tip: Issue names above are long-standing Orders v2 error issues; the authoritative list is in the Orders v2 reference's error section for each operation.

Going to production

  • Create a Live app, switch PAYPAL_BASE_URL to https://api-m.paypal.com, and use the live client ID in the frontend (and environment="production" for v6 React).
  • Register a live webhook — its webhook ID differs from sandbox.
  • Confirm your business account can receive the currencies you charge in.
  • Add monitoring for orders stuck in APPROVED and captures stuck in PENDING.

Security checklist

  • Client secret only on the server; token cached in memory, never logged.
  • Amount/currency set by the server; capture result cross-checked against your order (custom_id, amount, currency).
  • The capture endpoint checks that the PayPal order belongs to the logged-in user's order.
  • Webhooks verified (postback or self-verification) before parsing into business logic; duplicates ignored by event ID.
  • Idempotency with PayPal-Request-Id on create, capture and refund.
  • Refunds restricted to authorised staff and audited.

Testing

  • Approve payments in the sandbox popup with the generated personal sandbox account.
  • Use the dashboard's card testing tools / generated test cards for guest card checkout.
  • Use the webhooks simulator for event shapes — remember simulator events fail postback verification by design; test the postback path with real sandbox payments.
  • Automated tests: mock the PayPal HTTP calls and assert that a duplicate PAYMENT.CAPTURE.COMPLETED does not deliver twice, and that a mismatched amount is rejected.

Common mistakes

  • Re-serialising the event before postback verification (key order/whitespace changes) → FAILURE.
  • Using the sandbox webhook ID in live (or vice versa).
  • Sending minor units (2000) instead of a decimal string ("20.00"), or too many decimals for the currency.
  • Capturing from the browser or trusting onApprove alone; fulfilment must follow a server-side capture result or verified webhook.
  • Treating PENDING captures as paid.
  • Fetching a new OAuth token on every request (slow, and can hit rate limits).
  • No PayPal-Request-Id → a network retry creates a second order or refund.

Troubleshooting

  • verify-webhook-signature returns FAILURE — wrong webhook_id, event re-serialised, headers read from the wrong place behind a proxy, or a simulator event.
  • invalid_client on token request — sandbox credentials against the live URL or vice versa; check PAYPAL_BASE_URL.
  • Buttons don't render — client ID/environment mismatch, currency not supported for the buyer, or a Content-Security-Policy blocking PayPal's script domains.
  • UNPROCESSABLE_ENTITY on create — breakdown totals don't add up, or invoice_id was used before.
  • Webhooks never arrive — URL not publicly reachable over HTTPS, or the event type isn't subscribed for this app.

Further reading

Official documentation

Checked on 2026-11-25. Endpoint paths, headers and status enums were read from PayPal's published OpenAPI specs; re-check before going live:

Official documentation

Sources

More payment guides