# Send Stripe Production Engineering to your agent
Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.
## Fast path
- Download the package from Yavira.
- Extract it into a folder your agent can access.
- Paste one of the prompts below and point your agent at the extracted folder.
## Suggested prompts
### New install

```text
I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete.
```
### Upgrade existing

```text
I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run.
```
## Machine-readable fields
```json
{
  "schemaVersion": "1.0",
  "item": {
    "slug": "afrexai-stripe-production",
    "name": "Stripe Production Engineering",
    "source": "tencent",
    "type": "skill",
    "category": "开发工具",
    "sourceUrl": "https://clawhub.ai/1kalin/afrexai-stripe-production",
    "canonicalUrl": "https://clawhub.ai/1kalin/afrexai-stripe-production",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadUrl": "/downloads/afrexai-stripe-production",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=afrexai-stripe-production",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "packageFormat": "ZIP package",
    "primaryDoc": "SKILL.md",
    "includedAssets": [
      "README.md",
      "SKILL.md"
    ],
    "downloadMode": "redirect",
    "sourceHealth": {
      "source": "tencent",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-05-07T17:22:31.273Z",
      "expiresAt": "2026-05-14T17:22:31.273Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=afrexai-annual-report",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=afrexai-annual-report",
        "contentDisposition": "attachment; filename=\"afrexai-annual-report-1.0.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null
      },
      "scope": "source",
      "summary": "Source download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this source.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/afrexai-stripe-production"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    }
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/afrexai-stripe-production",
    "downloadUrl": "https://openagent3.xyz/downloads/afrexai-stripe-production",
    "agentUrl": "https://openagent3.xyz/skills/afrexai-stripe-production/agent",
    "manifestUrl": "https://openagent3.xyz/skills/afrexai-stripe-production/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/afrexai-stripe-production/agent.md"
  }
}
```
## Documentation

### Stripe Production Engineering

Complete methodology for building, scaling, and operating production Stripe payment systems. From first checkout to enterprise billing at scale.

### Quick Health Check

Run through these 8 signals. Score 1 point each. Below 5 = stop and fix.

✅ Webhook endpoint verified and idempotent
✅ All API calls use idempotency keys
✅ Customer portal enabled for self-service
✅ Stripe Tax or manual tax collection configured
✅ Failed payment retry logic with dunning emails
✅ PCI compliance questionnaire completed (SAQ-A minimum)
✅ Test mode → live mode checklist completed
✅ Monitoring/alerting on payment failures and webhook errors

Score: /8 — Below 5? Fix gaps before adding features.

### Integration Pattern Decision

PatternBest ForComplexityPCI ScopeStripe Checkout (hosted)MVPs, quick launchLowSAQ-A (minimal)Payment Element (embedded)Custom UX, brand controlMediumSAQ-ACard Element (legacy)Existing integrationsMediumSAQ-A-EPDirect APIPlatform/marketplaceHighSAQ-D (avoid)

Decision rule: Start with Checkout. Move to Payment Element only when you have specific UX requirements that Checkout can't solve.

### Billing Model Selection

ModelStripe ProductUse WhenOne-timePayment Links / CheckoutSingle purchases, lifetime dealsRecurring flatSubscriptionsFixed monthly/annual SaaSUsage-basedMetered billingAPI calls, compute, storagePer-seatSubscriptions + quantityTeam/user-based pricingTieredTiered pricingVolume discountsHybridSubscription + usage recordsBase fee + overage

### Project Structure

src/
  payments/
    stripe.config.ts        # Stripe client initialization
    webhooks.handler.ts     # Webhook endpoint + event routing
    checkout.service.ts     # Checkout session creation
    subscription.service.ts # Subscription lifecycle
    customer.service.ts     # Customer CRUD + portal
    invoice.service.ts      # Invoice customization
    tax.service.ts          # Tax calculation
    types.ts                # Shared types
  middleware/
    webhook-verify.ts       # Signature verification middleware

### 7 Architecture Rules

Never trust the client — verify payment status server-side via webhooks, never from redirect URLs
Webhooks are the source of truth — your database updates from webhook events, not API call responses
Idempotency everywhere — every mutating API call gets an idempotency key
One Stripe customer per user — create customer at signup, store stripe_customer_id in your DB
Metadata is your friend — attach user_id, plan, source to every object for debugging
Test mode mirrors live — your test environment should use the exact same code paths
Never store card numbers — use Stripe.js/Elements, never handle raw card data

### Stripe Client Setup

// stripe.config.ts
import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: '2024-12-18.acacia',  // Pin API version!
  maxNetworkRetries: 2,
  timeout: 10_000,
  telemetry: false,
});

export { stripe };

Rules:

Pin API version — never use rolling latest
Set explicit timeout (10s default is fine)
Disable telemetry in production if privacy-sensitive
Use restricted keys with minimum required permissions

### Customer Lifecycle

// customer.service.ts
async function getOrCreateCustomer(userId: string, email: string, name?: string) {
  // Check DB first
  const existing = await db.users.findOne({ id: userId });
  if (existing?.stripeCustomerId) {
    return existing.stripeCustomerId;
  }

  // Create in Stripe
  const customer = await stripe.customers.create({
    email,
    name,
    metadata: {
      user_id: userId,
      created_via: 'signup',
    },
  });

  // Store mapping
  await db.users.update({ id: userId }, { stripeCustomerId: customer.id });
  return customer.id;
}

Customer rules:

Create at signup, not at first purchase
Always set metadata.user_id for reverse lookups
Store stripe_customer_id in your users table
Use customer email updates to sync — listen for customer.updated

### Checkout Session (Recommended Starting Point)

// checkout.service.ts
async function createCheckoutSession(params: {
  customerId: string;
  priceId: string;
  mode: 'payment' | 'subscription';
  successUrl: string;
  cancelUrl: string;
  metadata?: Record<string, string>;
}) {
  const session = await stripe.checkout.sessions.create({
    customer: params.customerId,
    mode: params.mode,
    line_items: [{ price: params.priceId, quantity: 1 }],
    success_url: \`${params.successUrl}?session_id={CHECKOUT_SESSION_ID}\`,
    cancel_url: params.cancelUrl,
    metadata: params.metadata ?? {},

    // Recommended defaults
    allow_promotion_codes: true,
    billing_address_collection: 'auto',
    tax_id_collection: { enabled: true },
    customer_update: { address: 'auto', name: 'auto' },
    payment_method_types: ['card'],
    
    // For subscriptions
    ...(params.mode === 'subscription' && {
      subscription_data: {
        metadata: params.metadata ?? {},
        trial_period_days: 14,
      },
    }),
  }, {
    idempotencyKey: \`checkout_${params.customerId}_${params.priceId}_${Date.now()}\`,
  });

  return session;
}

### Payment Element (Custom UI)

// Server: create PaymentIntent
async function createPaymentIntent(params: {
  customerId: string;
  amount: number;      // in cents!
  currency: string;
  metadata?: Record<string, string>;
}) {
  return stripe.paymentIntents.create({
    customer: params.customerId,
    amount: params.amount,
    currency: params.currency,
    automatic_payment_methods: { enabled: true },
    metadata: {
      ...params.metadata,
      created_at: new Date().toISOString(),
    },
  }, {
    idempotencyKey: \`pi_${params.customerId}_${params.amount}_${Date.now()}\`,
  });
}

// Client: React Payment Element
// <PaymentElement /> handles all payment method rendering
// Use confirmPayment() on form submit

### Subscription Lifecycle Events

Created → Active → Past Due → Canceled → (optionally) Unpaid
                ↓
            Trialing → Active
                ↓
            Paused → Resumed → Active

### Critical Webhook Events for Subscriptions

EventActioncustomer.subscription.createdProvision access, set plan in DBcustomer.subscription.updatedHandle plan changes, quantity updatescustomer.subscription.deletedRevoke access, clean upcustomer.subscription.trial_will_endSend conversion email (3 days before)invoice.payment_succeededConfirm access renewalinvoice.payment_failedStart dunning sequencecustomer.subscription.pausedRestrict access, retain datacustomer.subscription.resumedRestore access

### Plan Change Patterns

// Upgrade (immediate)
async function upgradePlan(subscriptionId: string, newPriceId: string) {
  const sub = await stripe.subscriptions.retrieve(subscriptionId);
  return stripe.subscriptions.update(subscriptionId, {
    items: [{
      id: sub.items.data[0].id,
      price: newPriceId,
    }],
    proration_behavior: 'create_prorations',  // charge difference immediately
    payment_behavior: 'error_if_incomplete',
  });
}

// Downgrade (at period end)
async function downgradePlan(subscriptionId: string, newPriceId: string) {
  const sub = await stripe.subscriptions.retrieve(subscriptionId);
  return stripe.subscriptions.update(subscriptionId, {
    items: [{
      id: sub.items.data[0].id,
      price: newPriceId,
    }],
    proration_behavior: 'none',               // no refund, change at renewal
    billing_cycle_anchor: 'unchanged',
  });
}

// Cancel (at period end — always prefer this)
async function cancelSubscription(subscriptionId: string) {
  return stripe.subscriptions.update(subscriptionId, {
    cancel_at_period_end: true,
  });
  // User keeps access until period ends
  // Handle \`customer.subscription.deleted\` to revoke
}

### Dunning (Failed Payment Recovery)

# Stripe Dashboard → Settings → Subscriptions → Smart Retries
retry_schedule:
  attempt_1: 1 day after failure    # Smart timing
  attempt_2: 3 days after failure
  attempt_3: 5 days after failure
  attempt_4: 7 days after failure   # Final attempt

# Custom dunning emails (supplement Stripe's built-in)
dunning_sequence:
  - day: 0
    action: "Email: payment failed, update card link"
    template: "Your payment of {amount} failed. Update → {portal_url}"
  - day: 3
    action: "Email: second notice, urgency"
    template: "Still unable to charge. Update payment to avoid interruption."
  - day: 5
    action: "Email: final warning"
    template: "Last chance to update. Access pauses in 48 hours."
  - day: 7
    action: "Pause or cancel subscription"
    note: "Automatic via Stripe if all retries fail"

### Usage-Based Billing

// Report usage for metered billing
async function reportUsage(subscriptionItemId: string, quantity: number) {
  return stripe.subscriptionItems.createUsageRecord(subscriptionItemId, {
    quantity,
    timestamp: Math.floor(Date.now() / 1000),
    action: 'increment',  // or 'set' for absolute value
  }, {
    idempotencyKey: \`usage_${subscriptionItemId}_${Date.now()}\`,
  });
}

// Best practice: batch usage reports
// Don't report every API call individually — aggregate per hour/day
// Report at least daily to avoid surprise bills at period end

### Webhook Handler Template

// webhooks.handler.ts
import { stripe } from './stripe.config';
import type { Request, Response } from 'express';

const WEBHOOK_SECRET = process.env.STRIPE_WEBHOOK_SECRET!;

// Event handlers map
const handlers: Record<string, (event: Stripe.Event) => Promise<void>> = {
  'checkout.session.completed': handleCheckoutCompleted,
  'customer.subscription.created': handleSubscriptionCreated,
  'customer.subscription.updated': handleSubscriptionUpdated,
  'customer.subscription.deleted': handleSubscriptionDeleted,
  'invoice.payment_succeeded': handleInvoicePaymentSucceeded,
  'invoice.payment_failed': handleInvoicePaymentFailed,
  'customer.subscription.trial_will_end': handleTrialEnding,
  'payment_intent.succeeded': handlePaymentSucceeded,
  'payment_intent.payment_failed': handlePaymentFailed,
};

export async function handleWebhook(req: Request, res: Response) {
  // 1. Verify signature (NEVER skip this)
  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(
      req.body,        // raw body, not parsed JSON!
      req.headers['stripe-signature']!,
      WEBHOOK_SECRET,
    );
  } catch (err) {
    console.error('Webhook signature verification failed:', err);
    return res.status(400).send('Invalid signature');
  }

  // 2. Idempotency check
  const alreadyProcessed = await db.webhookEvents.findOne({ eventId: event.id });
  if (alreadyProcessed) {
    return res.status(200).json({ received: true, duplicate: true });
  }

  // 3. Route to handler
  const handler = handlers[event.type];
  if (handler) {
    try {
      await handler(event);
      await db.webhookEvents.insert({ eventId: event.id, type: event.type, processedAt: new Date() });
    } catch (err) {
      console.error(\`Webhook handler failed for ${event.type}:\`, err);
      return res.status(500).send('Handler error');  // Stripe will retry
    }
  }

  // 4. Always return 200 quickly
  res.status(200).json({ received: true });
}

### 10 Webhook Rules

Verify every signature — never process unverified events
Use raw body — don't parse JSON before verification (Express: express.raw({type: 'application/json'}))
Idempotency — store processed event IDs, handle duplicates gracefully
Return 200 fast — do heavy processing async/in background
Handle out-of-order — events may arrive in unexpected order; check current state before applying
Don't rely on event data alone — for critical actions, re-fetch the object from the API
Log everything — event ID, type, relevant object IDs, processing result
Monitor failures — alert on repeated 500s or unhandled event types
Use CLI for local dev — stripe listen --forward-to localhost:3000/webhooks
Register only events you handle — don't subscribe to everything

### Essential Events by Use Case

Use CaseMust-Have EventsOne-time paymentscheckout.session.completed, payment_intent.succeeded, payment_intent.payment_failedSubscriptionsAll subscription.* + invoice.payment_succeeded, invoice.payment_failed, invoice.upcomingMarketplace/Connectaccount.updated, payout.paid, payout.failed, transfer.createdInvoicinginvoice.created, invoice.finalized, invoice.paid, invoice.payment_failed

### Phase 5: Customer Portal & Self-Service

// Customer portal — saves you building billing UI
async function createPortalSession(customerId: string, returnUrl: string) {
  return stripe.billingPortal.sessions.create({
    customer: customerId,
    return_url: returnUrl,
  });
}

// Configure in Dashboard → Settings → Customer portal
// Enable: Update payment method, Cancel subscription, View invoices
// Optional: Plan switching, Invoice history download

### Portal Configuration Checklist

Payment method update enabled
 Subscription cancellation with reason collection
 Plan switching with proration preview
 Invoice history visible
 Business information (name, logo) set
 Return URL configured
 Terms of service / privacy policy linked

### Tax Decision Tree

Do you sell to EU customers?
  YES → Need VAT collection
    Use Stripe Tax (automatic) OR manual tax rates
  NO → 
Do you sell to US customers in multiple states?
  YES → Need sales tax (nexus rules)
    Use Stripe Tax (automatic) — manual is nightmare
  NO →
Do you exceed $100K revenue or 200 transactions in any US state?
  YES → You have economic nexus — collect tax
  NO → May not need to collect, but verify with accountant

### Stripe Tax Setup

// Enable automatic tax on Checkout
const session = await stripe.checkout.sessions.create({
  // ... other config
  automatic_tax: { enabled: true },
  customer_update: { address: 'auto' },  // Required for tax calculation
});

// For subscriptions via API
const subscription = await stripe.subscriptions.create({
  customer: customerId,
  items: [{ price: priceId }],
  automatic_tax: { enabled: true },
});

Tax rules:

Stripe Tax handles calculation + collection automatically
You still need to file/remit taxes yourself (or use Stripe Tax filing in supported regions)
Always collect billing address for accurate tax calculation
Enable tax ID collection for B2B reverse charge (EU)

### Connect Account Types

TypeControlOnboardingBest ForStandardLow (Stripe-hosted dashboard)Stripe-hostedMarketplaces where sellers manage their own StripeExpressMedium (limited dashboard)Stripe-hostedPlatforms managing payouts for contractors/sellersCustomFull (you build everything)You build itEnterprise platforms needing total control

Decision rule: Use Express unless you have a specific reason not to.

### Payment Flow Patterns

// Direct charge (platform takes cut)
const paymentIntent = await stripe.paymentIntents.create({
  amount: 10000,  // $100
  currency: 'usd',
  application_fee_amount: 1500,  // $15 platform fee
  transfer_data: {
    destination: 'acct_seller123',
  },
});

// Destination charge (seller's Stripe processes)
// Same as above but payment appears on seller's statement

// Separate charges and transfers (most flexible)
const charge = await stripe.paymentIntents.create({
  amount: 10000,
  currency: 'usd',
});
// Then transfer to seller
const transfer = await stripe.transfers.create({
  amount: 8500,
  currency: 'usd',
  destination: 'acct_seller123',
  transfer_group: 'order_123',
});

### Test Mode Checklist

TestHowPass CriteriaSuccessful paymentCard: 4242424242424242Checkout completes, webhook fires, DB updatedDeclined cardCard: 4000000000000002Error shown, no DB change3D Secure requiredCard: 4000002500003155Auth modal shown, completes afterInsufficient fundsCard: 4000000000009995Graceful failure messageSubscription createUse test price, complete checkoutSub active, access grantedPayment failure + retryAttach 4000000000000341, trigger invoiceDunning sequence firesWebhook replaystripe events resend evt_xxxIdempotent — no duplicate processingRefundRefund via API or DashboardCustomer notified, access handledUpgrade/downgradeChange plan mid-cycleProration correctCancel at period endCancel, verify access until period endAccess maintained, then revoked

### Stripe CLI for Local Development

# Install
brew install stripe/stripe-cli/stripe

# Login
stripe login

# Forward webhooks to local server
stripe listen --forward-to localhost:3000/api/webhooks/stripe

# Trigger specific events for testing
stripe trigger checkout.session.completed
stripe trigger invoice.payment_failed
stripe trigger customer.subscription.deleted

### PCI Compliance Levels

LevelCriteriaRequirementSAQ-ACheckout or Elements (recommended)Annual questionnaire, no scanSAQ-A-EPClient-side tokenizationAnnual questionnaire + quarterly scanSAQ-DDirect API card handling (avoid)Full audit, quarterly scans, penetration tests

### Security Checklist (P0 — Mandatory)

API keys in environment variables, never in code
 Webhook signatures verified on every request
 Restricted API keys with minimum permissions
 HTTPS everywhere (Stripe requires it)
 No card numbers logged, stored, or transmitted
 CSRF protection on payment endpoints
 Rate limiting on checkout creation
 Idempotency keys on all mutating calls

### API Key Strategy

Live mode:
  sk_live_xxx    → Server only, env var, restricted permissions
  pk_live_xxx    → Client-side (public, safe to expose)
  whsec_xxx      → Webhook secret, server only

Test mode:
  sk_test_xxx    → Same restrictions as live
  pk_test_xxx    → Client-side
  whsec_test_xxx → Webhook secret (different from live!)

Restricted key permissions (create in Dashboard → API Keys):

Checkout Sessions: Write
Customers: Write
Subscriptions: Read/Write
Webhook Endpoints: Read
Everything else: None

### Pre-Launch (P0 — Mandatory)

Webhook endpoint registered and verified in live mode
 All webhook events subscribed (same as test)
 Live API keys in production environment
 Customer portal configured with live branding
 Test a real $1 payment end-to-end (then refund)
 Error handling for all payment states (success, failure, pending, requires_action)
 Logging: payment ID, customer ID, amount, status on every transaction
 PCI SAQ-A completed in Stripe Dashboard

### Pre-Launch (P1 — Within First Week)

Monitoring: alert on payment failure rate > 5%
 Monitoring: alert on webhook delivery failures
 Receipt emails configured (Stripe auto-sends or custom)
 Refund process documented
 Dispute/chargeback response process
 Dunning emails active for subscriptions
 Stripe Tax enabled (if applicable)

### Pre-Launch (P2 — Within First Month)

Revenue analytics dashboard
 MRR/churn tracking
 Coupon/promotion code strategy
 Annual vs monthly pricing toggle
 Customer portal self-service verified

### Key Metrics Dashboard

metrics:
  payment_success_rate:
    calculation: "successful_payments / total_attempts × 100"
    healthy: ">= 95%"
    warning: "90-95%"
    critical: "< 90%"
    
  webhook_delivery_rate:
    calculation: "successful_deliveries / total_events × 100"  
    healthy: ">= 99.5%"
    critical: "< 99%"
    
  average_revenue_per_user:
    calculation: "total_revenue / active_customers"
    track: "weekly trend"
    
  monthly_recurring_revenue:
    calculation: "sum(active_subscription_amounts)"
    track: "monthly growth rate"
    
  churn_rate:
    calculation: "canceled_subscriptions / total_active × 100"
    healthy: "< 5% monthly"
    warning: "5-10%"
    critical: "> 10%"
    
  involuntary_churn:
    calculation: "failed_payment_cancellations / total_churn × 100"
    note: "Should be < 30% of total churn — fix with better dunning"

### Weekly Review Checklist

Payment success rate vs last week
 Failed payments — any patterns? (card type, region, amount)
 Webhook failures — any endpoints timing out?
 New disputes/chargebacks — respond within 7 days
 Subscription metrics: new, churned, upgraded, downgraded
 Revenue: MRR, net new MRR, expansion MRR, contraction MRR

### Pricing Page with Annual Toggle

// Create both monthly and annual prices for each plan
const prices = {
  starter: {
    monthly: 'price_starter_monthly',   // $29/mo
    annual: 'price_starter_annual',     // $290/yr (save ~17%)
  },
  pro: {
    monthly: 'price_pro_monthly',       // $79/mo
    annual: 'price_pro_annual',         // $790/yr
  },
};

// Client toggles monthly/annual → creates checkout with correct priceId

### Grandfathering & Price Increases

// New price, existing customers keep old price
// 1. Create new price object (don't modify existing)
// 2. New signups use new price
// 3. Existing subs stay on old price until they change plans
// 4. Optional: scheduled price migration with notice

async function schedulePriceIncrease(subscriptionId: string, newPriceId: string, effectiveDate: Date) {
  // Create a subscription schedule
  const schedule = await stripe.subscriptionSchedules.create({
    from_subscription: subscriptionId,
  });
  
  // Add phase with new price
  await stripe.subscriptionSchedules.update(schedule.id, {
    phases: [
      { items: [{ price: currentPriceId }], end_date: Math.floor(effectiveDate.getTime() / 1000) },
      { items: [{ price: newPriceId }] },
    ],
  });
}

### Coupon & Promotion Codes

// Create coupon (reusable)
const coupon = await stripe.coupons.create({
  percent_off: 20,
  duration: 'repeating',
  duration_in_months: 3,
  max_redemptions: 100,
  metadata: { campaign: 'launch_2024' },
});

// Create promotion code (shareable link)
const promoCode = await stripe.promotionCodes.create({
  coupon: coupon.id,
  code: 'LAUNCH20',
  max_redemptions: 50,
  expires_at: Math.floor(new Date('2024-12-31').getTime() / 1000),
});

### Handling Disputes (Chargebacks)

dispute_response_process:
  when_received:
    - Log dispute details: amount, reason, deadline
    - Alert team immediately
    - Begin evidence collection within 24 hours
    
  evidence_to_collect:
    - Customer communication (emails, chat logs)
    - Delivery proof (access logs, download records)
    - Terms of service acceptance timestamp
    - Refund policy shown at checkout
    - IP address and device fingerprint
    - Prior successful transactions from same customer
    
  submit:
    - Within 7 days (Stripe deadline is usually 21 days, but act fast)
    - Use Stripe Dashboard evidence submission form
    - Include written rebuttal addressing specific reason code
    
  prevention:
    - Clear billing descriptor (customer recognizes charge)
    - Send receipt emails immediately
    - Offer easy refunds before disputes escalate
    - Use Radar for fraud detection

### 10 Common Mistakes

#MistakeFix1Trusting client-side redirect as payment confirmationAlways verify via webhook2Parsing JSON body before webhook signature verificationUse raw body buffer3No idempotency keys on API callsAdd to every mutating call4Immediately canceling instead of cancel_at_period_endAlways cancel at period end unless refunding5Amounts in dollars instead of centsStripe uses smallest currency unit (cents)6Not handling 3D Secure / requires_action statusCheck payment_intent.status, handle authentication7Same webhook secret for test and liveUse separate secrets per environment8Not testing with Stripe CLI locallySet up stripe listen in development9Hardcoding price IDsUse config/env vars, different per environment10No dunning strategy for failed subscription paymentsConfigure Smart Retries + custom emails

### Quality Rubric (0-100)

DimensionWeightCriteriaWebhook reliability25%Signature verification, idempotency, error handling, event coverageSecurity & PCI20%SAQ-A compliance, key management, no card data exposureSubscription lifecycle15%Create/upgrade/downgrade/cancel/pause all handled correctlyCustomer experience15%Portal, receipts, dunning emails, clear error messagesTesting coverage10%All payment states tested, CLI setup, edge casesMonitoring10%Failure alerts, revenue metrics, dispute trackingCode quality5%TypeScript types, error handling, idempotency keys, logging

### Commands

The agent responds to these natural language requests:

"Set up Stripe checkout" → Full Checkout integration with webhook handler
"Add subscriptions" → Subscription lifecycle with plan changes and dunning
"Configure webhooks" → Webhook handler with signature verification and idempotency
"Set up customer portal" → Billing portal configuration
"Add usage-based billing" → Metered subscription with usage reporting
"Stripe security audit" → PCI compliance check + security hardening
"Go-live checklist" → Pre-launch verification for production
"Set up Stripe Connect" → Marketplace/platform payment flows
"Add coupons and promos" → Promotion code system
"Review payment metrics" → Revenue and payment health dashboard
"Handle a dispute" → Chargeback response process
"Migrate pricing" → Grandfathering and price increase strategy
## Trust
- Source: tencent
- Verification: Indexed source record
- Publisher: 1kalin
- Version: 1.0.0
## Source health
- Status: healthy
- Source download looks usable.
- Yavira can redirect you to the upstream package for this source.
- Health scope: source
- Reason: direct_download_ok
- Checked at: 2026-05-07T17:22:31.273Z
- Expires at: 2026-05-14T17:22:31.273Z
- Recommended action: Download for OpenClaw
## Links
- [Detail page](https://openagent3.xyz/skills/afrexai-stripe-production)
- [Send to Agent page](https://openagent3.xyz/skills/afrexai-stripe-production/agent)
- [JSON manifest](https://openagent3.xyz/skills/afrexai-stripe-production/agent.json)
- [Markdown brief](https://openagent3.xyz/skills/afrexai-stripe-production/agent.md)
- [Download page](https://openagent3.xyz/downloads/afrexai-stripe-production)