Claude Code के साथ Stripe Checkout Implementation
Claude Code का उपयोग करके stripe checkout implementation सीखें। Practical tips और code examples शामिल हैं।
Stripe Checkoutimplementationको Claude Code से Efficient बनाएं
Stripe Checkoutはホスト型の決済UIで、PCI DSS準拠の手बीचを最小限に抑えながらsafeな決済をimplementationでき है।Claude Code का उपयोग करके、complexな決済フローのbuildもスムーズに進められ है।
Checkout セッションのcreate
> Stripe CheckoutセッションをबनानाAPIをimplement करो。
> 単品購入とsubscription両方にsupportして。
// src/api/checkout.ts
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: '2024-12-18.acacia',
});
// 単品購入のCheckoutセッション
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のCheckoutセッション
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;
}
Webhookprocessing
> StripeのWebhookをprocessingするendpointをimplement करो。
> 署名検証と主要な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にuser情報を保存、メール送信 आदि
console.log(`Checkout completed for ${customerEmail}`);
}
async function handlePaymentSucceeded(invoice: Stripe.Invoice) {
// subscriptionのupdateprocessing
console.log(`Payment succeeded: ${invoice.id}`);
}
async function handleSubscriptionCanceled(subscription: Stripe.Subscription) {
// アクセス権の無効化processing
console.log(`Subscription canceled: ${subscription.id}`);
}
フロントエンドのimplementation
> Next.jsで価格表pageとCheckoutbuttonを作って。
// 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 ? 'processingमें...' : '購入する'}
</button>
</div>
))}
</div>
);
}
Summary
Stripe Checkoutを使えば、safeで高品質な決済体験を素早くbuild किया जा सकता है。Claude Code का लाभ उठाकर、Webhookやsubscription आदिのStripe固有のimplementationpatternもefficiently進められ है।決済integrationの基本やWebhookimplementationガイドभी reference के लिए देखें。
Stripeके details के लिएStripeofficial documentationをदेखें。
Related Posts
Claude Code से अपने Side Projects को Supercharge कैसे करें [Examples के साथ]
Claude Code से personal development projects को dramatically speed up करना सीखें। Real-world examples और idea से deployment तक practical workflow शामिल है।
Claude Code से Refactoring कैसे Automate करें
Claude Code से efficiently code refactoring automate करना सीखें। Real-world projects के लिए practical prompts और concrete refactoring patterns शामिल हैं।
Claude Code के साथ Complete CORS Configuration Guide
Claude Code का उपयोग करके complete CORS configuration guide सीखें। Practical tips और code examples शामिल हैं।