Use Cases

Stripe Checkout Implementation dengan Claude Code

Pelajari tentang stripe checkout implementation menggunakan Claude Code. Dilengkapi tips praktis dan contoh kode.

Stripe Checkoutimplementasi dengan Claude Code: efisiensi

Stripe Checkout ホスト型 決済UI 、PCI DSS準拠 手間 最小限 抑えな らamanな決済 implementasi bisa dilakukan.Claude Code 使えば、kompleksな決済フロー pembangunan juga スムーズ 進められ.

pembuatan Checkout session

> Stripe Checkoutsession pembuatanするAPI implementasikan.
> 単品購入 dan subscription両方 support.
// src/api/checkout.ts
import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: '2024-12-18.acacia',
});

// 単品購入 Checkoutsession
export async function createCheckoutSession(
  priceId: string,
  customerId?: string
) {
  const session = await stripe.checkout.sessions.create({
    mode: 'payment',
    payment_method_types: ['card'],
    customer: customerId,
    line_items: [
      {
        price: priceId,
        quantity: 1,
      },
    ],
    success_url: `${process.env.APP_URL}/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${process.env.APP_URL}/cancel`,
    metadata: {
      source: 'web',
    },
  });

  return session;
}

// subscription Checkoutsession
export async function createSubscriptionSession(
  priceId: string,
  customerId?: string
) {
  const session = await stripe.checkout.sessions.create({
    mode: 'subscription',
    payment_method_types: ['card'],
    customer: customerId,
    line_items: [
      {
        price: priceId,
        quantity: 1,
      },
    ],
    subscription_data: {
      trial_period_days: 14,
      metadata: { plan: 'pro' },
    },
    success_url: `${process.env.APP_URL}/dashboard?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${process.env.APP_URL}/pricing`,
  });

  return session;
}

Penanganan Webhook

> Stripe Webhook pemrosesanするendpoint implementasikan.
> 署名verifikasi dan 主要なeventハンドリング して。
// src/api/webhook.ts
import Stripe from 'stripe';

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

export async function handleWebhook(
  body: string | Buffer,
  signature: string
) {
  let event: Stripe.Event;

  try {
    event = stripe.webhooks.constructEvent(body, signature, webhookSecret);
  } catch (err) {
    throw new Error(`Webhook signature verification failed`);
  }

  switch (event.type) {
    case 'checkout.session.completed': {
      const session = event.data.object as Stripe.Checkout.Session;
      await handleCheckoutComplete(session);
      break;
    }
    case 'invoice.payment_succeeded': {
      const invoice = event.data.object as Stripe.Invoice;
      await handlePaymentSucceeded(invoice);
      break;
    }
    case 'customer.subscription.deleted': {
      const subscription = event.data.object as Stripe.Subscription;
      await handleSubscriptionCanceled(subscription);
      break;
    }
    default:
      console.log(`Unhandled event type: ${event.type}`);
  }

  return { received: true };
}

async function handleCheckoutComplete(session: Stripe.Checkout.Session) {
  const customerId = session.customer as string;
  const customerEmail = session.customer_details?.email;
  // DB pengguna情報 penyimpanan、メールpengirimanなど
  console.log(`Checkout completed for ${customerEmail}`);
}

async function handlePaymentSucceeded(invoice: Stripe.Invoice) {
  // subscription pembaruanpemrosesan
  console.log(`Payment succeeded: ${invoice.id}`);
}

async function handleSubscriptionCanceled(subscription: Stripe.Subscription) {
  // アクセス権 無効化pemrosesan
  console.log(`Subscription canceled: ${subscription.id}`);
}

implementasi frontend

> Next.js dengan 価格表halaman dan Checkouttombol buatkan.
// app/pricing/page.tsx
'use client';

import { useState } from 'react';

const plans = [
  { name: 'Basic', price: '¥980/月', priceId: 'price_basic_monthly' },
  { name: 'Pro', price: '¥2,980/月', priceId: 'price_pro_monthly' },
  { name: 'Enterprise', price: '¥9,800/月', priceId: 'price_enterprise_monthly' },
];

export default function PricingPage() {
  const [loading, setLoading] = useState<string | null>(null);

  const handleCheckout = async (priceId: string) => {
    setLoading(priceId);
    try {
      const res = await fetch('/api/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ priceId }),
      });
      const { url } = await res.json();
      window.location.href = url;
    } catch (error) {
      console.error('Checkout error:', error);
    } finally {
      setLoading(null);
    }
  };

  return (
    <div className="grid grid-cols-3 gap-6 max-w-4xl mx-auto p-8">
      {plans.map((plan) => (
        <div key={plan.priceId} className="border rounded-lg p-6 text-center">
          <h3 className="text-xl font-bold">{plan.name}</h3>
          <p className="text-3xl font-bold my-4">{plan.price}</p>
          <button
            onClick={() => handleCheckout(plan.priceId)}
            disabled={loading === plan.priceId}
            className="bg-indigo-600 text-white px-6 py-2 rounded-lg"
          >
            {loading === plan.priceId ? 'pemrosesan中...' : '購入'}
          </button>
        </div>
      ))}
    </div>
  );
}

Summary

Stripe Checkout 使えば、aman 高品質な決済体験 素早くpembangunan bisa dilakukan.Claude Code pemanfaatanすれば、Webhookやsubscription dll. Stripe固有 implementasipola juga efisien 進められ.決済integrasi dasarWebhookimplementasipanduan juga bisa dijadikan referensi.

Untuk Stripeの詳細, lihat Stripe公式ドキュメント.

#Claude Code #Stripe #payments #Checkout #subscription