stripe-integration は何をしますか?
Stripe決済処理を実装し、チェックアウト、サブスクリプション、Webhookを含む堅牢でPCI準拠の決済フローを構築します。Stripe決済の統合、サブスクリプションシステムの構築、安全なチェックアウトフローの実装に使用します。
概要
このスキルは、アプリケーションにStripe決済を統合するための完全なガイドです。以下の機能をサポートします。
- ワンタイム決済: 単一の商品やサービスの購入
- サブスクリプション: 定期的な支払いプランの作成と管理
- Webhook: 決済イベントのリアルタイム処理
- カスタマーポータル: ユーザーによるサブスクリプション管理
前提条件
- Stripeアカウントの作成
- APIキーの取得(公開可能キーとシークレットキー)
- 開発環境のセットアップ(Node.js、Python、Rubyなど)
クイックスタート
# Stripe CLIのインストール(テスト用)
brew install stripe/stripe-cli/stripe
# 依存関係のインストール
npm install stripe
基本的な実装パターン
1. サーバーサイドのセットアップ
const Stripe = require('stripe');
const stripe = Stripe(process.env.STRIPE_SECRET_KEY);
// 決済インテントの作成
async function createPaymentIntent(amount, currency = 'usd') {
const paymentIntent = await stripe.paymentIntents.create({
amount: amount,
currency: currency,
automatic_payment_methods: { enabled: true },
});
return paymentIntent.client_secret;
}
2. フロントエンドの実装
<script src="https://js.stripe.com/v3/"></script>
<script>
const stripe = Stripe('pk_test_...');
const elements = stripe.elements();
const cardElement = elements.create('card');
cardElement.mount('#card-element');
const form = document.getElementById('payment-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const { error, paymentIntent } = await stripe.confirmCardPayment(
clientSecret,
{ payment_method: { card: cardElement } }
);
});
</script>
3. Webhookの処理
// Webhook署名の検証
const endpointSecret = 'whsec_...';
const sig = request.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
} catch (err) {
response.status(400).send(`Webhook Error: ${err.message}`);
return;
}
// イベントタイプに応じた処理
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data.object;
console.log('PaymentIntent was successful!');
break;
case 'payment_intent.payment_failed':
const paymentIntentFailed = event.data.object;
console.log('Payment failed!');
break;
default:
console.log(`Unhandled event type ${event.type}`);
}
4. サブスクリプションの作成
// 顧客の作成
const customer = await stripe.customers.create({
email: '[email protected]',
});
// サブスクリプションの作成
const subscription = await stripe.subscriptions.create({
customer: customer.id,
items: [{ price: 'price_123' }],
payment_behavior: 'default_incomplete',
expand: ['latest_invoice.payment_intent'],
});
環境変数
| 変数名 | 説明 |
|---|---|
STRIPE_SECRET_KEY | Stripeシークレットキー(サーバーサイド) |
STRIPE_PUBLISHABLE_KEY | Stripe公開可能キー(フロントエンド) |
STRIPE_WEBHOOK_SECRET | Webhook署名シークレット |
ベストプラクティス
- シークレットキーをコードにハードコーディングしないでください
- 本番環境ではStripe SDKの最新バージョンを使用してください
- すべてのWebhookイベントを適切に処理してください
- エラーハンドリングを徹底し、ユーザーにわかりやすいメッセージを表示してください
- テスト環境ではテストカード番号(
4242 4242 4242 4242)を使用してください