To build server-side code for Stripe, you create a backend endpoint that receives a payment request from your client, uses your secret API key to create a PaymentIntent or Checkout Session, returns only safe identifiers to the browser, and confirms the outcome through a signature-verified webhook rather than trusting the redirect. The key condition: the secret key and webhook verification secret live only on the server, and your order fulfillment logic keys off the webhook event, not the browser's "success" page.

That single sentence is the whole architecture. Everything below is the working detail: which objects to use, how the request flows, how to verify webhooks correctly, how to test it, and where implementations usually break. I'll use Node.js with Express for concrete code because it's the most common starting point, but the patterns map directly to Python, PHP, Go, Java, Ruby, or .NET with the same Stripe concepts and equivalent SDK calls. Version-specific SDK details change, so treat the code as a template to reconcile against the current Stripe API reference and your SDK's release notes rather than a frozen artifact.

What "server-side code for Stripe" actually means

Stripe splits responsibilities deliberately. Your server is the trusted party. It holds the secret API key (sk_...), decides what to charge and in what currency, creates payment objects, and is the only place that should ever mark an order as paid. The browser is the untrusted party. It can hold your publishable key (pk_...), collect card details in Stripe-hosted or Stripe-embedded form fields, and talk to Stripe directly for tokenization, but it must never see your secret key or set the final price.

That split exists because anything shipped to the browser is readable by anyone. A price calculated in client JavaScript can be changed before the request leaves the device. So the canonical flow is: the client tells your server what it wants to buy (a product ID, a cart, a booking), the server looks up the real price from its own data, creates a Stripe object, and returns only a client secret or a checkout URL to the browser. The browser completes payment with Stripe directly. Stripe then tells your server, out of band, that payment happened.

There are two dominant implementation styles, and the right choice depends on your UI:

Stripe Checkout (hosted): your server creates a Checkout Session and redirects to a Stripe-hosted page. Least code, Stripe handles the payment form, wallets, and tax display. Good default for most products. Payment Intents with Stripe Elements (embedded): your server creates a PaymentIntent, returns its client secret, and your own form uses Stripe.js to confirm. More control over look and flow, more moving parts.

Both end at the same place: a webhook. I'll build the PaymentIntent path in detail because it exposes the mechanics, then show the Checkout Session shortcut, because in practice that's often what you'll ship.

Prerequisites before you write a line of code

Get these in place first; skipping them is the most common reason a first integration stalls.

1: A Stripe account and API keys. In the Stripe Dashboard, use test mode first. You'll have a test secret key (sk_test_...) and a test publishable key (pk_test_...). Live keys are separate and should never appear in test configuration. 2: A server runtime and framework. Node 18+ with Express is assumed here. The official stripe npm package is the SDK. Pin its major version in package.json and read the changelog when you upgrade, because major-version upgrades occasionally change default API behavior. 3: A public HTTPS endpoint for webhooks during development. Stripe must reach your server. A tunneling tool such as the Stripe CLI's stripe listen command, or any HTTPS tunnel, solves local development. A bare URL won't receive events from Stripe's servers. 4: Environment variable handling. Your secret key and webhook signing secret must come from environment variables or a secrets manager, never from committed files. Add .env to .gitignore before you create it. 5: Persistent storage. You need at least an orders or payments table with columns for your internal order ID, the Stripe object ID, the amount, the currency, and a status. Webhooks arrive more than once and out of order in edge cases; the database, not memory, is your source of truth.

A minimal .env for local work looks like this:

The whsec_... value comes from the Stripe CLI when you run stripe listen, or from the Dashboard endpoint settings for a deployed endpoint. It is per endpoint; don't reuse one endpoint's secret for another.

Step 1: Initialize the SDK on the server only

Create a small module that constructs the Stripe client once and exports it. Reconstructing the client per request works but wastes connections and scatters configuration.

Two details matter. First, the SDK sets an Authorization: Bearer sk_... header on every call; that key must not leave the server. Second, the apiVersion pin makes upgrades intentional. If you omit it, the SDK uses its own default version, which can shift when you upgrade the package. The exact version string to pin is whatever the current Stripe API reference lists and whatever your SDK release notes recommend; check both rather than copying the placeholder above blindly.

Fail fast if the key is missing. A server that boots without a key and only fails at the first payment attempt is harder to diagnose than one that refuses to start.

Step 2: Create a PaymentIntent endpoint

This endpoint is the heart of the integration. It must (a) authenticate the user, (b) look up the authoritative price server-side, (c) create or reuse a PaymentIntent, and (d) return only the client secret.

A few decisions inside that code deserve explanation.

Amounts are integers in the smallest currency unit. For USD that's cents, so $49.99 becomes 4999. Passing a float like 49.99 will throw or, worse, silently create a charge for 49 cents depending on the SDK's coercion. Compute money in integer cents everywhere, and only format for display at the edge.

Idempotency keys prevent double charges on retries. If the client times out and retries the same request, Stripe returns the original PaymentIntent rather than creating a second one, provided you send the same idempotency key. Derive the key from stable data (order ID plus attempt number), not from a random value generated per request.

Metadata carries your correlation. Storing orderId and userId in metadata lets webhook handlers and the Dashboard reconcile Stripe objects with your rows without a separate lookup table. Keep metadata small; don't put secrets in it.

The response is deliberately minimal. The client secret authorizes the browser to confirm that one PaymentIntent. Returning the whole intent object leaks amount and status details the client can read from Stripe anyway, but it also invites developers to trust client-side status. Return the secret and your own order ID; nothing else is needed.

Step 3: Confirm payment on the client with Stripe.js

The browser half is short, but it has one rule: the client confirms, it does not decide.

Your publishable key (pk_test_...) is loaded via Stripe(pk_...) and is safe in the browser. The card fields come from Stripe Elements, so raw card numbers never touch your server, which keeps you out of the most demanding PCI scope. The redirect: 'if_required' option lets wallet payments that need a redirect proceed while keeping card payments on-page.

After confirmation, the client may show a "thanks" screen. That screen is cosmetic. If you mark the order paid because the browser reached /checkout/return, a user who closes the tab mid-redirect leaves a paid order marked unpaid, and a crafted request can mark an unpaid order paid. Fulfillment must wait for the webhook.

Step 4: Handle webhooks correctly — the part that decides whether it works

Stripe sends events to your endpoint over HTTPS. Your job is to verify the event genuinely came from Stripe, make handling idempotent, and return 2xx quickly.

The raw body is non-negotiable. Signature verification hashes the exact bytes Stripe sent. If your JSON body parser runs first, it re-serializes the object and the signature no longer matches, producing the classic "No signatures found matching the expected signature for payload" error. If you use a global express.json() middleware, mount the webhook route before it, or configure a raw-body exception for that path. In frameworks other than Express, look for the equivalent raw-body accessor; every Stripe SDK provides a construct-event function that takes raw bytes.

The idempotency check on event.id protects you from duplicate deliveries, which are normal during retries and can happen at any time. Store processed event IDs with a unique constraint and return success immediately for repeats. Your fulfillment functions should also be idempotent at the business level; marking an order paid twice is usually harmless, but shipping twice is not.

Return 2xx fast, do slow work asynchronously. Stripe expects a response within a short window (its documentation describes a timeout in the tens of seconds; the exact figure is in the webhook docs and changes over time). If you need to send emails, provision servers, or call slow third-party APIs, enqueue a job and respond 200 after persisting the event. If you must do synchronous work and it fails, return 5xx so Stripe retries with exponential backoff.

A subtle but important limit: retries are not infinite. Stripe retries failed events for a period measured in days (consult the current docs for the exact schedule), after which the event is dropped. That means you also need a reconciliation job that queries Stripe for PaymentIntents in a recent window and compares them against your orders, to catch events that were missed entirely because your endpoint was down for longer than the retry window.

Step 5: Test before you trust it

Testing is where most integration bugs become visible, and Stripe gives you sharp tools for it. With the Stripe CLI running stripe listen --forward-to localhost:4242/api/stripe-webhook, the CLI prints a whsec_... secret to use locally and forwards real test-mode events to your machine.

Use Stripe's documented test card numbers (for example, the widely used 4242 4242 4242 4242 for a successful Visa charge) with any future expiry and any CVC in test mode. Stripe publishes a table of cards that trigger specific failures, authentication challenges, and disputes; consult the current testing docs rather than relying on memory, since the list evolves.

Then run the failures deliberately:

Card declined: use a decline test card, confirm payment_intent.payment_failed arrives and your order stays unpaid. 3D Secure required: use a card that triggers authentication, confirm the redirect or modal appears and the webhook fires after confirmation. Webhook signature error: temporarily set a wrong STRIPE_WEBHOOK_SECRET and confirm the endpoint returns 400 and does not mark anything paid. Duplicate delivery: replay an event with stripe events resend <event_id> and confirm your handler is idempotent. Server crash mid-handler: stop the server, trigger an event, restart, and confirm Stripe retries and your handler eventually succeeds.

Success check: the Stripe Dashboard's Payments list and your orders table agree on amount, currency, and status for every test case, and your webhook endpoint's event log shows 2xx responses with no signature failures.

Checkout Sessions: the shorter path for most products

If you don't need a custom payment form, a Checkout Session replaces steps 2 through 4 with less code and fewer failure modes. Your server creates a session with line_items referencing your own Price IDs or ad hoc price_data, sets success and cancel URLs, and returns the session URL. Stripe hosts the page.

The webhook handling is nearly identical, except you listen for checkout.session.completed and read session.metadata.orderId. Use the success URL only to show a confirmation page; fetch the session server-side if you want to display a summary, but still gate fulfillment on the webhook. Checkout also handles tax calculation, shipping address collection, and locale automatically when configured, which is a meaningful amount of code you don't write.

The trade-off is control: Checkout's UI is Stripe's, branding options are limited to settings Stripe exposes, and some unusual flows (split payments, custom multi-step wizards) fit PaymentIntents better. For a straightforward "buy these items" flow, Checkout usually wins on both speed and correctness.

Idempotency, reconciliation, and the failure modes that bite

Beyond the webhook basics, four failure patterns recur in real deployments.

Trusting the client's amount. If your endpoint accepts amount from the request body, an attacker can pay one cent for a thousand-dollar order. Always derive the amount from server-side data. If you must accept a client hint (a coupon code, a shipping option), validate it server-side against your own rules before it affects the amount.

Marking paid on redirect. Covered above, but worth repeating because it's the single most common first-integration bug. The success URL is a UX signal, not a payment signal.

Double fulfillment on duplicate events. Stripe can and does deliver the same event more than once, especially after timeouts and retries. Without an idempotency key on event.id and idempotent business logic, you'll ship twice or credit twice. Use a unique database constraint on the event ID; a simple check-then-insert race is not enough under concurrent delivery.

Silent drift between Stripe and your database. Events can be missed if your endpoint is down past the retry window, or if a bug caused your handler to reject a valid event. A nightly reconciliation job that lists PaymentIntents updated in the last 24–48 hours (Stripe's list endpoints support time filters) and compares status against your orders catches drift before customers do. Log every mismatch and alert on any.

A fifth, less obvious point: currency and amount rounding. Stripe charges in the smallest unit of the currency, and some currencies have zero decimal places (JPY) or three (BHD, KWD). If you hardcode "multiply by 100," you'll be wrong for those currencies. Stripe's docs list zero-decimal and three-decimal currencies; encode that table in your money-handling code, or use integer minor units end to end with the correct exponent per currency.

Security and production hygiene

A short checklist that prevents the expensive mistakes:

Secret key scope. Use a restricted API key in production where possible, granting only the permissions your integration needs (for example, write access to PaymentIntents and read access to Charges), rather than a full secret key. Stripe's restricted keys are created in the Dashboard and behave like normal keys. Environment separation. Test and live keys are distinct; a test-key server pointed at a live database, or vice versa, is a data-integrity incident waiting to happen. Gate startup on an explicit environment flag. Secrets management. Inject STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET from your platform's secrets store. Rotate them if they ever appear in logs, error traces, or a repository. Stripe supports rolling keys, so rotation need not cause downtime if you follow its guidance. HTTPS everywhere. Webhook endpoints must be HTTPS in production. Stripe rejects plain HTTP for live endpoints. Logging discipline. Log event IDs and your order IDs, not full payloads containing customer data, and never the keys. A log aggregator that ingests secret keys is a breach. Rate limiting and auth on your endpoints. Your create-payment-intent endpoint should require an authenticated session and be rate-limited; otherwise it's a free way for anyone to create objects in your Stripe account. TLS and SDK currency. Keep the stripe package reasonably current; older majors can stop receiving security fixes. Check the package's release notes rather than assuming.

Where to stop and get help

This walkthrough covers the standard card and wallet flow. Some adjacent areas need dedicated, current documentation and, often, professional review before you ship: tax calculation and remittance rules vary by jurisdiction; SCA and strong customer authentication requirements differ by region and are enforced differently over time; subscription billing and invoicing have their own object model and proration rules; and marketplace or platform flows (Connect) change who is liable and who must be verified. If your integration touches regulated lending, stored-value balances, or cross-border payout rules, bring in someone qualified in those areas rather than extrapolating from the payment flow above.

For immediate troubleshooting, the fastest checks in order are: does the webhook return 200 in the Dashboard event log, does the signature verify with the correct per-endpoint secret, is the raw body unparsed, and does your handler tolerate replay. Those four questions resolve the large majority of "it works in test but not in production" reports.