# External Integration Pattern

**Pattern Type**: External Integration
**Confidence**: 0.90
**Expected Complexity**: 7.5-9.0

## Pattern Characteristics

This directive matches the **External Integration** pattern because it involves:

1. **Third-party API** (Stripe payment processing)
2. **Webhook handling** (payment events)
3. **Multiple failure modes** (payment failures, network errors, API downtime)
4. **State synchronization** (Stripe state vs local database)
5. **Security concerns** (API keys, webhook signatures)
6. **Retry logic** (failed payment handling)

## Expected Systems

- **API Layer**: Checkout endpoints, payment flow
- **Webhook Handler**: Stripe event processing
- **Database**: Payment metadata, subscription state
- **Admin UI**: Subscription management dashboard
- **Background Jobs**: Payment retry logic

## Expected Modifiers

- **External API**: High (Stripe SDK integration)
- **Error Handling**: High (network failures, payment failures, API errors)
- **State Coordination**: High (sync Stripe state with local DB)
- **Security**: High (API keys, webhook signature verification)

## Recommended Splitting

### Ternary Split (3 children)

**Recommended for clean separation of payment flow stages**:

```
Parent: Stripe Payment Integration
├── Child 0: Checkout Flow - Frontend & API
│   ├── Checkout page UI (plan selection)
│   ├── Stripe Checkout Session creation
│   ├── Success/cancel redirect handlers
│   └── Client-side integration tests
├── Child 1: Webhook Processing - Event Handlers
│   ├── Webhook endpoint (/webhooks/stripe)
│   ├── Signature verification
│   ├── Event handlers (payment_intent.succeeded, etc.)
│   ├── Database updates (subscription state)
│   └── Idempotency handling
└── Child 2: Admin & Retry - Management Interface
    ├── Admin dashboard (subscription list)
    ├── Payment history view
    ├── Retry logic for failed payments
    ├── Manual intervention tools
    └── Monitoring/alerting integration
```

## Key Considerations

### Security
- **API Keys**: Store in environment variables, never commit
- **Webhook Signatures**: Verify using Stripe signature header
- **HTTPS Only**: Enforce for webhook endpoint
- **PCI Compliance**: Use Stripe Checkout (no card data touches your server)

### Webhook Reliability
- **Idempotency**: Use `event.id` to prevent duplicate processing
- **Retry Strategy**: Stripe retries failed webhooks (return 200 quickly)
- **Event Ordering**: Don't assume order (use timestamps)
- **Event Types**: Handle success, failure, cancellation at minimum

### State Synchronization
- **Source of Truth**: Stripe is authoritative for payment state
- **Local Cache**: Database stores subscription metadata for queries
- **Reconciliation**: Background job to sync Stripe state (hourly)
- **Conflict Resolution**: Stripe wins in case of discrepancy

### Payment Retry Logic
- **Automatic Retry**: Stripe retries failed payments (configurable)
- **Manual Retry**: Admin interface for manual retry
- **Grace Period**: 3-day grace before suspension
- **Notification**: Email user on payment failure

## Expected Conflicts

### Likely Conflicts
- **Interface Mismatch**: Webhook handler signature vs admin dashboard queries
- **Assumption Violation**: Checkout flow assumes webhook will fire (but network failures exist)

### Unlikely Conflicts
- **File Overlap**: Checkout, webhook, and admin touch different files
- **Decision Contradiction**: Well-established Stripe integration patterns

## Verification Commands

```bash
# Test checkout session creation
curl -X POST http://localhost:8000/api/checkout \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <token>" \
  -d '{"plan": "monthly"}'

# Test webhook (use Stripe CLI)
stripe listen --forward-to localhost:8000/webhooks/stripe

# Trigger test webhook
stripe trigger payment_intent.succeeded

# Verify database state
psql -d mydb -c "SELECT * FROM subscriptions WHERE user_id=123"

# Test admin dashboard
curl http://localhost:8000/admin/subscriptions \
  -H "Authorization: Bearer <admin-token>"

# Test payment retry
curl -X POST http://localhost:8000/admin/subscriptions/123/retry \
  -H "Authorization: Bearer <admin-token>"

# Run integration tests
pytest tests/test_stripe_integration.py -v
```

## Success Criteria

1. Checkout flow creates Stripe Checkout Session
2. Successful payment redirects to success page
3. Webhook processes `payment_intent.succeeded` event
4. Database updated with subscription metadata
5. Admin dashboard displays subscription status
6. Failed payments trigger retry logic
7. Webhook signature verification passes
8. Idempotency prevents duplicate processing
9. Integration tests pass with Stripe test mode

## Common Pitfalls

- **Webhook Signature Skipped**: Always verify signatures in production
- **Idempotency Ignored**: Stripe may send duplicate events
- **Synchronous Webhook Processing**: Return 200 quickly, process async
- **No Reconciliation**: Database drifts from Stripe over time
- **Hardcoded API Keys**: Use environment variables
- **Test Mode Confusion**: Clearly separate test/live keys
