HomeBlogHow to Build a Payment Integration...

Engineering Guide · 9 min read · October 23, 2026

How to Build a Payment Integration with Stripe

A payment integration is only half-built when the test card succeeds in staging. Production-grade Stripe billing requires server-side price calculation, idempotency keys, asynchronous webhook fulfillment, and a clean local ledger that survives retries, 3D Secure redirects, and disputes.

Author
Smit Desai
Published
October 23, 2026
Read time
9 min read
Topic
APIs & Integrations
Services
Custom Web · Mobile Apps · All Services

Every founder wants checkout live yesterday, which is why so many startups ship the same fragile Stripe shortcut: the frontend calls an endpoint to create a payment, receives a success callback in JavaScript, and immediately fires POST /api/unlock-subscription.

Then real customers arrive. A buyer completes 3D Secure in a European banking app and closes Safari before the redirect finishes—their card is charged, yet their account stays locked. Or a flaky mobile connection retries checkout twice without an idempotency key, charging the customer twice.

Reliable payment systems treat Stripe as an asynchronous state machine, never a synchronous RPC call.

Stripe Checkout vs. PaymentIntents + Elements

Before writing a line of integration code, match the integration surface to your stage and compliance appetite:

Factor Stripe Checkout (Hosted) PaymentIntents + Elements (Embedded)
Time to production 1–2 days 4–8 days
PCI DSS scope Minimal (SAQ A) Minimal (SAQ A with Elements)
3D Secure / SCA & local methods Handled automatically Handled via confirmPayment + return_url
Custom multi-step UI control Limited to branding/theme Full control inside React/Vue/Blade
Best fit MVPs, SaaS plans, fast B2B invoicing Marketplaces, custom POS, complex cart flows

Unless custom checkout UX is a core product differentiator, Stripe Checkout eliminates entire classes of edge cases around localized payment methods, address validation, and tax calculation.

Server-Side Pricing, Integer Amounts, and Idempotency

Never accept amount or price from the browser. Your backend looks up plan_id or cart SKU totals from your database, computes amounts in the smallest currency unit (cents for USD/EUR, fils for AED, zero-decimal yen for JPY), and passes an explicit idempotencyKey:

import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function createOrderPaymentIntent(orderId: string, userId: string) {
  const order = await db.orders.findUniqueOrThrow({ where: { id: orderId, userId } });

  if (order.status === "paid") {
    throw new Error("Order already settled");
  }

  // Deterministic key guarantees retries never double-charge the same checkout attempt
  const intent = await stripe.paymentIntents.create(
    {
      amount: order.totalCents,
      currency: order.currency.toLowerCase(),
      customer: order.stripeCustomerId,
      automatic_payment_methods: { enabled: true },
      metadata: {
        order_id: order.id,
        user_id: userId,
      },
    },
    {
      idempotencyKey: `pi_order_${order.id}_v${order.attemptCount}`,
    }
  );

  await db.orders.update({
    where: { id: order.id },
    data: { stripePaymentIntentId: intent.id },
  });

  return intent.client_secret;
}

Incrementing attemptCount whenever cart totals change avoids Stripe's idempotency_error if a customer goes back, adds another item, and restarts checkout on the same order record.

Designing Your Local Billing Schema

Avoid querying Stripe's API synchronously on every dashboard request to ask "is this user subscribed?" Mirror authoritative state locally using three lean tables:

  • billing_customers: Maps your user_id or organization_id (UNIQUE) to stripe_customer_id (UNIQUE).
  • subscriptions: Stores stripe_subscription_id (UNIQUE), status (active, trialing, past_due, canceled), price_id, current_period_end, and cancel_at_period_end.
  • processed_stripe_events: Stores stripe_event_id (UNIQUE) and processed_at so duplicate webhook deliveries are ignored safely.

Keep an eye on event ordering: Stripe does not guarantee webhooks arrive in strict chronological sequence. When customer.subscription.updated fires, either check event.created against your stored last_synced_event_ts or fetch the canonical subscription object inside your background worker before updating entitlements.

Signed Webhooks: The Only Source of Fulfillment Truth

Follow Stripe's webhook verification guide strictly: verify Stripe-Signature using the unparsed raw request body, record the event ID, enqueue fulfillment work, and respond 200 OK within two seconds.

// Laravel webhook endpoint skeleton
public function __invoke(Request $request)
{
    $payload   = $request->getContent();
    $sigHeader = (string) $request->header('Stripe-Signature', '');

    try {
        $event = \Stripe\Webhook::constructEvent(
            $payload,
            $sigHeader,
            config('services.stripe.webhook_secret')
        );
    } catch (\Throwable $e) {
        return response()->json(['error' => 'Invalid signature'], 400);
    }

    // Atomic deduplication before enqueueing
    $inserted = DB::table('processed_stripe_events')->insertOrIgnore([
        'stripe_event_id' => $event->id,
        'type'            => $event->type,
        'created_at'      => now(),
    ]);

    if ($inserted === 1) {
        HandleStripeWebhookJob::dispatch($event->id, $event->type, $event->data->object->toArray());
    }

    return response()->json(['received' => true], 200);
}

Running fulfillment inside HandleStripeWebhookJob isolates receipt from heavy work (provisioning tenant workspaces, generating PDF invoices, sending transactional emails). If your mail provider goes down temporarily, your Redis worker retries cleanly—see scaling background jobs with Laravel and Redis for the exact worker configuration—while Stripe already received 200 OK.

If you want deeper background on why webhook-only flows still benefit from a periodic sync sweep, check webhooks vs. API polling.

Subscription Lifecycles, Proration, and Past-Due Grace Windows

One-off charges are relatively forgiving; recurring SaaS billing is where database state drifts unless you model subscription transitions deliberately:

  • Plan upgrades and proration: When a customer switches from a monthly tier to an annual or higher-seat plan, pass proration_behavior: "create_prorations" (or "always_invoice" when upgrading immediately) and avoid flipping feature flags locally until invoice.paid settles—otherwise a declined upgrade card grants free access.
  • Grace periods on past_due: Do not lock a paying team out of their workspace the millisecond invoice.payment_failed arrives. Keep core access active while status === "past_due" for a defined 5–7 day dunning window, display an in-app banner linking to Stripe's Customer Portal, and revoke seats only when customer.subscription.deleted or status === "unpaid" triggers.
  • Preventing checkout race conditions: Create a single billing_customers row inside a database lock before calling stripe.customers.create, so two simultaneous browser clicks never spawn duplicate Stripe Customer objects for the same tenant.

Production Launch Checklist for Founders & CTOs

Before switching from sk_test_ to sk_live_, verify these five details:

  1. Live webhook endpoint & secret: Test keys and Live keys use completely separate webhook signing secrets (whsec_...).
  2. Dispute and refund webhooks: Listen for charge.dispute.created and charge.refunded to pause access or alert finance automatically.
  3. Customer Portal enabled: Let users update expiring cards and download VAT/GST invoices via Stripe's hosted Billing Portal instead of building custom card-update forms.
  4. Dunning emails & Smart Retries: Configure failed-payment retries inside Stripe Billing so involuntary churn from expired cards recovers automatically.
  5. Audit logging on entitlements: Log every plan upgrade, downgrade, and webhook event ID so support can trace billing disputes in seconds.

How SmitDev Delivers Production Stripe Billing

Having shipped 170+ production applications—including subscription billing, mobile-to-web payment funnels, and multi-currency SaaS platforms across the USA, UK, Europe, UAE, Australia, and Singapore—I build Stripe integrations that reconcile cleanly down to the cent.

Whether you need a fresh checkout + subscription architecture via custom web application development, senior capacity through our services, or an hourly developer at $55/day for 8–9 hours of hands-on implementation (or $1,999/month dedicated engineering), you get senior architecture without agency bloat. Let's discuss your billing integration.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Custom Web & SaaS

Custom Web Application Development

Production Laravel, Next.js, API, and multi-tenant SaaS systems engineered end to end at $55/day (8–9 hrs) or $1,999/mo.

Comparison · Buyer Guide

SmitDev vs Software Agencies

See side-by-side economics, senior code ownership, and onboarding speed vs traditional dev shops and marketplaces.

01 — Frequently asked questions

apis & integrations

Should a startup build with Stripe Checkout or PaymentIntents + Elements?

Start with Stripe Checkout if you want to launch in days with built-in Apple Pay, Google Pay, Link, tax collection, and zero PCI UI maintenance. Choose PaymentIntents with Stripe Elements only when you need custom multi-step checkout UX or embedded billing inside an existing React/mobile flow.

Why shouldn't I unlock a user's purchase right after stripe.confirmPayment() succeeds in React?

Browser tabs close, mobile networks drop right after 3D Secure authentication, and client requests can be spoofed. Treat the client redirect solely as a UX confirmation screen and grant entitlements only inside your verified backend webhook handler.

How do Stripe idempotency keys prevent double charges?

Passing a deterministic idempotency key (such as an order UUID) on POST requests tells Stripe to return the original result if your server or network retries the exact same call within 24 hours, rather than creating a second PaymentIntent.

What Stripe webhook events are mandatory for SaaS subscriptions?

At minimum, handle checkout.session.completed (or invoice.paid), invoice.payment_failed, customer.subscription.updated, and customer.subscription.deleted so upgrades, past-due states, and cancellations stay synchronized with your database.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.