跳到主要内容

Accept a card payment

  • Audience. Developers sending a first payment through the Stripe API.
  • Prerequisites. A Stripe account in test mode, a secret key in the environment, and Node.js 18 or later.
  • Goal. Collect a card payment, read its status, and fulfill the order only after the server confirms the charge.

By the end, you'll have a server endpoint that creates a PaymentIntent and a client that confirms it. Every result comes from test mode, so the flow costs nothing to run.

Request flow​

A card payment splits across your server, your client, and Stripe. The server stores the secret key. The client collects card details and confirms the intent. Stripe reports the outcome twice: once to the client, and once to a webhook.

Each stage runs in one place, and the key type follows the location.

StageRuns onCredential
Create the PaymentIntentYour serverSecret key
Collect card detailsClientPublishable key
Confirm the paymentClientclient_secret
Report the outcomeStripeWebhook signature

Handle payment webhooks covers the last stage. This page stops at a verified status.

1. Create the PaymentIntent​

Create one intent per order on the server. The response includes a client_secret, which the client uses to confirm the payment.

server.js
import express from "express";

const app = express();
app.use(express.json());

app.post("/create-payment-intent", async (req, res) => {
const orderId = req.body.orderId;

if (!orderId) {
return res.status(400).json({ error: "orderId is required" });
}

const params = new URLSearchParams({
amount: "2120",
currency: "usd",
"automatic_payment_methods[enabled]": "true",
"metadata[order_id]": orderId,
});

const response = await fetch("https://api.stripe.com/v1/payment_intents", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
"Content-Type": "application/x-www-form-urlencoded",
"Idempotency-Key": `order-${orderId}`,
},
body: params,
});

if (!response.ok) {
const failure = await response.json();
return res.status(response.status).json({ error: failure.error.message });
}

const intent = await response.json();
res.json({ clientSecret: intent.client_secret });
});

app.listen(4242, () => console.log("Listening on port 4242"));
  • amount uses the smallest currency unit. 2120 charges $21.20, not $2,120.
  • Idempotency-Key reuses the order ID. A retried request returns the original intent instead of creating a second one.
  • metadata[order_id] links the intent to your order. The webhook handler reads it back without a database lookup.
注意

The client_secret belongs in the browser for one order. Don't log it, and don't reuse it across customers.

Confirm the endpoint answers before you write any client code.

curl -X POST http://localhost:4242/create-payment-intent \
-H "Content-Type: application/json" \
-d '{"orderId":"ord_8842"}'

The response includes a clientSecret value that starts with pi_ and contains _secret_.

2. Confirm the payment in the client​

Load Stripe.js and confirm the intent with the customer's card. Stripe handles card entry, so the card number never touches your server.

checkout.html
<script src="https://js.stripe.com/v3/"></script>
<script>
const stripe = Stripe("pk_test_REPLACE_WITH_YOUR_KEY");

async function pay(cardElement) {
const response = await fetch("/create-payment-intent", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ orderId: "ord_8842" }),
});

const { clientSecret } = await response.json();

const result = await stripe.confirmCardPayment(clientSecret, {
payment_method: { card: cardElement },
});

if (result.error) {
showDecline(result.error.message);
return;
}

if (result.paymentIntent.status === "succeeded") {
showConfirmation();
} else {
showPending();
}
}
</script>

The status field drives the branch. A succeeded status means the issuer approved the charge. A requires_action status means the customer still needs to complete a challenge, and Stripe.js opens it during confirmCardPayment.

3. Verify the status on the server​

The client reports the result, but a browser can lie. Anyone can open developer tools and send a fake status. Read the intent from Stripe before you send goods.

server.js
app.get("/orders/:orderId/status", async (req, res) => {
const intentId = await lookupIntentId(req.params.orderId);

const response = await fetch(
`https://api.stripe.com/v1/payment_intents/${intentId}`,
{ headers: { Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}` } }
);

const intent = await response.json();

res.json({
fulfilled: intent.status === "succeeded",
status: intent.status,
amountReceived: intent.amount_received,
});
});

Compare amount_received with amount as well. A partial capture leaves amount_received below amount. The difference shows how much to refund or release.

提示

Cache the result for a few seconds per order. A status poll on a fast checkout page can otherwise hit the API once per second.

4. Fulfill only on a confirmed status​

The payment_intent.succeeded webhook gives you a safer fulfillment trigger than the browser. It arrives once, even when the customer closes the tab, and it includes a verifiable signature.

fulfillment.js
async function handleSucceeded(intent) {
const orderId = intent.metadata.order_id;

if (!orderId) {
console.warn("No order_id on intent", intent.id);
return;
}

if (intent.amount_received < intent.amount) {
console.warn("Underpaid intent", intent.id);
return;
}

await markOrderPaid(orderId, intent.id);
}

The order ID comes from the metadata you set in step 1. That field removes the need to search for the intent later.

Handle the decline path​

A declined card leaves the intent in requires_payment_method. The amount and the customer remain, so the customer can retry with another card against the same intent.

client.js
function showDecline(message, code) {
const copy = {
insufficient_funds: "That card can't cover this order. Try another card.",
expired_card: "That card has expired. Add a new one.",
incorrect_cvc: "The security code doesn't match. Check it and try again.",
};

showMessage(copy[code] ?? "That card was declined. Try another payment method.");
}

Map decline_code to your own copy instead of showing the raw message. The raw text names the card issuer and fits badly in a checkout form.

Test the four outcomes​

Run each card number from Test mode and test cards and confirm the behavior.

CardExpected resultWhat to verify
4242 4242 4242 4242Payment succeeds.Status reads succeeded, and the order flips to paid.
4000 0000 0000 9995Decline for insufficient funds.The decline copy shows, and the intent remains open.
4000 0025 0000 3155Authentication required.The challenge opens, and the flow resumes after it.
4000 0000 0000 0002Generic decline.The fallback copy shows, and the order remains unpaid.

Then replay the confirm call with the same idempotency key. Stripe returns the original intent, which keeps the order at one charge.

Go live​

Move from test mode to live mode in one pass.

  1. Swap the test key pair for live keys in the production secret store.
  2. Register the production webhook endpoint and store the signing secret.
  3. Send one low-value live charge and refund it.
  4. Confirm the payout schedule and the bank account on file.
  5. Turn on alerting for 5xx responses and failed webhooks.

Next steps​