> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mlm-platform.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Sandbox Testing

> Test your integration safely with sandbox environments

# Sandbox Testing

The MLM Platform provides sandbox environments for safe testing without affecting production data.

## Overview

Sandbox environments allow you to:

* Test API integrations without real transactions
* Simulate purchases and commission flows
* Create test users and hierarchies
* Reset data for clean test runs

## Creating a Sandbox

1. Navigate to **Settings** > **Environments** in the Admin Dashboard
2. Click **Create Sandbox**
3. Enter a label (e.g., "Development", "QA")
4. Optionally connect Stripe test mode
5. Click **Create**

<Info>
  You can create up to 3 sandbox environments per tenant.
</Info>

## Sandbox API Keys

Each sandbox has its own API keys:

1. Go to **Settings** > **API Keys**
2. Click **Create API Key**
3. Select your sandbox environment
4. Copy the key (prefix: `mlm_sandbox_`)

## Simulating Purchases

Use your sandbox API key to record purchase events safely:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://app.mlm-platform.com/api/v1/events/purchase \
    -H "Content-Type: application/json" \
    -H "x-tenant-api-key: mlm_sandbox_abc123" \
    -d '{
      "user_id": "550e8400-e29b-41d4-a716-446655440000",
      "amount": 99.99,
      "currency": "USD",
      "description": "[SANDBOX] Test purchase"
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'https://app.mlm-platform.com/api/v1/events/purchase',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-tenant-api-key': 'mlm_sandbox_abc123'
      },
      body: JSON.stringify({
        user_id: '550e8400-e29b-41d4-a716-446655440000',
        amount: 99.99,
        currency: 'USD',
        description: '[SANDBOX] Test purchase'
      })
    }
  );

  const result = await response.json();
  console.log('Commissions created:', result.commissions_created);
  ```
</CodeGroup>

Response:

```json theme={null}
{
  "purchase_id": "660e8400-e29b-41d4-a716-446655440001",
  "commissions_created": 3,
  "commission_details": [
    {
      "beneficiary_id": "550e8400-e29b-41d4-a716-446655440002",
      "level": 1,
      "rate": 0.10,
      "amount": 9.999
    },
    {
      "beneficiary_id": "550e8400-e29b-41d4-a716-446655440003",
      "level": 2,
      "rate": 0.05,
      "amount": 4.9995
    }
  ]
}
```

## Creating Test Users

Create test users for building hierarchies:

```javascript theme={null}
// Create a test user hierarchy
const root = await client.createTestUser({
  email: 'root@test.com',
  membershipTier: 'SENIOR'
});

const level1 = await client.createTestUser({
  email: 'level1@test.com',
  membershipTier: 'ORDINARY',
  parentId: root.id
});

const level2 = await client.createTestUser({
  email: 'level2@test.com',
  membershipTier: 'ORDINARY',
  parentId: level1.id
});

// Simulate a purchase by level2
const result = await client.simulatePurchase({
  buyerUserId: level2.id,
  amount: 100.00
});

// root and level1 should receive commissions
console.log('Commissions:', result.commission_details);
```

## Resetting Sandbox Data

To reset your sandbox, use the Admin Dashboard to reset or recreate your sandbox environment.

## Cloning Configuration

Copy your production commission rules to sandbox:

```javascript theme={null}
await client.cloneConfigToSandbox({
  targetEnvironmentId: 'sandbox-environment-id'
});
```

This copies:

* Commission rules and rates
* Tier configurations
* Payout settings

It does **not** copy:

* User data
* Commission history
* API keys or credentials

## Testing Stripe Integration

### Connect Stripe Test Mode

1. Go to **Settings** > **Environments**
2. Select your sandbox
3. Click **Connect Stripe**
4. Use Stripe test mode credentials

### Test Card Numbers

| Card Number           | Result             |
| --------------------- | ------------------ |
| `4242 4242 4242 4242` | Success            |
| `4000 0000 0000 0002` | Decline            |
| `4000 0000 0000 9995` | Insufficient funds |
| `4000 0000 0000 0069` | Expired card       |

### Test Webhooks

Use Stripe CLI to forward test webhooks:

```bash theme={null}
stripe listen --forward-to localhost:3000/api/v1/webhooks/stripe?tenant_id=YOUR_TENANT_ID

# In another terminal
stripe trigger checkout.session.completed
```

## Environment Detection

Verify you're in sandbox mode:

```javascript theme={null}
const response = await fetch('/api/users', {
  headers: { 'x-tenant-api-key': apiKey }
});

const environment = response.headers.get('X-Environment');
console.log('Environment:', environment); // "SANDBOX"
```

## Best Practices

### Separate Test Data

* Use distinct email patterns: `test-*@example.com`
* Use recognizable product names: `[TEST] Product Name`
* Add metadata: `{ "test": true, "scenario": "happy-path" }`

### Automated Testing

```javascript theme={null}
describe('Commission Flow', () => {
  beforeEach(async () => {
    // Reset sandbox before each test
    await client.resetSandbox();
  });
  
  it('should create commissions for upline', async () => {
    // Create hierarchy
    const sponsor = await client.createTestUser({ email: 'sponsor@test.com' });
    const buyer = await client.createTestUser({ 
      email: 'buyer@test.com',
      parentId: sponsor.id
    });
    
    // Simulate purchase
    const result = await client.simulatePurchase({
      buyerUserId: buyer.id,
      amount: 100.00
    });
    
    // Verify commissions
    expect(result.commissions_created).toBe(1);
    expect(result.commission_details[0].beneficiary_id).toBe(sponsor.id);
  });
});
```

### CI/CD Integration

```yaml theme={null}
# .github/workflows/test.yml
jobs:
  integration-tests:
    runs-on: ubuntu-latest
    env:
      MLM_API_KEY: ${{ secrets.MLM_SANDBOX_API_KEY }}
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: npm run test:integration
```
