> ## 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.

# Errors & Troubleshooting

> Error codes, troubleshooting guides, and solutions for common H2H integration issues

# Errors & Troubleshooting

Comprehensive error handling guide for Caibo H2H integration with error codes, causes, and solutions.

## Error Response Format

All API errors follow this consistent format:

```json theme={null}
{
  "error": "PAYMENT_DECLINED",
  "message": "Payment was declined by the issuing bank",
  "code": "P001",
  "details": {
    "declineReason": "insufficient_funds",
    "issuerResponse": "51"
  },
  "timestamp": "2024-01-15T10:30:00Z",
  "requestId": "req_123456789"
}
```

## HTTP Status Codes

| Status | Meaning      | Action Required          |
| ------ | ------------ | ------------------------ |
| 200    | Success      | Continue processing      |
| 400    | Bad Request  | Fix request parameters   |
| 401    | Unauthorized | Check API key            |
| 403    | Forbidden    | Check permissions        |
| 404    | Not Found    | Verify endpoint/resource |
| 429    | Rate Limited | Implement backoff        |
| 500    | Server Error | Retry with backoff       |

## Authentication Errors

### 401 Unauthorized

**Cause**: Invalid or missing API key

```json theme={null}
{
  "error": "UNAUTHORIZED",
  "message": "Invalid API key provided",
  "code": "AUTH001"
}
```

**Solutions**:

* Verify API key is correct
* Check `X-API-Key` header is present
* Ensure using correct environment (sandbox/production)

```javascript theme={null}
// Correct authentication
const headers = {
  'X-API-Key': process.env.Caibo_API_KEY,
  'Content-Type': 'application/json'
};
```

### 403 Forbidden

**Cause**: API key lacks required permissions

```json theme={null}
{
  "error": "FORBIDDEN",
  "message": "Insufficient permissions for this operation",
  "code": "AUTH002"
}
```

**Solutions**:

* Contact support to verify account permissions
* Check if feature is enabled for your account

## Validation Errors

### 400 Bad Request - Missing Fields

```json theme={null}
{
  "error": "VALIDATION_ERROR",
  "message": "Required field missing",
  "code": "VAL001",
  "details": {
    "missingFields": ["name", "email", "amount"]
  }
}
```

**Solutions**:

* Include all required fields
* Verify field names match API specification

### 400 Bad Request - Invalid Format

```json theme={null}
{
  "error": "INVALID_FORMAT",
  "message": "Invalid email format",
  "code": "VAL002",
  "details": {
    "field": "email",
    "value": "invalid-email"
  }
}
```

**Common Format Issues**:

* Email: Must be valid email format
* Phone: Include country code (+1234567890)
* Amount: Positive number with max 2 decimals
* Currency: 3-letter ISO code (USD, EUR, etc.)

## Payment Errors

### Card Declined

```json theme={null}
{
  "error": "CARD_DECLINED",
  "message": "Card was declined by the issuing bank",
  "code": "PAY001",
  "details": {
    "declineCode": "05",
    "declineReason": "do_not_honor"
  }
}
```

**Common Decline Codes**:

| Code | Reason                    | Customer Action                 |
| ---- | ------------------------- | ------------------------------- |
| 05   | Do Not Honor              | Try different card              |
| 51   | Insufficient Funds        | Add funds or use different card |
| 54   | Expired Card              | Use valid card                  |
| 57   | Transaction Not Permitted | Contact bank                    |
| 61   | Exceeds Withdrawal Limit  | Contact bank                    |

### Invalid Card Details

```json theme={null}
{
  "error": "INVALID_CARD",
  "message": "Invalid card number provided",
  "code": "PAY002",
  "details": {
    "field": "cardNumber",
    "reason": "invalid_luhn"
  }
}
```

**Solutions**:

* Verify card number passes Luhn check
* Check expiry date format (MM/YY)
* Validate CVV length (3-4 digits)

### 3D Secure Errors

```json theme={null}
{
  "error": "THREEDS_FAILED",
  "message": "3D Secure authentication failed",
  "code": "PAY003",
  "details": {
    "threeDsResult": "authentication_failed",
    "acsResponse": "N"
  }
}
```

**Solutions**:

* Customer should retry with correct 3DS credentials
* Ensure browser supports 3D Secure
* Check if card is enrolled for 3DS

## UPI Errors

### Invalid UPI ID

```json theme={null}
{
  "error": "INVALID_UPI_ID",
  "message": "UPI ID format is invalid",
  "code": "UPI001",
  "details": {
    "upiId": "invalid-format",
    "expectedFormat": "username@bankcode"
  }
}
```

**Solutions**:

* Validate UPI ID format: `username@bankcode`
* Check for valid bank codes (paytm, googlepay, etc.)

### UPI Transaction Failed

```json theme={null}
{
  "error": "UPI_TRANSACTION_FAILED",
  "message": "UPI transaction was declined",
  "code": "UPI002",
  "details": {
    "upiResponse": "U30",
    "reason": "invalid_pin"
  }
}
```

**Common UPI Error Codes**:

| Code | Reason                   | Action                          |
| ---- | ------------------------ | ------------------------------- |
| U30  | Invalid PIN              | Customer retry with correct PIN |
| U16  | Risk threshold exceeded  | Contact bank                    |
| U66  | Device not registered    | Register device with bank       |
| U69  | Collect request declined | Customer declined payment       |

## Webhook Errors

### Invalid Signature

```json theme={null}
{
  "error": "INVALID_WEBHOOK_SIGNATURE",
  "message": "Webhook signature verification failed",
  "code": "WH001"
}
```

**Solutions**:

* Verify webhook secret is correct
* Check HMAC SHA512 signature calculation
* Ensure raw request body is used for signature

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

function verifySignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha512', secret)
    .update(payload, 'utf8')
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature, 'hex'),
    Buffer.from(expectedSignature, 'hex')
  );
}
```

### Webhook Timeout

```json theme={null}
{
  "error": "WEBHOOK_TIMEOUT",
  "message": "Webhook endpoint did not respond within timeout",
  "code": "WH002"
}
```

**Solutions**:

* Ensure webhook endpoint responds within 30 seconds
* Return HTTP 200 status code
* Process webhook asynchronously if needed

## Rate Limiting

### 429 Too Many Requests

```json theme={null}
{
  "error": "RATE_LIMIT_EXCEEDED",
  "message": "Too many requests, please slow down",
  "code": "RATE001",
  "details": {
    "limit": 100,
    "window": "1 minute",
    "retryAfter": 60
  }
}
```

**Solutions**:

* Implement exponential backoff
* Respect `Retry-After` header
* Distribute requests over time

```javascript theme={null}
// Exponential backoff implementation
async function retryWithBackoff(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (error.status === 429 && i < maxRetries - 1) {
        const delay = Math.pow(2, i) * 1000; // 1s, 2s, 4s
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      throw error;
    }
  }
}
```

## Network Errors

### Connection Timeout

**Cause**: Network connectivity issues or slow response

**Solutions**:

* Increase timeout values
* Implement retry logic
* Check network connectivity

```javascript theme={null}
// Timeout configuration
const axios = require('axios');

const client = axios.create({
  timeout: 30000, // 30 seconds
  retry: 3,
  retryDelay: 1000
});
```

### DNS Resolution Failed

**Cause**: Unable to resolve API hostname

**Solutions**:

* Check internet connectivity
* Verify DNS settings
* Try different DNS servers (8.8.8.8, 1.1.1.1)

## Troubleshooting Playbooks

### Payment Not Processing

1. **Check API Response**
   * Verify 200 status code
   * Check `paymentRequestId` is returned

2. **Verify Webhook Setup**
   * Confirm webhook URL is accessible
   * Test signature verification
   * Check webhook logs

3. **Monitor Payment Status**
   * Poll status endpoint
   * Check for status updates
   * Review error messages

### Webhook Not Received

1. **Verify Webhook URL**
   ```bash theme={null}
   curl -X POST https://your-webhook-url.com/webhook \
     -H "Content-Type: application/json" \
     -d '{"test": "payload"}'
   ```

2. **Check Firewall/Security**
   * Ensure webhook URL is publicly accessible
   * Check firewall rules
   * Verify SSL certificate

3. **Test Signature Verification**
   ```javascript theme={null}
   // Test with known values
   const testPayload = '{"test":"payload"}';
   const testSecret = 'your_webhook_secret';
   const signature = crypto
     .createHmac('sha512', testSecret)
     .update(testPayload)
     .digest('hex');
   ```

### High Error Rate

1. **Analyze Error Patterns**
   * Group errors by type
   * Identify common causes
   * Check error frequency

2. **Review Request Data**
   * Validate input formats
   * Check required fields
   * Verify data quality

3. **Monitor System Health**
   * Check API response times
   * Monitor error rates
   * Review system logs

## Error Monitoring

### Logging Best Practices

```javascript theme={null}
// Structured error logging
function logError(error, context) {
  console.error(JSON.stringify({
    timestamp: new Date().toISOString(),
    level: 'error',
    error: {
      code: error.code,
      message: error.message,
      stack: error.stack
    },
    context: {
      paymentId: context.paymentId,
      userId: context.userId,
      endpoint: context.endpoint
    }
  }));
}
```

### Error Alerting

Set up alerts for:

* High error rates (>5%)
* Authentication failures
* Webhook delivery failures
* Rate limit violations
* Payment decline spikes

## Getting Help

### Support Channels

* **Technical Support**: [support@caibo.com](mailto:support@caibo.com)
* **Documentation**: Browse our guides and API reference
* **Status Page**: Check system status and incidents
* **Community**: Developer community forum

### When Contacting Support

Include:

* Error code and message
* Request ID from error response
* Timestamp of the issue
* Steps to reproduce
* Code samples (remove sensitive data)

### Emergency Contacts

For critical production issues:

* **Phone**: +1-XXX-XXX-XXXX
* **Emergency Email**: [emergency@caibo.com](mailto:emergency@caibo.com)
* **Response Time**: Within 1 hour

## Next Steps

<CardGroup cols={2}>
  <Card title="FAQ" icon="question-circle" href="/h2h/faq">
    Frequently asked questions
  </Card>

  <Card title="Testing Guide" icon="flask" href="/h2h/testing-sandbox">
    Test error scenarios
  </Card>

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

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