# エージェントを使用した AI SaaS 請求ワークフローの構築 Stripe API と AI 活用エージェントを使用して、定期的な請求ワークフローを自動化します。 AI エージェントにより、Stripe を使用して、サブスクリプションベースの SaaS 請求プログラムを作成および管理できます。このガイドでは、次の方法について説明します。 - 新規顧客とサブスクリプションをプロビジョニング - Webhook を使用した、サブスクリプションライフサイクルイベントへの応答 - エージェントツールキットを使用して AI エージェントから請求アクションを呼び出す ## Before you begin このガイドでは、エージェントツールキットの設定が完了しており、Stripe アカウントがあることを前提に説明しています。次のリソースは、このガイド全体を通してリンクしされています。 - [エージェントツールキット](https://docs.stripe.com/agents.md) - [エージェントワークフローへの決済手段の追加](http://stripe.dev/blog/adding-payments-to-your-agentic-workflows) - [サブスクリプションの構築](https://docs.stripe.com/billing/subscriptions/build-subscriptions.md) - [サブスクリプション](https://docs.stripe.com/subscriptions.md) - [Webhook](https://docs.stripe.com/webhooks.md) - [導入テスト](https://docs.stripe.com/testing.md) さらに、次のものがあることを確認してください。 - Node.js 14 以降および既存のエージェントツールキットプロジェクト - API キーを持つ Stripe テストアカウント - Stripe Agent Toolkit がインストールされているか、Stripe アカウントと通信するように設定された [Model Context Protocol (MCP)](https://docs.stripe.com/mcp.md) サーバーのいずれか ## 顧客およびサブスクリプションのプロビジョニング 顧客およびサブスクリプションをプロビジョニングするには、エージェントが新しい顧客を作成して、サブスクリプションをアタッチする必要があります。Stripe Node.js SDK を使用した例を次に示します。 ```js import Stripe from 'stripe'; const stripe = new Stripe(process.env.STRIPE_SECRET_KEY); // Create a customer and subscription async function createSubscription(customerInfo, priceId) { // 1. Create or fetch the customer const customer = await stripe.customers.create({ email: customerInfo.email, name: customerInfo.name, }); // 2. Create the subscription const subscription = await stripe.subscriptions.create({ customer: customer.id, items: [{ price: priceId }], expand: ['latest_invoice.payment_intent'], }); } ``` 価格と試用版のオプションについては、[サブスクリプションの構築](https://docs.stripe.com/billing/subscriptions/build-subscriptions.md) をご参照ください。 ## Webhook を使用した請求イベントの処理 アプリケーションのサブスクリプションは、更新、決済の失敗、キャンセルなど、さまざまなイベントを引き起こします。いくつかの請求イベントは非同期であり、エージェントはそれらに応答する必要があります。例えば、サブスクリプションがキャンセルされた場合、エージェントに顧客のフォローアップをさせたり、顧客を維持するための提案をさせたりします。 これらのイベントを管理するには、[Webhook](https://docs.stripe.com/webhooks.md) を使用して、これらのトリガーをリッスンし、応答します。 以下のコード例では、Stripe Webhook イベントをリッスンし、受信リクエストを検証し、決済の成功、決済の失敗、サブスクリプションのキャンセルなどの特定のイベントタイプを処理するための Express サーバーを設定する方法を示しています。これらのイベントをキャプチャ後、エージェントを呼び出し、必要に応じて対応させます。 ```js import express from 'express'; import Stripe from 'stripe'; const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, { apiVersion: '2022-11-15' }); const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET; const app = express(); app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => { let event; try { event = stripe.webhooks.constructEvent(req.body, req.headers['stripe-signature'], endpointSecret); } catch (err) { return res.status(400).send(`Webhook Error: ${err.message}`); } switch (event.type) { case 'invoice.payment_succeeded': // Handle successful payment break; case 'invoice.payment_failed': // Call agent to retry or gather information to communicate with the buyer break; case 'customer.subscription.deleted': // Clean up access break; default: // Unexpected event } res.status(200).json({ received: true }); }); app.listen(4242, () => console.log('Webhook listener running on port 4242')); ``` ## エージェントツールキットを使用した請求の管理 [エージェントツールキット](https://docs.stripe.com/agents.md) を使用して、AI エージェントで請求フローを自動的に開始できるようにすることができます。 これは、コードで直接実装することも、Claude や MCP サーバーなどのアプリケーションで実装することもできます。 Vercel の [AI SDK](https://ai-sdk.dev/) を使用した例を次に示します。 ```javascript import { StripeAgentToolkit } from '@stripe/agent-toolkit/ai-sdk'; import { openai } from '@ai-sdk/openai'; import { generateText } from 'ai'; const stripeAgentToolkit = new StripeAgentToolkit({ secretKey: process.env.STRIPE_SECRET_KEY!, configuration: { actions: { prices: { read: true, }, customers: { create: true, }, subscriptions: { create: true, }, }, }, }); const result = await generateText({ model: openai('gpt-4o'), tools: { ...stripeAgentToolkit.getTools(), }, maxSteps: 5, prompt: 'Sign up jenny.rosen@example.com to the Premium plan', }); ``` 以下は、Stripe の MCP サーバーと OpenAI の Responses API を使用する例です。 ```curl curl https://api.openai.com/v1/responses -i \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-5", "tools": [ { "type": "mcp", "server_label": "Stripe", "server_url": "https://mcp.stripe.com", "require_approval": "never" } ], "input": "Sign up jenny.rosen@example.com to the Premium plan" }' ``` 完全なアクションを表示するには、[エージェントワークフローへの Stripe の追加](https://docs.stripe.com/agents.md) を参照してください。[LLM エージェントワークフローに決済を追加する](https://stripe.dev/blog/adding-payments-to-your-agentic-workflows) 方法の詳細をご覧ください。 ## テスト [サンドボックス](https://docs.stripe.com/sandboxes.md) を使用して、統合をテストできます。これにより、ライブ口座やデータに影響を与えることなく、決済処理やその他の機能をシミュレートできます。