Integrating Payment Processing

Learn how to integrate payment processing with AgencyOS - from one-time payments to subscriptions, webhooks, and revenue optimization.

Overview

Goal: Implement secure payment processing with provider integration Time: 25-50 minutes (vs 5-10 hours manually) Agents Used: planner, researcher, tester, code-reviewer Commands: /integrate

, /integrate
, /cook, /test

Prerequisites

  • Existing application with user accounts
  • Payment provider account (Stripe, Polar, etc.)
  • SSL certificate (required for payments)
  • Business/tax information configured

Payment Providers

ProviderBest ForFeaturesSetup Time
StripeGlobal, feature-richCards, wallets, subscriptions20-30 min
PolarCreator economySubscriptions, products15-25 min
PayPalGlobal recognitionCards, PayPal balance20-30 min
SePayVietnam marketBank transfer, e-wallets15-20 min
SquareIn-person + onlinePOS integration25-35 min

Step-by-Step Workflow

Step 1: Choose Payment Provider

Select provider based on your needs:

# For SaaS subscriptions
/plan [integrate Stripe for subscription billing]

# For creator platforms
/integrate:polar

# For Vietnamese market
/integrate:sepay

# For general e-commerce
/plan [integrate Stripe with PayPal fallback]

Step 2: Integrate Stripe (Most Common)

/cook [integrate Stripe payment processing with one-time and subscription payments]

Implementation:

[1/8] Setting up Stripe...
  āœ“ Installed Stripe SDK
  āœ“ Created Stripe configuration
  āœ“ Added API keys to environment

[2/8] Database changes...
  āœ“ Created Payment model
  āœ“ Created Subscription model
  āœ“ Added stripeCustomerId to User
  āœ“ Migrations generated

[3/8] Payment endpoints...
  āœ“ POST /api/payments/create-intent
  āœ“ POST /api/payments/confirm
  āœ“ GET /api/payments/:id
  āœ“ GET /api/payments/history

[4/8] Subscription endpoints...
  āœ“ POST /api/subscriptions/create
  āœ“ POST /api/subscriptions/cancel
  āœ“ POST /api/subscriptions/update
  āœ“ GET /api/subscriptions/current

[5/8] Webhook handling...
  āœ“ POST /api/webhooks/stripe
  āœ“ Signature verification
  āœ“ Event processing
  āœ“ Idempotency handling

[6/8] Frontend components...
  āœ“ Payment form component
  āœ“ Stripe Elements integration
  āœ“ Subscription management UI
  āœ“ Payment history display

[7/8] Testing...
  āœ“ Payment flow tests (24 tests)
  āœ“ Webhook tests (16 tests)
  āœ“ Subscription tests (18 tests)

[8/8] Documentation...
  āœ“ Payment integration guide
  āœ“ Webhook setup instructions
  āœ“ Testing guide

āœ… Stripe integration complete

Configuration needed (.env):
STRIPE_SECRET_KEY=sk_test_...
STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...

Generated files:

src/
ā”œā”€ā”€ services/
│   ā”œā”€ā”€ stripe.service.js
│   ā”œā”€ā”€ payment.service.js
│   └── subscription.service.js
ā”œā”€ā”€ routes/
│   ā”œā”€ā”€ payment.routes.js
│   ā”œā”€ā”€ subscription.routes.js
│   └── webhook.routes.js
ā”œā”€ā”€ models/
│   ā”œā”€ā”€ Payment.js
│   └── Subscription.js
ā”œā”€ā”€ middleware/
│   ā”œā”€ā”€ stripe-webhook.middleware.js
│   └── payment-auth.middleware.js
└── utils/
    └── stripe-helpers.js

frontend/
ā”œā”€ā”€ components/
│   ā”œā”€ā”€ PaymentForm.tsx
│   ā”œā”€ā”€ SubscriptionCard.tsx
│   └── PaymentHistory.tsx

Step 3: Implement One-Time Payments

# Already done in Step 2, but can add specific features
/cook [add invoice generation for one-time payments]

Payment flow:

// Frontend
const handlePayment = async (amount, currency) => {
  // 1. Create payment intent
  const { clientSecret } = await fetch('/api/payments/create-intent', {
    method: 'POST',
    body: JSON.stringify({ amount, currency })
  }).then(r => r.json());

  // 2. Confirm with Stripe Elements
  const { error, paymentIntent } = await stripe.confirmCardPayment(
    clientSecret,
    { payment_method: { card: cardElement } }
  );

  // 3. Handle result
  if (error) {
    showError(error.message);
  } else if (paymentIntent.status === 'succeeded') {
    showSuccess('Payment successful!');
  }
};

Step 4: Implement Subscriptions

/cook [implement subscription tiers with monthly and annual billing]

Implementation:

[1/5] Subscription plans...
  āœ“ Created plan configuration
  āœ“ Synced with Stripe products
  āœ“ Price IDs configured

Plans created:
- Starter: $9/month or $90/year
- Pro: $29/month or $290/year
- Enterprise: $99/month or $990/year

[2/5] Subscription flow...
  āœ“ Plan selection UI
  āœ“ Subscription creation
  āœ“ Trial period support (14 days)
  āœ“ Proration handling

[3/5] Billing management...
  āœ“ Update payment method
  āœ“ Change plan (upgrade/downgrade)
  āœ“ Cancel subscription
  āœ“ Reactivate subscription

[4/5] Usage tracking...
  āœ“ Feature access control
  āœ“ Usage limits enforcement
  āœ“ Overage handling

[5/5] Testing...
  āœ“ Subscription tests (22 tests)

āœ… Subscriptions implemented

Step 5: Set Up Webhooks

Webhooks are critical for payment processing:

/cook [implement comprehensive Stripe webhook handling]

Webhook events handled:

āœ“ payment_intent.succeeded
  - Mark payment as successful
  - Grant access to product/service
  - Send confirmation email

āœ“ payment_intent.payment_failed
  - Notify user of failure
  - Log for investigation
  - Retry if temporary failure

āœ“ customer.subscription.created
  - Activate subscription
  - Grant feature access
  - Send welcome email

āœ“ customer.subscription.updated
  - Update subscription status
  - Adjust feature access
  - Handle plan changes

āœ“ customer.subscription.deleted
  - Deactivate subscription
  - Remove feature access
  - Send cancellation email

āœ“ invoice.payment_succeeded
  - Mark invoice as paid
  - Extend subscription period
  - Send receipt

āœ“ invoice.payment_failed
  - Notify user
  - Attempt retry
  - Suspend after final failure

āœ“ checkout.session.completed
  - Process successful checkout
  - Create customer record
  - Send confirmation

Webhook security:

// Verify webhook signature
const verifyWebhook = (req) => {
  const signature = req.headers['stripe-signature'];
  const event = stripe.webhooks.constructEvent(
    req.body,
    signature,
    process.env.STRIPE_WEBHOOK_SECRET
  );
  return event;
};

Step 6: Add Payment Methods

/cook [add support for multiple payment methods - cards, Apple Pay, Google Pay]

Implementation:

[1/4] Payment methods...
  āœ“ Credit/debit cards (Visa, MC, Amex)
  āœ“ Apple Pay integration
  āœ“ Google Pay integration
  āœ“ Link (Stripe's payment method)

[2/4] Payment method management...
  āœ“ Save cards for future use
  āœ“ Multiple cards per customer
  āœ“ Default payment method
  āœ“ Remove payment methods

[3/4] Checkout optimization...
  āœ“ Auto-detect payment method
  āœ“ One-click checkout
  āœ“ Remember me option

[4/4] Testing...
  āœ“ Payment method tests (14 tests)

āœ… Multiple payment methods added

Step 7: Implement Polar (for Creators)

/integrate:polar

Implementation:

[1/6] Polar setup...
  āœ“ Installed Polar SDK
  āœ“ Created Polar configuration
  āœ“ Connected to Polar API

[2/6] Product management...
  āœ“ Digital products
  āœ“ Subscriptions
  āœ“ One-time purchases
  āœ“ Tiered pricing

[3/6] Checkout flow...
  āœ“ Polar Checkout integration
  āœ“ Embedded checkout option
  āœ“ Custom success pages

[4/6] Webhook handling...
  āœ“ order.created event
  āœ“ subscription.created event
  āœ“ subscription.updated event
  āœ“ refund.created event

[5/6] Customer portal...
  āœ“ Subscription management
  āœ“ Invoice history
  āœ“ Update payment method

[6/6] Testing...
  āœ“ Polar integration tests (18 tests)

āœ… Polar integration complete

Configuration (.env):
POLAR_ACCESS_TOKEN=polar_...
POLAR_WEBHOOK_SECRET=whsec_...

Step 8: Add Vietnamese Payment (SePay)

/integrate:sepay

Implementation:

[1/5] SePay integration...
  āœ“ Bank transfer payments
  āœ“ E-wallet support (Momo, ZaloPay)
  āœ“ QR code generation
  āœ“ Transaction verification

[2/5] Payment flow...
  āœ“ Create payment request
  āœ“ Display QR code
  āœ“ Poll for payment status
  āœ“ Auto-confirm on payment

[3/5] Webhook handling...
  āœ“ Payment confirmed webhook
  āœ“ Transaction updates
  āœ“ Refund notifications

[4/5] Vietnamese localization...
  āœ“ VND currency support
  āœ“ Vietnamese language UI
  āœ“ Local payment methods

[5/5] Testing...
  āœ“ SePay tests (12 tests)

āœ… SePay integration complete

Step 9: Add Revenue Optimization

Coupon/Discount System

/cook [implement coupon and discount code system]

Abandoned Cart Recovery

/cook [add abandoned checkout email automation]

Upsell/Cross-sell

/cook [implement checkout upsells and product recommendations]

Tax Calculation

/cook [add automatic tax calculation with TaxJar integration]

Step 10: Analytics and Reporting

/cook [implement payment analytics dashboard]

Analytics features:

āœ“ Revenue metrics (MRR, ARR)
āœ“ Subscription metrics (churn, LTV)
āœ“ Payment success rates
āœ“ Failed payment analysis
āœ“ Revenue forecasting
āœ“ Customer lifetime value
āœ“ Cohort analysis
āœ“ Geographic revenue breakdown

Step 11: Testing Payments

/test

Test coverage:

āœ“ Unit Tests (46 tests)
  āœ“ Payment intent creation (8 tests)
  āœ“ Subscription logic (12 tests)
  āœ“ Webhook processing (16 tests)
  āœ“ Coupon validation (10 tests)

āœ“ Integration Tests (38 tests)
  āœ“ End-to-end payment flows (14 tests)
  āœ“ Subscription lifecycle (12 tests)
  āœ“ Refund processing (6 tests)
  āœ“ Multiple payment methods (6 tests)

āœ“ Security Tests (12 tests)
  āœ“ Webhook signature verification (4 tests)
  āœ“ Payment authorization (4 tests)
  āœ“ Idempotency (4 tests)

Tests: 96 passed, 96 total
Coverage: 92.4%

āœ… All payment tests passed

Manual testing with test cards:

# Stripe test cards
4242 4242 4242 4242  # Success
4000 0000 0000 9995  # Decline
4000 0000 0000 3220  # 3D Secure

# Test in Stripe Dashboard
# Monitor webhook delivery
# Verify payment flow

Step 12: Deploy to Production

# Switch to production keys
# Update .env
STRIPE_SECRET_KEY=sk_live_...
STRIPE_PUBLISHABLE_KEY=pk_live_...

# Deploy
/cook [deploy payment integration to production with security review]

Complete Example: SaaS Subscription Platform

Requirements

Implement payment system for SaaS platform:
- Three subscription tiers
- Monthly and annual billing
- 14-day free trial
- Usage-based add-ons
- Team billing
- Invoice generation
- Automatic tax calculation
- Multiple payment methods
- Dunning management (failed payments)

Implementation

# Plan implementation
/plan [design payment system for SaaS with all requirements]

# Integrate Stripe (use /code since plan exists)
/code @plans/payment-system.md

# Subscription tiers
/cook [create three subscription tiers with feature gates]

# Free trial
/cook [implement 14-day free trial without requiring payment method]

# Usage billing
/cook [add usage-based billing for API calls]

# Team billing
/cook [implement team billing with seat management]

# Invoicing
/cook [add automatic invoice generation and email delivery]

# Tax calculation
/cook [integrate TaxJar for automatic tax calculation]

# Payment methods
/cook [add card, Apple Pay, Google Pay, and ACH support]

# Dunning
/cook [implement smart retry logic for failed payments]

# Test everything
/test

# Deploy
/cook [deploy to production with monitoring]

Time Comparison

Manual implementation: 8-14 hours

  • Stripe integration: 2-3 hours
  • Subscription logic: 2-3 hours
  • Webhooks: 2-3 hours
  • UI components: 1-2 hours
  • Testing: 1-2 hours
  • Debugging: 1-2 hours

With AgencyOS: 48 minutes

  • Planning: 6 minutes
  • Stripe setup: 15 minutes
  • Subscriptions: 12 minutes
  • Webhooks: 8 minutes
  • Testing: 7 minutes

Time saved: 7-13 hours (88% faster)

Payment Patterns

Pattern 1: Freemium Model

/cook [implement freemium model with upgrade prompts]

Pattern 2: Pay-What-You-Want

/cook [add pay-what-you-want pricing with suggested amounts]

Pattern 3: Tiered Pricing

/cook [implement dynamic tiered pricing based on usage]

Pattern 4: Marketplace Payments

/cook [implement marketplace payments with split payouts using Stripe Connect]

Best Practices

1. Idempotency

// Ensure operations are idempotent
const createPayment = async (idempotencyKey, data) => {
  return stripe.paymentIntents.create(data, {
    idempotencyKey
  });
};

2. Webhook Retry Logic

// Handle webhook retries gracefully
const processWebhook = async (event) => {
  // Check if already processed
  const existing = await Webhook.findOne({
    eventId: event.id
  });

  if (existing) {
    return { status: 'already_processed' };
  }

  // Process and save
  await processEvent(event);
  await Webhook.create({ eventId: event.id });
};

3. Failed Payment Handling

/cook [implement dunning management with smart retry and email notifications]

4. PCI Compliance

āœ“ Never store card details
āœ“ Use Stripe Elements (PCI-compliant)
āœ“ Tokenize payment info
āœ“ HTTPS everywhere
āœ“ Regular security audits

5. Transaction Monitoring

/cook [add fraud detection and transaction monitoring]

Troubleshooting

Issue: Webhook Not Receiving Events

Solution:

# Test webhook locally with Stripe CLI
stripe listen --forward-to localhost:3000/api/webhooks/stripe

# Or fix with AgencyOS
/fix:fast [Stripe webhooks not being received]

Issue: Payment Failing

Solution:

/fix:logs [analyze payment failure logs and fix issues]

Issue: Double Charging

Solution:

/fix:fast [prevent double charging with idempotency keys]

Issue: Tax Calculation Wrong

Solution:

/fix:fast [tax calculation incorrect for Canadian customers]

Security Checklist

Before production:

āœ“ Using production API keys
āœ“ Webhook signatures verified
āœ“ HTTPS enforced
āœ“ No card data stored
āœ“ Stripe Elements used (PCI compliant)
āœ“ Idempotency keys implemented
āœ“ Rate limiting on payment endpoints
āœ“ Transaction logging enabled
āœ“ Fraud detection configured
āœ“ 3D Secure enabled for EU
āœ“ Refund policy documented
āœ“ Terms of service updated
āœ“ Privacy policy includes payment info
āœ“ GDPR compliance for EU customers
āœ“ Error messages don't leak info
āœ“ Audit logging enabled
āœ“ Failed payment retry logic
āœ“ Customer dispute handling process

Next Steps

Further Reading


Key Takeaway: AgencyOS enables rapid payment integration with built-in security, webhook handling, and best practices - from simple one-time payments to complex subscription systems in under an hour.