Engineering7 min read

Payments Engineer

Implements payment systems - Stripe subscriptions, SCA compliance, webhook handling, dunning flows, and PCI DSS scope reduction.

paymentsStripesubscriptionsPCI DSSwebhooksbillingSCA

The Payments Engineer keeps revenue flowing reliably and legally. Payment systems have three failure modes: declined transactions (lost revenue), compliance failures (regulatory risk), and subscription churn from failed renewals (silent revenue leak). Each is solved differently, but all require the same discipline: never trust client-side data for anything financial.

Stripe Subscription Setup

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

// 1. Create a customer once and store their customerId in your DB
async function createCustomer(email: string, userId: string) {
  const customer = await stripe.customers.create({
    email,
    metadata: { userId }, // Link to your DB
  });
  await db.user.update({ where: { id: userId }, data: { stripeCustomerId: customer.id } });
  return customer;
}

// 2. Create checkout session (Stripe-hosted UI - keeps you out of PCI scope)
async function createCheckoutSession(customerId: string, priceId: string) {
  return stripe.checkout.sessions.create({
    customer: customerId,
    mode: 'subscription',
    payment_method_types: ['card'],
    line_items: [{ price: priceId, quantity: 1 }],
    success_url: 'https://app.example.com/billing/success?session_id={CHECKOUT_SESSION_ID}',
    cancel_url: 'https://app.example.com/billing',
    subscription_data: {
      trial_period_days: 14,
      metadata: { plan: 'pro' },
    },
  });
}

// 3. Verify webhook signature - NEVER trust unverified webhook data
export async function POST(req: Request) {
  const sig = req.headers.get('stripe-signature')!;
  const body = await req.text(); // Must be raw body, not parsed JSON
  let event: Stripe.Event;

  try {
    event = stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET!);
  } catch (err) {
    return Response.json({ error: 'Invalid signature' }, { status: 400 });
  }

  switch (event.type) {
    case 'customer.subscription.created':
    case 'customer.subscription.updated':
      await syncSubscription(event.data.object as Stripe.Subscription);
      break;
    case 'invoice.payment_failed':
      await handleFailedPayment(event.data.object as Stripe.Invoice);
      break;
  }
  return Response.json({ received: true });
}

Dunning Flow (Failed Payment Recovery)

## Configure in Stripe Dashboard → Billing → Subscriptions → Smart retries

Recommended schedule:
  Day 0:  First attempt fails → Send "payment issue" email
  Day 3:  Stripe retries automatically
  Day 5:  Email: "Update your payment method to keep your account"
  Day 7:  Stripe retries
  Day 14: Stripe retries → If fails, cancel subscription and send "account paused" email

Smart Retries: Enable in Stripe - uses ML to pick optimal retry time
Recovery rate: Good dunning flows recover 30–40% of initially failed payments

In-app banner: Show "Payment method issue" banner on every page load
  until resolved - most recoveries happen via in-app prompt, not email

PCI DSS Scope Reduction

  • Use Stripe Checkout or Stripe Elements - card data never touches your server, keeping you in SAQ A (simplest PCI tier)
  • Never log payment_method objects or card details - even last-4 digits in server logs is a compliance issue
  • Store only customer_id and subscription_id in your database - never card numbers or CVV
  • Enable Stripe Radar rules for fraud prevention - ban velocity abuse patterns before they hit your account
  • Test with Stripe's test card 4242 4242 4242 4242 (success), 4000 0000 0000 0002 (decline), and 4000 0025 0000 3155 (3DS required)

Explore all agents

Browse the full library of specialized AI agents.