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

# Testing & Sandbox

> Test cards, UPI IDs, Google/Apple Pay sandbox, 3DS flows, and webhook testing

# Testing & Sandbox

Comprehensive testing guide for Caibo H2H integration with test data, scenarios, and sandbox configurations.

## Sandbox Environment

* **Base URL**: `https://sandbox-api.caibo.com`
* **Purpose**: Safe testing environment with simulated responses
* **Features**: Test payment methods, webhook testing, 3DS simulation

## Environment Differences: Test vs Production

* The only difference between environments is the number of enabled H2H payment methods.
* Endpoints, request/response schemas, and error codes are identical in Test and Production.
* Production method availability depends on your tenant's configuration and compliance enablement.

## Test Credit Cards

### Successful Payments

| Card Number      | Brand      | CVV  | Expiry | Expected Result |
| ---------------- | ---------- | ---- | ------ | --------------- |
| 4111111111111111 | Visa       | 123  | 12/25  | Success         |
| 5555555555554444 | Mastercard | 123  | 12/25  | Success         |
| 378282246310005  | Amex       | 1234 | 12/25  | Success         |
| 6011111111111117 | Discover   | 123  | 12/25  | Success         |

### Failed Payments

| Card Number      | Brand | Expected Result  |
| ---------------- | ----- | ---------------- |
| 4000000000000002 | Visa  | Declined         |
| 4000000000000119 | Visa  | Processing Error |
| 4000000000000127 | Visa  | Incorrect CVC    |
| 4000000000000069 | Visa  | Expired Card     |

### 3D Secure Testing

| Card Number      | 3DS Outcome                    |
| ---------------- | ------------------------------ |
| 4000000000003220 | 3DS Authentication Required    |
| 4000000000003238 | 3DS Authentication Failed      |
| 4000000000003246 | 3DS Authentication Unavailable |

## Test UPI IDs

### Successful UPI Payments

| UPI ID          | Expected Result |
| --------------- | --------------- |
| success\@paytm  | Payment Success |
| test\@googlepay | Payment Success |
| demo\@phonepe   | Payment Success |

### Failed UPI Payments

| UPI ID              | Expected Result     |
| ------------------- | ------------------- |
| failure\@paytm      | Payment Failed      |
| insufficient\@paytm | Insufficient Funds  |
| timeout\@paytm      | Transaction Timeout |
| invalid\@paytm      | Invalid UPI ID      |

## Google Pay Testing

### Sandbox Setup

1. Use Google Pay test environment
2. Configure test merchant ID
3. Use test card tokens

```javascript theme={null}
// Google Pay test configuration
const testConfig = {
  environment: 'TEST',
  merchantId: '01234567890123456789',
  merchantName: 'Test Merchant'
};
```

### Test Payment Tokens

```json theme={null}
{
  "protocolVersion": "ECv2",
  "signature": "test_signature_here",
  "signedMessage": "test_signed_message"
}
```

## Apple Pay Testing

### Sandbox Configuration

1. Use Apple Pay sandbox certificates
2. Configure test merchant identifier
3. Test with iOS Simulator

```javascript theme={null}
// Apple Pay test setup
const applePayConfig = {
  merchantIdentifier: 'merchant.com.example.test',
  displayName: 'Test Store',
  domainName: 'test.example.com'
};
```

## Webhook Testing

### Test Webhook Payloads

#### Successful Payment

```json theme={null}
{
  "paymentRequestId": "pr_test_123456789",
  "status": "completed",
  "transactionId": "txn_test_987654321",
  "amount": 10.00,
  "currency": "USD",
  "timestamp": "2024-01-15T10:30:00Z",
  "signature": "test_signature_hash"
}
```

#### Failed Payment

```json theme={null}
{
  "paymentRequestId": "pr_test_123456789",
  "status": "failed",
  "errorCode": "CARD_DECLINED",
  "errorMessage": "Card was declined",
  "timestamp": "2024-01-15T10:30:00Z",
  "signature": "test_signature_hash"
}
```

### Webhook Signature Testing

```javascript theme={null}
// Test webhook signature verification
const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha512', secret)
    .update(payload)
    .digest('hex');
  
  return signature === expectedSignature;
}

// Test with known values
const testPayload = '{"paymentRequestId":"pr_test_123"}';
const testSecret = 'test_webhook_secret';
const testSignature = crypto
  .createHmac('sha512', testSecret)
  .update(testPayload)
  .digest('hex');

console.log('Signature valid:', verifyWebhookSignature(testPayload, testSignature, testSecret));
```

## Test Scenarios

### End-to-End Payment Flow

1. **Create Payment Request**
   ```bash theme={null}
   curl -X POST https://sandbox-api.caibo.com/payments/h2h/1 \
     -H "X-API-Key: sandbox_key" \
     -H "Content-Type: application/json" \
     -d '{"name":"Test User","amount":10.00,"unit":"USD"}'
   ```

2. **Simulate Payment Completion**
   * Use test card: `4111111111111111`
   * Expected webhook: `status: "completed"`

3. **Verify Payment Status**
   ```bash theme={null}
   curl -X GET https://sandbox-api.caibo.com/payment-requests/status/{id} \
     -H "X-API-Key: sandbox_key"
   ```

### Error Handling Tests

#### Invalid API Key

```bash theme={null}
curl -X POST https://sandbox-api.caibo.com/payments/h2h/1 \
  -H "X-API-Key: invalid_key" \
  -H "Content-Type: application/json"
# Expected: 401 Unauthorized
```

#### Missing Required Fields

```bash theme={null}
curl -X POST https://sandbox-api.caibo.com/payments/h2h/1 \
  -H "X-API-Key: sandbox_key" \
  -H "Content-Type: application/json" \
  -d '{"amount":10.00}'
# Expected: 400 Bad Request
```

#### Invalid Amount

```bash theme={null}
curl -X POST https://sandbox-api.caibo.com/payments/h2h/1 \
  -H "X-API-Key: sandbox_key" \
  -H "Content-Type: application/json" \
  -d '{"name":"Test","amount":-10.00,"unit":"USD"}'
# Expected: 400 Bad Request
```

## Load Testing

### Rate Limit Testing

```javascript theme={null}
// Test rate limits
async function testRateLimit() {
  const requests = [];
  
  // Send 150 requests (above 100/min limit)
  for (let i = 0; i < 150; i++) {
    requests.push(createTestPayment());
  }
  
  const results = await Promise.allSettled(requests);
  const rateLimited = results.filter(r => 
    r.status === 'rejected' && r.reason.status === 429
  );
  
  console.log(`Rate limited requests: ${rateLimited.length}`);
}
```

## Webhook Testing Tools

### ngrok for Local Testing

```bash theme={null}
# Install ngrok
npm install -g ngrok

# Expose local webhook endpoint
ngrok http 3000

# Use the HTTPS URL as your webhook endpoint
# https://abc123.ngrok.io/webhook
```

### Webhook Testing Server

```javascript theme={null}
const express = require('express');
const app = express();

app.use(express.json());

app.post('/webhook', (req, res) => {
  console.log('Webhook received:', {
    headers: req.headers,
    body: req.body,
    timestamp: new Date().toISOString()
  });
  
  res.status(200).send('OK');
});

app.listen(3000, () => {
  console.log('Webhook test server running on port 3000');
});
```

## Testing Checklist

### Pre-Production Testing

* [ ] **API Authentication**
  * [ ] Valid API key works
  * [ ] Invalid API key returns 401
  * [ ] Missing API key returns 401

* [ ] **Payment Creation**
  * [ ] Successful payment with valid data
  * [ ] Failed payment with invalid card
  * [ ] Validation errors for missing fields

* [ ] **Webhook Handling**
  * [ ] Webhook signature verification
  * [ ] Handle successful payment webhook
  * [ ] Handle failed payment webhook
  * [ ] Webhook retry mechanism

* [ ] **Payment Status**
  * [ ] Status check with valid ID
  * [ ] Status check with invalid ID
  * [ ] Status updates in real-time

* [ ] **Error Handling**
  * [ ] Network timeout handling
  * [ ] Rate limit handling
  * [ ] Invalid response handling

### Performance Testing

* [ ] **Load Testing**
  * [ ] Handle expected traffic volume
  * [ ] Graceful degradation under load
  * [ ] Rate limit compliance

* [ ] **Stress Testing**
  * [ ] System behavior at limits
  * [ ] Recovery after overload
  * [ ] Error rate monitoring

## Monitoring & Debugging

### Logging Best Practices

```javascript theme={null}
// Structured logging for debugging
const logger = {
  info: (message, data) => console.log(JSON.stringify({
    level: 'info',
    message,
    data,
    timestamp: new Date().toISOString()
  })),
  
  error: (message, error) => console.error(JSON.stringify({
    level: 'error',
    message,
    error: error.message,
    stack: error.stack,
    timestamp: new Date().toISOString()
  }))
};

// Usage
logger.info('Payment created', { paymentId: 'pr_123' });
logger.error('Payment failed', new Error('Card declined'));
```

### Debug Mode

```javascript theme={null}
// Enable debug mode for detailed logging
const DEBUG = process.env.NODE_ENV === 'development';

if (DEBUG) {
  console.log('Request payload:', JSON.stringify(payload, null, 2));
  console.log('Response:', JSON.stringify(response, null, 2));
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Error Handling" icon="exclamation-triangle" href="/h2h/errors">
    Handle errors and troubleshooting
  </Card>

  <Card title="Production Deployment" icon="rocket" href="/h2h/getting-started">
    Deploy to production environment
  </Card>

  <Card title="Webhooks Guide" icon="webhook" href="/h2h/notifications">
    Advanced webhook configuration
  </Card>

  <Card title="API Reference" icon="code" href="/h2h/payment-api/h2h-payment">
    Complete API documentation
  </Card>
</CardGroup>
