# Stripe EventBridge Integration Setup

This document explains how to set up Stripe to send events to AWS EventBridge for the billing infrastructure.

## Quick Start with Scripts

### For Staging (TEST Mode)
```bash
# 1. Configure Stripe products and pricing
python scripts/setup_stripe_products.py staging

# 2. Get setup instructions for Stripe TEST Dashboard
python scripts/setup_stripe_eventbridge.py staging

# 3. Create EventBridge destination in Stripe TEST Dashboard (manual step)
#    ⚠️ IMPORTANT: Go to TEST mode: https://dashboard.stripe.com/test/webhooks
#    NOT the live dashboard!

# 4. Activate the partner event source in AWS
python scripts/activate_stripe_eventbus.py staging

# 5. Deploy your stack
make deploy-staging

# 6. Test the integration
make test-stripe
```

### For Production (LIVE Mode)
```bash
# 1. Configure Stripe products and pricing
python scripts/setup_stripe_products.py production

# 2. Get setup instructions for Stripe LIVE Dashboard
python scripts/setup_stripe_eventbridge.py production

# 3. Create EventBridge destination in Stripe LIVE Dashboard (manual step)
#    Go to LIVE mode: https://dashboard.stripe.com/webhooks

# 4. Activate the partner event source in AWS
python scripts/activate_stripe_eventbus.py production

# 5. Deploy your stack
make deploy-prod

# 6. Verify the integration
python scripts/test_stripe_events.py production --verify
```

## Overview

The billing system uses AWS EventBridge to receive Stripe webhook events. This provides:
- Automatic retry logic
- Event replay capabilities
- Better reliability than traditional webhooks
- Native AWS integration

## Prerequisites

- Stripe account (test mode for staging, live mode for production)
- AWS account with appropriate permissions
- Python with boto3 and stripe packages installed (`pip install stripe boto3 python-dotenv`)
- Stripe CLI (optional, for testing)
- Poetry for dependency management (`pip install poetry`)

## Setup Steps

### Step 1: Configure Stripe Products and Pricing

Before setting up EventBridge, you need to create the necessary products and prices in Stripe:

**Script Helper (Recommended):**
```bash
# Set up products for staging (TEST mode)
python scripts/setup_stripe_products.py staging

# Set up products for production (LIVE mode)
python scripts/setup_stripe_products.py production

# Verify existing configuration
python scripts/setup_stripe_products.py staging --verify-only
```

This script will:
1. Create an API Usage product with metered pricing tiers
2. Optionally create a base subscription product
3. Store product IDs in your `.env` file for deployment
4. Configure graduated pricing tiers for usage-based billing

**Manual Setup (Alternative):**
If you prefer to create products manually in Stripe Dashboard:
1. Go to **Products** in Stripe Dashboard
2. Create a product named "API Usage"
3. Add a metered price with:
   - Billing period: Monthly
   - Usage type: Metered
   - Aggregation: Sum of usage values during period
   - Pricing model: Graduated tiers
4. Note the Product ID and Price ID
5. Add to your `.env` file:
   ```
   STAGING_API_USAGE_PRODUCT_ID=prod_xxxxx
   STAGING_API_USAGE_PRICE_ID=price_xxxxx
   ```

### Step 2: Create EventBridge Destination in Stripe

**Script Helper:**
```bash
# Shows instructions for Stripe Dashboard configuration
python scripts/setup_stripe_eventbridge.py staging
```

The script will display the exact values to enter in the Stripe Dashboard.

**Manual Setup via Stripe Dashboard:**

⚠️ **CRITICAL: Use the correct Stripe mode!**
- For **staging**: Use TEST mode dashboard: https://dashboard.stripe.com/test/webhooks
- For **production**: Use LIVE mode dashboard: https://dashboard.stripe.com/webhooks

1. Log into Stripe Dashboard in the **correct mode** (TEST for staging, LIVE for production)
2. Navigate to **Developers → Webhooks**
3. Click **Add destination**
4. Select **EventBridge** as the destination type
5. Configure the destination:
   - **Name**: `AWS EventBridge - Staging (TEST)` or `AWS EventBridge - Production (LIVE)`
   - **AWS account ID**:
     - Staging: Your default AWS account ID
     - Production: Your aillc AWS account ID
   - **AWS region**: `us-east-1` (or your region)
6. Select events to send:
   - `customer.subscription.created`
   - `customer.subscription.updated`
   - `customer.subscription.deleted`
   - `invoice.payment_succeeded`
   - `invoice.payment_failed`
   - `checkout.session.completed`
   - `payment_method.attached`
   - `payment_method.detached`
7. Click **Create destination**

### Step 3: Note the Partner Event Source Name

After creating the destination, Stripe will display:
- **Partner event source name**: Something like `aws.partner/stripe.com/acct_xxxxx/xxxxx`

Save this value - you'll need it for AWS configuration.

### Step 4: Activate Partner Event Source in AWS

**Script Helper (Recommended):**
```bash
# List pending partner event sources
python scripts/activate_stripe_eventbus.py --list

# Activate for staging (interactive - will prompt for selection)
python scripts/activate_stripe_eventbus.py staging

# Or activate specific source directly
python scripts/activate_stripe_eventbus.py staging --activate aws.partner/stripe.com/acct_xxxxx/xxxxx
```

The script will:
1. Find pending Stripe partner event sources
2. Activate the selected source in AWS
3. Update your .env file with the event bus name
4. Tell you when it's ready to deploy

**Manual Setup via AWS Console:**

1. Go to [AWS EventBridge Console](https://console.aws.amazon.com/events)
2. Navigate to **Partner event sources** in the left menu
3. Find your Stripe source (status will be "Pending")
4. Select it and click **Associate with event bus**
5. Accept the default name or customize it
6. Click **Associate**

**Manual Setup via AWS CLI:**

```bash
# List pending partner event sources
aws events list-partner-event-sources --region us-east-1

# Activate the source (replace with your source name)
aws events create-event-bus \
  --name aws.partner/stripe.com/acct_xxxxx/xxxxx \
  --event-source-name aws.partner/stripe.com/acct_xxxxx/xxxxx \
  --region us-east-1
```

### Step 5: Update Your .env File

**Note:** The `activate_stripe_eventbus.py` script does this automatically!

To manually add the event bus name and product IDs to your `.env` file:

```bash
# For staging
STAGING_PARTNER_EVENT_BUS_NAME=aws.partner/stripe.com/acct_xxxxx/xxxxx
STAGING_API_USAGE_PRODUCT_ID=prod_xxxxx
STAGING_API_USAGE_PRICE_ID=price_xxxxx

# For production
PROD_PARTNER_EVENT_BUS_NAME=aws.partner/stripe.com/acct_xxxxx/xxxxx
PROD_API_USAGE_PRODUCT_ID=prod_xxxxx
PROD_API_USAGE_PRICE_ID=price_xxxxx
```

### Step 6: Deploy the Stack

```bash
# Deploy with the correct event bus name
make deploy-staging
# or
make deploy-prod
```

## Verification Script

Check if everything is properly configured:

```bash
# Verify the setup for staging
python scripts/setup_stripe_eventbridge.py staging --verify

# This will check:
# - Event bus exists in AWS
# - Event bus name is in .env
# - Connection is active
```

## Testing the Integration

### Send Test Events from Stripe

Using Stripe CLI:
```bash
# Trigger a test event
stripe trigger checkout.session.completed
```

Or from the Stripe Dashboard:
1. Go to your EventBridge destination
2. Click **Send test event**
3. Select an event type and send

### Verify in AWS

Check CloudWatch Logs for your Lambda function:
```bash
# View recent logs
aws logs tail /aws/lambda/augint-billing-staging-stripe-event-handler --follow
```

## Troubleshooting

### Common Mistake: Wrong Stripe Mode

**This is the most common setup error!** If events aren't flowing:

1. **Check your Stripe mode mismatch:**
   - TEST mode events (staging) only flow to TEST mode EventBridge destinations
   - LIVE mode events (production) only flow to LIVE mode EventBridge destinations
   - If you created the destination in LIVE mode but are testing with TEST events, nothing will flow!

2. **How to verify:**
   - In Stripe Dashboard, check if you see "TEST DATA" toggle at the top
   - EventBridge destinations created in TEST mode only appear when viewing TEST mode
   - EventBridge destinations created in LIVE mode only appear when viewing LIVE mode

3. **To fix:**
   - Delete the incorrectly created event bus in AWS
   - Switch to the correct Stripe mode (TEST for staging, LIVE for production)
   - Recreate the EventBridge destination in the correct mode

### "Event bus does not exist" Error

This means the partner event source hasn't been activated in AWS. Follow Step 3 above.

### Events Not Arriving

1. Check Stripe Dashboard → Developers → Webhooks → Your EventBridge destination
   - Look for failed events
   - Check the destination is enabled

2. Verify the event bus name in your `.env` matches exactly

3. Check IAM permissions for the Lambda function

### Wrong Event Bus Name

If you need to find the correct event bus name:
```bash
# List all event buses
aws events list-event-buses --region us-east-1
```

## Event Types

The billing system processes these Stripe events:

| Event Type | Purpose |
|------------|---------|
| `checkout.session.completed` | Customer completes checkout |
| `customer.subscription.created` | New subscription created |
| `customer.subscription.updated` | Subscription modified |
| `customer.subscription.deleted` | Subscription cancelled |
| `invoice.payment_succeeded` | Payment successful |
| `invoice.payment_failed` | Payment failed |
| `payment_method.attached` | Card added |
| `payment_method.detached` | Card removed |

## Security Notes

- EventBridge destinations are more secure than webhooks (no endpoint exposure)
- Events are encrypted in transit
- IAM policies control access to the event bus
- No webhook secrets needed with EventBridge

## Known Issues and Required Configuration

### Missing Infrastructure Components

The following components need to be added to the CloudFormation template:

1. **DynamoDB Table**: The `customer_links` table is referenced but not created
   - Currently requires manual creation or separate stack
   - Should be added to `template.yaml` as infrastructure-as-code

2. **Environment Variables**: The Lambda functions need these configured:
   - `API_USAGE_PRODUCT_ID`: Stripe product ID for metered billing
   - `API_USAGE_PRICE_ID`: Stripe price ID for metered billing
   - These should be passed as parameters or environment variables

3. **Currency Configuration**: Checkout sessions require currency to be specified
   - Currently missing from the Lambda handler implementation
   - Needs to be added to the checkout session creation

### Configuration Checklist

Before deploying, ensure you have:
- [ ] Created Stripe products using `setup_stripe_products.py`
- [ ] Set up EventBridge destination in correct Stripe mode (TEST/LIVE)
- [ ] Activated partner event source in AWS
- [ ] Added all required values to `.env` file
- [ ] Created DynamoDB table (until added to template)

## Alternative: Traditional Webhooks

If you prefer traditional webhooks instead of EventBridge:

1. Deploy an API Gateway endpoint for webhooks
2. Configure webhook endpoint in Stripe
3. Use webhook signing secret for validation

However, EventBridge is recommended for better reliability and AWS integration.
