๐Ÿ’ณ

Payments with Stripe

๐Ÿ‘จโ€๐Ÿณ Chefโฑ๏ธ 35 minutes

๐Ÿ“‹ Suggested prerequisites

  • โ€ขStripe account
  • โ€ขNext.js API

What you'll build

A payment page where your users can purchase products or subscribe to your service securely with a credit card. You'll implement Stripe Checkout which handles all the complexity: payment form, card validation, PCI compliance, and webhooks to confirm payments. When finished, you'll have a complete payment flow with success and cancellation pages, ready to receive real money (starting in test mode).


Setup

  1. Create account at stripe.com
  2. Copy API keys (test mode)
  3. pnpm add stripe @stripe/stripe-js

Step 1: Ask an AI for the integration

I need to integrate payments with Stripe:
- Checkout Session for one-time payment
- Webhook to confirm payment
- Success/cancel page
- Next.js App Router
- TypeScript

Give me the complete code.

API Route

import Stripe from 'stripe'

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

export async function POST(request: Request) {
  const { priceId } = await request.json()

  const session = await stripe.checkout.sessions.create({
    mode: 'payment',
    line_items: [{ price: priceId, quantity: 1 }],
    success_url: `${process.env.URL}/success`,
    cancel_url: `${process.env.URL}/cancel`
  })

  return Response.json({ url: session.url })
}

Payment button

const handleCheckout = async () => {
  const { url } = await fetch('/api/checkout', {
    method: 'POST',
    body: JSON.stringify({ priceId: 'price_xxx' })
  }).then(r => r.json())

  window.location.href = url
}

Next step

โ†’ Transactional Emails