Skill: ivangdavila/payments (version 1.0.0)

--- name: Payments description: Integrate payments with provider selection, checkout flows, subscription billing, and security best practices. --- ## Situation Detection | Context | Load | |---------|------| | Choosing Stripe vs Paddle vs LemonSqueezy | `providers.md` | | Implementing checkout, webhooks, refunds | `integration.md` | | Subscription billing, trials, upgrades | `subscriptions.md` | | PCI compliance, fraud prevention | `security.md` | --- ## Universal Rules **Never store card data.** Use provider-hosted checkout or tokenization. PCI compliance burden explodes the moment raw card numbers touch your server. **Webhooks are truth.** Client-side success callbacks lie. A payment succeeded only when your webhook confirms it. Design for webhook-first verification. **Test mode exists for a reason.** Use test cards, simulate failures, verify webhook handling. Production surprises cost real money and real customers. **Pricing psychology:** $9.99/mo feels cheaper than $120/year, but annual retention is 2-3x higher. Default to annual with monthly option, not the reverse. --- ## Provider Quick Compare | Need | Recommendation | |------|----------------| | US/global B2C | Stripe (best docs, widest coverage) | | SaaS selling to EU (VAT headache) | Paddle, LemonSqueezy (merchant of record) | | Simple product, no dev resources | Gumroad, Lemonsqueezy hosted | | Marketplace with splits | Stripe Connect | | High-risk or adult | Specialized processors (CCBill, Epoch) | See `providers.md` for detailed comparison. --- ## Integration Checklist Before going live: - [ ] Webhook endpoint secured and verified - [ ] Idempotency keys on all charges - [ ] Failure states handled (declined, expired, insufficient) - [ ] Receipts and invoices configured - [ ] Refund flow tested - [ ] Subscription lifecycle events handled (upgrade, downgrade, cancel) - [ ] Currency handling explicit (store in cents/smallest unit) --- ## Red Flags - Storing CVV anywhere, ever → Instant PCI violation - Trusting client-side payment confirmation → Fraud vector - No retry logic for failed webhooks → Lost transactions - Hardcoding prices in frontend → Easy manipulation - Missing `cancel_at_period_end` handling → Angry customers --- ## When to Load More | Situation | Reference | |-----------|-----------| | Evaluating payment processors | `providers.md` | | Building checkout, handling webhooks | `integration.md` | | Recurring billing, metering, trials | `subscriptions.md` | | Fraud, PCI, chargebacks | `security.md` |

path: integration.md
content: # Payment Integration Patterns

## Checkout Flow Options

### Hosted Checkout (Recommended for most)
Provider handles the payment form. You redirect to their page.
- **Stripe:** Checkout Sessions
- **Paddle:** Paddle.js overlay or redirect
- **LemonSqueezy:** Hosted checkout links

**Pros:** PCI compliant by default, less code, provider handles UX
**Cons:** Less brand control, redirect can lose conversions

### Embedded Elements
Payment form embedded in your site using provider components.
- **Stripe:** Payment Element, Card Element
- **Paddle:** Paddle.js inline

**Pros:** Seamless UX, stays on your site
**Cons:** More integration work, still need to handle states

### Custom Form (Avoid unless required)
You build the form, tokenize via provider SDK.
- Only if you have specific UX requirements
- More PCI responsibility
- More things to break

---

## Webhook Architecture

**Webhooks are the source of truth.** Don't trust client-side callbacks.

### Essential Webhooks to Handle

| Event | Action |
|-------|--------|
| `payment_intent.succeeded` | Fulfill order, grant access |
| `payment_intent.payment_failed` | Notify user, retry logic |
| `invoice.paid` | Update subscription status |
| `customer.subscription.updated` | Handle plan changes |
| `customer.subscription.deleted` | Revoke access |
| `charge.refunded` | Reverse fulfillment |
| `charge.dispute.created` | Alert team, gather evidence |

### Webhook Security

```plaintext
1. Verify webhook signature (provider-specific)
2. Use HTTPS endpoint
3. Return 200 quickly, process async if slow
4. Implement idempotency (handle duplicate events)
5. Log raw payloads for debugging
```

### Webhook Failure Handling

Providers retry failed webhooks. Your endpoint must be:
- Idempotent (same event processed twice = same result)
- Fast (return 200 within 5-30 seconds)
- Resilient (queue for async processing if needed)

---

## Currency and Amount Handling

**Always store amounts in smallest unit (cents, pence).**

```plaintext
✅ $10.00 = 1000 (cents)
✅ €25.50 = 2550 (cents)
❌ $10.00 = 10.00 (floating point disasters)
```

**Display vs Storage:**
- Store: 1000 (integer, cents)
- Display: $10.00 (formatted for user)
- Never calculate on floating point prices

---

## Idempotency

**Every charge request must include an idempotency key.**

Without idempotency:
- Network timeout → You don't know if charge succeeded
- Retry → Possible double charge
- Angry customer + chargeback

With idempotency:
- Same key = same result (no duplicate charges)
- Safe to retry on any failure

```plaintext
Key format: "{order_id}_{timestamp}" or UUID
Store with order to prevent reuse
```

---

## Error Handling

| Error Type | User Action | Your Action |
|------------|-------------|-------------|
| Card declined | Try different card | Log, show clear error |
| Insufficient funds | Try different card | Same as declined |
| Expired card | Update card | Prompt card update |
| Fraud suspected | Contact bank | Block + manual review |
| Processing error | Retry | Retry with backoff, alert if persistent |

**Never expose raw error codes to users.** Map to friendly messages:
- "Your card was declined" not "card_declined"
- "Please try again" not "processing_error"

---

## Testing Checklist

- [ ] Successful payment flow (happy path)
- [ ] Declined card handling
- [ ] Webhook receives and processes events
- [ ] Duplicate webhook handling (idempotency)
- [ ] Refund flow works correctly
- [ ] 3D Secure flow (if applicable)
- [ ] Currency edge cases (JPY has no cents)
- [ ] Cancellation and proration


path: providers.md
content: # Payment Providers Comparison

## Full-Service Processors

### Stripe
- **Best for:** Developers, US/global B2C, marketplaces
- **Fees:** 2.9% + $0.30 (US), varies by country
- **Pros:** Best docs, widest payment method support, Stripe Connect for marketplaces
- **Cons:** You handle tax compliance, higher fees for international
- **Merchant of Record:** No (you're the seller)

### Paddle
- **Best for:** SaaS selling globally, avoiding tax complexity
- **Fees:** 5% + $0.50 per transaction
- **Pros:** Handles VAT/GST, chargebacks, invoicing. You're not the merchant.
- **Cons:** Higher fees, less control, slower payouts
- **Merchant of Record:** Yes (they're the seller, you're the vendor)

### LemonSqueezy
- **Best for:** Indie hackers, digital products, simple setup
- **Fees:** 5% + $0.50
- **Pros:** Beautiful checkout, handles taxes, simple dashboard
- **Cons:** Fewer features than Stripe, limited customization
- **Merchant of Record:** Yes

### PayPal
- **Best for:** User trust, older demographics, some regions
- **Fees:** 2.9% + $0.30 (varies)
- **Pros:** Brand recognition, buyer protection, easy disputes
- **Cons:** Account freezes, poor developer experience, dated UX
- **Merchant of Record:** Depends on integration type

---

## Decision Framework

**You should use Stripe if:**
- You want maximum control and customization
- Your team can handle tax compliance (or use Stripe Tax)
- You need Stripe Connect for marketplace splits
- Developer experience matters

**You should use Paddle/LemonSqueezy if:**
- Selling to EU and don't want VAT headaches
- Small team, no finance/legal resources
- Digital products (software, ebooks, courses)
- Want someone else to handle chargebacks

**You should offer PayPal alongside primary processor if:**
- Selling to demographics that trust PayPal
- High cart abandonment without PayPal option
- Markets where PayPal dominates (Germany, some LATAM)

---

## Fee Comparison (Example: $100 charge)

| Provider | Fee | You Keep |
|----------|-----|----------|
| Stripe | $3.20 | $96.80 |
| Paddle | $5.50 | $94.50 |
| LemonSqueezy | $5.50 | $94.50 |
| PayPal | $3.20 | $96.80 |

*Merchant of Record providers are more expensive but include tax handling, invoicing, and chargeback protection.*

---

## Local Payment Methods

Not everyone uses cards. Consider:
- **EU:** SEPA, iDEAL (Netherlands), Bancontact (Belgium), Sofort (Germany)
- **Brazil:** Boleto, Pix
- **Asia:** Alipay, WeChat Pay, GrabPay
- **Crypto:** Coinbase Commerce, BitPay (niche, but growing)

Stripe supports most of these. Research your target market.

---

## High-Risk Industries

Standard processors reject:
- Adult content
- CBD/cannabis
- Gambling
- Firearms
- Nutraceuticals

Specialized processors: CCBill, Epoch, Segpay, Durango Merchant Services.

Expect 5-10% fees, rolling reserves, and slower approvals.


path: security.md
content: # Payment Security

## PCI Compliance Basics

**PCI DSS** = Payment Card Industry Data Security Standard. Required if you handle card data.

### Compliance Levels

| Level | Criteria | Requirements |
|-------|----------|--------------|
| SAQ-A | Hosted checkout, no card data touches your server | Self-assessment questionnaire |
| SAQ-A-EP | Embedded elements, card data in your page (tokenized) | Longer questionnaire |
| SAQ-D | Full card processing on your server | Full audit, very expensive |

**Stay at SAQ-A if possible.** Use hosted checkout or provider elements.

### What You Must Never Do

❌ Store CVV/CVC (ever, anywhere, for any reason)
❌ Log full card numbers
❌ Store unencrypted card data
❌ Transmit card data without TLS
❌ Give developers access to production card data

### What You Should Do

✅ Use provider's hosted fields or checkout
✅ Tokenize immediately (card → token → charge token)
✅ Serve payment pages over HTTPS only
✅ Monitor for suspicious patterns
✅ Keep payment logic isolated from main codebase

---

## Fraud Prevention

### Red Flags

| Signal | Risk Level |
|--------|------------|
| Mismatched billing/shipping address | Medium |
| Free email with high-value order | Medium |
| Multiple failed attempts, then success | High |
| VPN/proxy from high-risk country | High |
| Velocity (many orders in short time) | High |
| Address verification failed (AVS) | Medium |
| CVC mismatch | High |

### Tools

- **Stripe Radar:** Built-in ML fraud detection
- **Sift:** Third-party fraud platform
- **Manual review:** Flag high-value or suspicious orders

### 3D Secure (3DS)

Extra authentication step ("Verified by Visa", "Mastercard SecureCode").

**Pros:**
- Liability shift to bank (you win chargebacks)
- Reduces fraud significantly

**Cons:**
- Adds friction (conversion drop 5-15%)
- Not all cards support it

**Recommendation:** Enable for high-risk transactions, new customers, high-value orders.

---

## Chargebacks

Customer disputes charge with their bank. You lose money + $15-25 fee.

### Chargeback Reasons

| Reason | What Happened |
|--------|---------------|
| Fraudulent | Stolen card used |
| Product not received | Delivery failed or claimed failed |
| Product not as described | Expectation mismatch |
| Duplicate | Charged twice |
| Subscription not canceled | User claims they canceled |

### Prevention

- Clear billing descriptor (customer recognizes charge)
- Delivery confirmation with signature
- Clear refund policy
- Easy cancellation process
- Proactive customer service

### Fighting Chargebacks

You can submit evidence to dispute:
- Proof of delivery
- Customer communication
- Terms of service acceptance
- Usage logs (for digital products)
- 3DS authentication proof

Win rates vary: ~30% for physical goods, ~50% for digital with good evidence.

---

## Refund Best Practices

**When to refund (no questions):**
- Within your stated refund window
- Duplicate charge
- Product genuinely not delivered

**When to partial refund:**
- Service partially rendered
- Usage occurred but customer unhappy

**When to deny:**
- Outside refund window with clear policy
- Obvious abuse pattern
- Fraud attempt

**Process:**
1. Refund via provider dashboard/API (not by creating negative charge)
2. Transaction fees usually not refunded to you
3. Document reason for records

---

## Data Protection

### What to Store

✅ Customer ID (provider's, not yours)
✅ Subscription status
✅ Payment method type (last 4 digits okay for display)
✅ Invoice/receipt links

### What Never to Store

❌ Full card numbers
❌ CVV/CVC
❌ Expiration dates (if not tokenized)
❌ PIN numbers
❌ Sensitive authentication data

### Encryption

- TLS 1.2+ for all payment pages
- Encrypt payment tokens at rest
- Separate database for payment data (if applicable)
- Audit access logs regularly

---

## Incident Response

If you suspect a breach:

1. **Contain:** Disable affected systems immediately
2. **Assess:** What data was exposed? Card data? Tokens only?
3. **Notify:** Provider (they may help), legal counsel
4. **Report:** PCI council if card data exposed, potentially customers
5. **Remediate:** Fix vulnerability, rotate keys
6. **Document:** Timeline, actions taken, improvements

**Card data breach = mandatory reporting and potential fines.** Another reason to never touch raw card data.


path: subscriptions.md
content: # Subscription Billing

## Billing Models

### Flat-Rate
Fixed price per period. Simple to implement and understand.
- $10/month for Pro
- $99/year for Premium
- Best for: Most SaaS, clear value proposition

### Tiered / Volume
Price changes based on usage tiers.
- 0-100 users: $50/mo
- 101-500 users: $200/mo
- 501+: $500/mo
- Best for: Collaboration tools, seat-based products

### Usage-Based / Metered
Pay for what you use.
- $0.01 per API call
- $0.10 per GB stored
- Best for: APIs, infrastructure, variable workloads
- Harder to predict revenue

### Hybrid
Base fee + usage.
- $50/mo + $0.01 per additional request
- Best for: Predictable base revenue with upside

---

## Trial Strategies

### Free Trial (Card Required)
- Higher conversion (they're committed)
- Some users won't start (friction)
- Easy chargeback if they forget

### Free Trial (No Card)
- More signups, lower conversion
- Requires good trial-to-paid nurture
- Common for enterprise sales

### Freemium
- Free tier forever, paid for more
- Best for products with viral/network effects
- Can cannibalize paid if free is too generous

**Trial length:** 7 days for simple products, 14-30 for complex. Don't default to 30 — shorter trials create urgency.

---

## Subscription Lifecycle Events

| Event | Handle By |
|-------|-----------|
| Trial started | Send onboarding sequence |
| Trial ending (3 days) | Remind to upgrade |
| Trial ended, no conversion | Offer extension or discount |
| Subscription activated | Send welcome, confirm access |
| Payment failed | Dunning sequence (emails + retries) |
| Plan upgraded | Prorate immediately |
| Plan downgraded | Apply at period end |
| Subscription canceled | Ask why, confirm end date |
| Subscription ended | Revoke access, offer win-back |

---

## Dunning (Failed Payment Recovery)

When a card fails, you have ~30 days before giving up.

**Standard Dunning Sequence:**
1. Day 0: Auto-retry, email "payment failed, updating card?"
2. Day 3: Retry, email with warning
3. Day 7: Retry, email "access at risk"
4. Day 14: Final retry, "account suspended tomorrow"
5. Day 15+: Suspend access, keep trying weekly
6. Day 30: Cancel subscription

**Involuntary churn (failed cards) is 20-40% of all churn.** Good dunning recovers 50%+ of these.

---

## Proration

When users upgrade/downgrade mid-cycle:

**Upgrade:** Charge difference immediately (or at next billing).
**Downgrade:** Credit remaining value, apply at period end.

Most providers handle this automatically. Verify behavior in test mode.

---

## Cancellation Flow

**Don't make it hard to cancel.** Dark patterns create chargebacks and bad reviews.

**Do:**
- Clear "Cancel Subscription" in settings
- Confirm cancel date (end of period, not immediate)
- Offer pause or downgrade as alternatives
- Exit survey (why leaving?)

**Don't:**
- Hidden cancel behind "contact support"
- Immediate access revocation
- Guilt-trip copy ("Your data will be deleted forever!")

---

## Metrics to Track

| Metric | What It Tells You |
|--------|-------------------|
| MRR | Monthly recurring revenue |
| Churn Rate | % of subscribers lost per period |
| LTV | Lifetime value per customer |
| CAC | Cost to acquire customer |
| LTV:CAC | Ratio (3:1+ is healthy) |
| Net Revenue Retention | Expansion - Churn (>100% = growth without new customers) |
| Trial-to-Paid Conversion | % of trials that convert |

---

## Common Mistakes

- **No grace period:** Suspend access immediately on failed payment = angry users
- **No dunning:** One email isn't enough. Keep trying.
- **Prorating wrong:** User pays $100/year, upgrades month 2 to $200 plan — they owe $91.67, not $100
- **Offering only monthly:** Annual plans have 2-3x retention. Always offer both.
- **Ignoring timezone:** "End of day" is different in SF and Singapore. Use UTC or explicit timestamps.


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)