# Stripe Connect Implementation

This document explains the Stripe Connect implementation that allows users to create connected accounts for receiving payments.

## Overview

The implementation includes:
- Creating Stripe Connect accounts with prefilled user information
- Generating onboarding links for account setup
- Managing account status and verification
- Database fields to track Connect account information

## Database Changes

### New Fields Added to Users Table

- `stripe_connect_account_id` (string, nullable): Stores the Stripe Connect account ID
- `stripe_connect_enabled` (boolean, default false): Indicates if Connect account is enabled
- `stripe_connect_onboarded_at` (timestamp, nullable): Records when onboarding was completed

## API Endpoints

### 1. Create Connect Account (Basic)

**POST** `/stripe/connect/create-account`

Creates a basic Stripe Connect account using existing user information.

**Response:**
```json
{
    "success": true,
    "message": "Stripe Connect account created successfully",
    "account_id": "acct_1234567890",
    "account": { /* Stripe account object */ }
}
```

### 2. Create Connect Account with Prefilled Data

**POST** `/stripe/connect/create-account-with-prefill`

Creates a Connect account with detailed prefilled information.

**Request Body:**
```json
{
    "business_type": "individual", // or "company"
    "country": "US",
    "email": "user@example.com",
    "first_name": "John",
    "last_name": "Doe",
    "phone": "+1234567890",
    "address_line1": "123 Main St",
    "address_city": "New York",
    "address_state": "NY",
    "address_postal_code": "10001"
}
```

**Response:**
```json
{
    "success": true,
    "message": "Stripe Connect account created successfully with prefilled information",
    "account_id": "acct_1234567890",
    "account": { /* Stripe account object */ }
}
```

### 3. Create Account Link for Onboarding

**POST** `/stripe/connect/create-account-link`

Generates an onboarding link for the user to complete their account setup.

**Response:**
```json
{
    "success": true,
    "onboarding_url": "https://connect.stripe.com/setup/c/acct_1234567890/...",
    "expires_at": 1234567890
}
```

### 4. Get Account Status

**GET** `/stripe/connect/account-status`

Retrieves the current status of the user's Connect account.

**Response:**
```json
{
    "success": true,
    "account": {
        "id": "acct_1234567890",
        "charges_enabled": true,
        "payouts_enabled": true,
        "details_submitted": true,
        "requirements": { /* Stripe requirements object */ }
    }
}
```

### 5. Refresh Account Link

**GET** `/stripe/connect/refresh`

Handles refresh requests from Stripe Connect onboarding flow.

### 6. Return from Onboarding

**GET** `/stripe/connect/return`

Handles return from Stripe Connect onboarding and updates user status.

## User Model Methods

### Helper Methods Added

```php
// Check if user has a Connect account
$user->hasStripeConnectAccount()

// Check if Connect account is enabled
$user->isStripeConnectEnabled()

// Check if onboarding is completed
$user->hasCompletedStripeConnectOnboarding()

// Enable Connect account
$user->enableStripeConnect()

// Mark onboarding as completed
$user->markStripeConnectOnboardingCompleted()
```

## Usage Examples

### Frontend Integration

```javascript
// Create a Connect account
fetch('/stripe/connect/create-account', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
    }
})
.then(response => response.json())
.then(data => {
    if (data.success) {
        console.log('Account created:', data.account_id);
    }
});

// Create onboarding link
fetch('/stripe/connect/create-account-link', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
    }
})
.then(response => response.json())
.then(data => {
    if (data.success) {
        window.location.href = data.onboarding_url;
    }
});
```

### Backend Usage

```php
// Check if user can receive payments
if ($user->isStripeConnectEnabled()) {
    // User can receive payments
    $canReceivePayments = true;
}

// Create account with custom data
$response = $stripeController->createConnectAccountWithPrefill($request);
```

## Configuration

### Environment Variables

Make sure these are set in your `.env` file:

```env
STRIPE_KEY_TEST=pk_test_...
STRIPE_SECRET_TEST=sk_test_...
STRIPE_KEY_LIVE=pk_live_...
STRIPE_SECRET_LIVE=sk_live_...
```

### Stripe Connect Settings

The implementation uses Express accounts by default, which provide:
- Simplified onboarding flow
- Automatic account creation
- Built-in compliance handling

## Security Considerations

1. **Authentication**: All endpoints require user authentication
2. **Email Verification**: Users must have verified email addresses
3. **Rate Limiting**: Consider adding rate limiting to prevent abuse
4. **Webhook Handling**: Implement webhooks to handle account updates

## Error Handling

The implementation includes comprehensive error handling for:
- Stripe API errors
- Authentication failures
- Validation errors
- Network issues

All errors return appropriate HTTP status codes and descriptive messages.

## Testing

### Test Mode

The implementation automatically uses test API keys when `APP_ENV=local`.

### Test Scenarios

1. Create account with basic information
2. Create account with detailed prefilled data
3. Generate onboarding link
4. Complete onboarding flow
5. Check account status

## Webhooks (Recommended)

Consider implementing webhooks to handle:
- Account updates
- Onboarding completion
- Account status changes
- Compliance requirements

## Next Steps

1. Implement webhook handling
2. Add payment processing with Connect accounts
3. Create admin interface for managing Connect accounts
4. Add comprehensive logging
5. Implement account verification workflows

## Support

For issues or questions about this implementation, refer to:
- [Stripe Connect Documentation](https://stripe.com/docs/connect)
- [Stripe Connect Express Accounts](https://stripe.com/docs/connect/express-accounts)
- [Stripe Connect Onboarding](https://stripe.com/docs/connect/onboarding)