sailfork / diff-demo / src/ checkout/ pay.ts

import Stripe from 'stripe';
import type { Cents } from '../util/money';

const stripe = new Stripe(process.env.STRIPE_KEY ?? '');

function backoff(attempt: number) {
  const base = 500 * 2 ** attempt;
  return Math.min(base, 30_000);
}

export async function pay(customer: string, amount: Cents) {
  for (let attempt = 0; attempt <= 5; attempt++) {
    try {
      return await stripe.paymentIntents.create({ customer, amount, currency: 'usd' });
    } catch {
      await new Promise((done) => setTimeout(done, backoff(attempt)));
    }
  }
  throw new Error('payment failed after retries');
}