Guide Payment Integration
Comprehensive agent designed for payment, systems, integration, specialist. Includes structured workflows, validation checks, and reusable patterns for business marketing.
Guide Payment Integration
An autonomous agent that designs and implements payment integrations β connecting Stripe, PayPal, and other payment processors with proper subscription handling, webhook processing, tax calculation, and PCI compliance.
When to Use This Agent
Choose Guide Payment Integration when:
- You need to integrate Stripe, PayPal, or other payment processors
- You are building subscription billing with upgrade/downgrade flows
- You need webhook handling for payment events (success, failure, refund)
- You want to ensure PCI compliance and secure payment handling
Consider alternatives when:
- You need payment fraud detection (use a fraud prevention service)
- You need accounting or revenue recognition (use an accounting system)
- You need payment processing without code (use a no-code payment platform)
Quick Start
# .claude/agents/payment-integration.yml name: guide-payment-integration description: Implement payment processing and subscription billing agent_prompt: | You are a Payment Integration Expert. When implementing payments: 1. Set up payment processor SDK (Stripe, PayPal, etc.) 2. Implement secure checkout flow (Stripe Elements, hosted pages) 3. Handle subscriptions: create, update, cancel, pause 4. Process webhooks for all payment events 5. Implement proper error handling and retry logic 6. Ensure PCI compliance (never handle raw card data) Security rules: - NEVER store raw credit card numbers - ALWAYS use Stripe Elements or equivalent for card input - ALWAYS verify webhook signatures - ALWAYS use idempotency keys for mutations - Handle payment failures gracefully with retry logic
Example invocation:
claude "Integrate Stripe for subscription billing with monthly and annual plans, including upgrade/downgrade proration"
Sample integration:
// Stripe subscription management import Stripe from 'stripe'; const stripe = new Stripe(process.env.STRIPE_SECRET_KEY); // Create subscription async function createSubscription(customerId: string, priceId: string) { const subscription = await stripe.subscriptions.create({ customer: customerId, items: [{ price: priceId }], payment_behavior: 'default_incomplete', expand: ['latest_invoice.payment_intent'], }); return { subscriptionId: subscription.id, clientSecret: (subscription.latest_invoice as Stripe.Invoice) .payment_intent?.client_secret, }; } // Upgrade/downgrade with proration async function changeSubscriptionPlan( subscriptionId: string, newPriceId: string ) { const subscription = await stripe.subscriptions.retrieve(subscriptionId); return stripe.subscriptions.update(subscriptionId, { items: [{ id: subscription.items.data[0].id, price: newPriceId, }], proration_behavior: 'create_prorations', }); }
Core Concepts
Payment Integration Architecture
| Component | Technology | Purpose |
|---|---|---|
| Checkout | Stripe Elements / PayPal SDK | Secure card input (PCI SAQ A) |
| Backend | Stripe SDK / REST API | Create charges, subscriptions |
| Webhooks | HTTP endpoints | Process async payment events |
| Database | Your DB | Store subscription state, invoices |
| Monitoring | Logs + alerts | Track failures, disputes, fraud |
Webhook Processing
// Secure webhook handler async function handleStripeWebhook(req: Request, res: Response) { const sig = req.headers['stripe-signature'] as string; let event: Stripe.Event; try { event = stripe.webhooks.constructEvent( req.body, sig, process.env.STRIPE_WEBHOOK_SECRET ); } catch (err) { console.error('Webhook signature verification failed:', err.message); return res.status(400).send(`Webhook Error: ${err.message}`); } // Process events idempotently switch (event.type) { case 'invoice.payment_succeeded': const invoice = event.data.object as Stripe.Invoice; await activateSubscription(invoice.subscription as string); await sendPaymentConfirmation(invoice.customer as string); break; case 'invoice.payment_failed': const failedInvoice = event.data.object as Stripe.Invoice; await handlePaymentFailure( failedInvoice.subscription as string, failedInvoice.attempt_count ); break; case 'customer.subscription.deleted': const sub = event.data.object as Stripe.Subscription; await deactivateSubscription(sub.id); break; } res.json({ received: true }); }
Subscription Lifecycle
Customer Journey:
Select Plan β Enter Payment β Subscribe β Use Product
β β β β
βΌ βΌ βΌ βΌ
Price lookup Stripe invoice. Active
from catalog Elements payment_ subscription
(client) succeeded
(webhook)
Upgrade β proration calculated β new plan active immediately
Downgrade β applies at period end β old plan until renewal
Cancel β immediate or at period end (configurable)
Failed β retry 3x over 7 days β dunning email β pause/cancel
Configuration
| Option | Type | Default | Description |
|---|---|---|---|
provider | string | "stripe" | Payment provider: stripe, paypal, braintree |
subscriptionModel | string | "recurring" | Model: recurring, metered, usage-based |
proration | string | "always" | Proration: always, create, none |
trialDays | number | 14 | Free trial duration |
retryAttempts | number | 3 | Payment retry attempts before cancellation |
taxCalculation | boolean | true | Enable automatic tax calculation |
Best Practices
-
Never handle raw card data β use Stripe Elements or equivalent β Handling card numbers directly puts you in PCI DSS scope (SAQ D), requiring extensive security audits. Stripe Elements (client-side) tokenizes cards without your server ever seeing the number, keeping you in SAQ A scope, which has minimal compliance requirements.
-
Always verify webhook signatures β Without signature verification, anyone can send fake webhook events to your endpoint, triggering subscription activations or refunds. Use
stripe.webhooks.constructEvent()with your webhook signing secret to verify that events genuinely originated from Stripe. -
Use idempotency keys for all mutation API calls β Network failures can cause your server to retry a payment creation, resulting in double charges. Pass an
idempotency_keyparameter with every Stripe API call that creates or modifies resources. Stripe will return the same result for duplicate requests with the same key. -
Handle payment failures with a dunning sequence β When a subscription payment fails, do not cancel immediately. Retry 3 times over 7 days with email notifications ("Your payment failed, please update your card"). Only pause or cancel after all retries are exhausted. This recovers 30-50% of failed payments.
-
Store subscription state in your database, not just Stripe β While Stripe is the source of truth for payment status, your application needs local state for fast access control checks. Sync subscription status via webhooks and add a background job that reconciles local state with Stripe periodically to catch any missed webhooks.
Common Issues
Webhook events arrive out of order β invoice.payment_succeeded arrives before customer.subscription.created, and your handler fails because the subscription does not exist locally yet. Design webhook handlers to be idempotent and order-independent. If a dependent resource does not exist yet, create it or retry the event processing after a short delay.
Proration calculations confuse customers β A customer upgrades mid-cycle and is charged a prorated amount that does not match their expectation. Display the prorated amount to the user BEFORE they confirm the upgrade using Stripe's upcoming invoice API. Show a clear breakdown: "You'll be charged $12.50 now for the remaining 15 days of this billing period."
Test mode works but live mode fails β Everything works with Stripe test keys, but live payments fail. Common causes: the webhook endpoint URL is still pointing to localhost, the live mode webhook signing secret is different from the test one, or the Stripe account has not completed identity verification. Use Stripe's dashboard to verify live mode webhook delivery and check for failed events.
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
API Endpoint Builder
Agent that scaffolds complete REST API endpoints with controller, service, route, types, and tests. Supports Express, Fastify, and NestJS.
Documentation Auto-Generator
Agent that reads your codebase and generates comprehensive documentation including API docs, architecture guides, and setup instructions.
Ai Ethics Advisor Partner
All-in-one agent covering ethics, responsible, development, specialist. Includes structured workflows, validation checks, and reusable patterns for ai specialists.