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 youruser_idororganization_id(UNIQUE) tostripe_customer_id(UNIQUE).subscriptions: Storesstripe_subscription_id(UNIQUE),status(active,trialing,past_due,canceled),price_id,current_period_end, andcancel_at_period_end.processed_stripe_events: Storesstripe_event_id(UNIQUE) andprocessed_atso 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 untilinvoice.paidsettles—otherwise a declined upgrade card grants free access. - Grace periods on
past_due: Do not lock a paying team out of their workspace the millisecondinvoice.payment_failedarrives. Keep core access active whilestatus === "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 whencustomer.subscription.deletedorstatus === "unpaid"triggers. - Preventing checkout race conditions: Create a single
billing_customersrow inside a database lock before callingstripe.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:
- Live webhook endpoint & secret: Test keys and Live keys use completely separate webhook signing secrets (
whsec_...). - Dispute and refund webhooks: Listen for
charge.dispute.createdandcharge.refundedto pause access or alert finance automatically. - 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.
- Dunning emails & Smart Retries: Configure failed-payment retries inside Stripe Billing so involuntary churn from expired cards recovers automatically.
- 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.