# Access & Login
Source: https://docs.caibo.digital/cpanel/access-and-login
How to access your tenant control panel and sign in securely.
## Access URL
Your tenant-specific control panel URL is provided during onboarding. Use your brand’s dedicated domain provided by Caibo. If you’re unsure of the URL, contact your Caibo onboarding contact.
## Environments
* Sandbox: use your sandbox tenant URL
* Production: use your production tenant URL
## Authentication
* Email and password (set during user invite)
* 2FA may be required if enabled for your tenant
## Troubleshooting
* Can’t access the URL: check with your administrator for the correct tenant URL
* Login failures: reset your password from the sign-in page or contact an admin to re-invite your account
# Analytics Overview
Source: https://docs.caibo.digital/cpanel/analytics/overview
Visualize payment performance with built-in charts (if available).
## Dashboards
* Volume by method and currency
* Success rates and declines
* Trends over time
## Notes
* Metrics vary by tenant configuration
* Use exports for deeper BI analysis
# Saved Reports
Source: https://docs.caibo.digital/cpanel/analytics/saved-reports
Create and manage saved analytics views.
## Overview
Save frequently used filters and date ranges as named reports for quick access.
## Tips
* Standardize naming across your finance team
* Periodically review and clean up unused reports
# Customer Details
Source: https://docs.caibo.digital/cpanel/customers/customer-details
View a customer's profile, activity, and related payments.
## Overview
The details view aggregates profile data and payment activity for the selected customer.
## Sections
* Profile: name, contact, identifiers
* Activity: recent payment requests and transactions
## Related API
* Get or update customer: [/ipg/customer/update\_customer](/ipg/customer/update_customer)
# Customers List
Source: https://docs.caibo.digital/cpanel/customers/customers-list
Browse and search your customers.
## List view
* View customers with basic attributes (name, contact, created date)
* Search by email/phone/reference (as available)
## Actions
* Open a customer to view details
## Related
* Customer details: [/cpanel/customers/customer-details](/cpanel/customers/customer-details)
* Create/Update customer via API: [/ipg/customer/create\_customer](/ipg/customer/create_customer)
# KYC Statuses
Source: https://docs.caibo.digital/cpanel/customers/kyc-statuses
Understand customer verification indicators in the portal (if enabled).
## Overview
If your tenant uses customer verification, status badges may appear on customer profiles or lists to indicate verification progress.
* Not enabled for all tenants; availability depends on your setup
* Use statuses to guide support or risk review
## Related
* Customers list: [/cpanel/customers/customers-list](/cpanel/customers/customers-list)
# Dashboard
Source: https://docs.caibo.digital/cpanel/dashboard
Understand key widgets and metrics on the Merchant Control Panel home view.
## Overview
The dashboard summarizes payment performance and recent activity.
## Widgets
* Payments summary: volume, success rate, refunds
* Recent payment requests and transactions
* Alerts: webhook delivery issues, configuration reminders
## Tips
* Use the date range selector to focus on specific periods
* Drill into any metric to view the underlying transactions
# Navigation Basics
Source: https://docs.caibo.digital/cpanel/navigation-basics
Find your way around the Caibo Merchant Control Panel.
## Layout
* Sidebar navigation with main sections: Payment Requests, Transactions, Customers, Wallets, Analytics, Security, Users & Roles, Settings
* Main content area for lists and details
* Global search and filters on list pages (where available)
## Tips
* Use filters to narrow large lists
* Many tables support CSV export
* Click any row to open the details view
# Merchant Control Panel
Source: https://docs.caibo.digital/cpanel/overview
How to use the Caibo Merchant Control Panel to manage payment requests, transactions, customers, security, and settings.
## What is the Merchant Control Panel?
The Caibo Merchant Control Panel is your browser-based portal to operate payment flows without coding. Use it to create and manage payment requests, monitor transactions, export reports, configure security, and manage users.
## Who should use it
* Business owner / merchant admin
* Finance and reconciliation team
* Customer support and risk ops
## Key capabilities
* Create and manage payment requests
* Track transaction status in real time
* Export transactions for reconciliation
* Configure origin domains and webhooks
* Manage users, roles and permissions
## Quick links
* Payment Requests → creating and managing requests
* Transactions → lists, filters, exports
* Origin Domains & Security → allowed domains, webhook signatures
* Users & Roles → access control
* Settings → payment methods, webhooks, API keys
## Related API
* Payment Requests API: [/ipg/payment-requests/payment-request](/ipg/payment-requests/payment-request)
* Payment Status: [/ipg/payment-requests/payment-status](/ipg/payment-requests/payment-status)
* Callbacks & Webhooks: [/ipg/callbacks](/ipg/callbacks)
# Creating Payment Requests
Source: https://docs.caibo.digital/cpanel/payment-requests/creating-requests
Create hosted payment requests directly from the control panel.
## Create a payment request
1. Go to Payment Requests → Create
2. Enter amount and currency
3. Provide reference ID and customer details if available
4. Optionally set success/failure/notify URLs
5. Save to generate a payment link or QR
## Share the payment link
* Send the generated link to your customer
* The hosted page handles customer payment and 3DS (if required)
## Related API
* Create via API: [/ipg/payment-requests/payment-request](/ipg/payment-requests/payment-request)
* Handle payment: [/ipg/payment-requests/handle-payment-request](/ipg/payment-requests/handle-payment-request)
# Managing Payment Requests
Source: https://docs.caibo.digital/cpanel/payment-requests/managing-requests
Search, filter, and take actions on existing payment requests.
## List and search
* Go to Payment Requests → List
* Filter by date, amount, currency, status, or reference ID
* Open a request to view details and activity
## Actions
* Copy link for resending
* Release or cancel (if applicable to your flow)
## Related API
* Get Payment Request: [/ipg/payment-requests/get-payment-request](/ipg/payment-requests/get-payment-request)
* Release Payment Request: [/ipg/payment-requests/release-payment-request](/ipg/payment-requests/release-payment-request)
# Refunds & Reversals
Source: https://docs.caibo.digital/cpanel/payment-requests/refunds-reversals
Issue refunds or reversals when enabled for your tenant.
## Overview
If your account has refunds enabled, you can initiate a refund from a completed transaction’s details page. Reversals may be available depending on the payment method and acquirer rules.
## Guidance
* Check your agreement for refund permissions and settlement timelines
* Use exports to track refund reconciliation
## Related
* Transactions list: [/cpanel/transactions/transactions-list](/cpanel/transactions/transactions-list)
* H2H Refund endpoint (for server-to-server integrations): [/h2h/payment-api/h2h-refund](/h2h/payment-api/h2h-refund)
# Payment Status Lifecycle
Source: https://docs.caibo.digital/cpanel/payment-requests/status-lifecycle
Understand how payment request statuses progress in the system.
## Overview
Payment requests progress through a series of statuses from creation to completion. Use the status and activity log to understand the current state.
## Reference
* Status reference: [/ipg/payment-requests/payment-status](/ipg/payment-requests/payment-status)
* Provider notifications: [/ipg/callbacks](/ipg/callbacks)
# Origin Domains
Source: https://docs.caibo.digital/cpanel/security/origin-domains
Restrict which website origins may initialize payment flows.
## Overview
Add allowed origins (e.g., [https://www.example.com](https://www.example.com)) to prevent unauthorized usage from other domains.
## Best practices
* Add production and sandbox origins separately
* Use exact origins (scheme + host + optional port)
## Related
* Webhook Signatures: [/cpanel/security/webhook-signatures](/cpanel/security/webhook-signatures)
* Callbacks reference: [/ipg/callbacks](/ipg/callbacks)
# Webhook Signatures
Source: https://docs.caibo.digital/cpanel/security/webhook-signatures
Verify webhook signatures to ensure callbacks originate from Caibo.
## Why verify
Webhook signatures protect you from spoofed callbacks.
## How to verify
1. Retrieve the signature header sent with the callback
2. Compute your own signature using the shared secret
3. Compare calculated vs received values
## Related
* Callbacks reference: [/ipg/callbacks](/ipg/callbacks)
* Troubleshooting: [/cpanel/troubleshooting/webhook-debugging](/cpanel/troubleshooting/webhook-debugging)
# API Keys
Source: https://docs.caibo.digital/cpanel/settings/api-keys
Generate and manage API keys for secure access to Caibo IPG APIs
## Overview
API keys are essential credentials that authenticate your requests to Caibo IPG APIs. They provide secure access to payment processing functionality and are generated through the Control Panel.
## Key Features
* **Secure Authentication**: API keys provide secure access to all Caibo IPG endpoints
* **Easy Generation**: Generate new keys instantly through the Control Panel interface
* **Key Rotation**: Regenerate keys for enhanced security without service interruption
* **Environment Support**: Separate keys for test and production environments
## Generating API Keys
### Step 1: Access Your Profile
1. **Log into the Control Panel** using your merchant credentials
2. **Navigate to Profile Settings** from the main menu
3. **Locate the API Key section** in your profile
### Step 2: Generate Your Key
1. **Click "Generate API Key"** or the key icon (🔑) next to the API Key field
2. **Confirm the action** in the dialog that appears
3. **Copy your new API key** immediately after generation
**Important**: Your API key is displayed only once during generation. Make sure to copy and store it securely before closing the dialog.
### Step 3: Store Securely
* **Environment Variables**: Store in your application's environment configuration
* **Secure Storage**: Never commit API keys to version control
* **Access Control**: Limit access to keys within your organization
## Key Types
### Test Keys
* **Format**: `caibo_test_sk_*`
* **Purpose**: Development and testing
* **Environment**: Sandbox/Test environment
* **Transactions**: No real money processed
### Live Keys
* **Format**: `caibo_live_sk_*`
* **Purpose**: Production transactions
* **Environment**: Live/Production environment
* **Transactions**: Real money processing
## Using API Keys
### HTTP Header Format
Include your API key in all requests using the `X-API-Key` header:
```http theme={null}
X-API-Key: caibo_live_sk_1234567890abcdef
Content-Type: application/json
```
### Example Request
```bash theme={null}
curl -X GET \
"https://apay.caibo.digital/payment-requests/12345" \
-H "X-API-Key: caibo_live_sk_1234567890abcdef" \
-H "Content-Type: application/json"
```
## Key Management
### Regenerating Keys
To regenerate an existing API key:
1. **Navigate to Profile Settings**
2. **Click the regenerate icon** (🔑) next to your current API key
3. **Confirm regeneration** in the dialog
4. **Update all integrations** with the new key
**Service Interruption**: Regenerating a key immediately invalidates the previous key. Ensure all systems are updated before regenerating.
### Key Rotation Best Practices
* **Regular Rotation**: Regenerate keys periodically for security
* **Planned Updates**: Schedule key rotations during maintenance windows
* **Testing**: Verify new keys work before invalidating old ones
* **Documentation**: Keep internal documentation updated with key changes
## Security Best Practices
### Storage Security
* **Never expose keys** in client-side code or public repositories
* **Use environment variables** or secure configuration management
* **Implement access controls** for key storage systems
* **Monitor key usage** for suspicious activity
### Access Management
* **Principle of least privilege**: Only grant access to necessary personnel
* **Audit key usage**: Regularly review who has access to API keys
* **Revoke unused keys**: Remove keys that are no longer needed
* **Separate environments**: Use different keys for test and production
### Monitoring
* **Track API usage**: Monitor requests made with your API keys
* **Set up alerts**: Configure notifications for unusual activity
* **Regular audits**: Review key usage patterns periodically
* **Incident response**: Have procedures for compromised keys
## Troubleshooting
### Common Issues
#### Key Not Working
* **Check format**: Ensure key starts with `caibo_test_sk_` or `caibo_live_sk_`
* **Verify environment**: Confirm you're using the correct key for your environment
* **Check regeneration**: Ensure the key hasn't been recently regenerated
#### Authentication Errors
* **Header format**: Verify `X-API-Key` header is correctly formatted
* **Key validity**: Confirm the key is active and not revoked
* **Account status**: Ensure your merchant account is in good standing
#### Missing Keys
* **Profile access**: Verify you can access the Profile Settings page
* **Account permissions**: Ensure you have permission to generate API keys
* **Browser issues**: Try clearing cache or using a different browser
### Getting Help
If you encounter issues with API key management:
1. **Check account status** in the Control Panel
2. **Review error messages** for specific guidance
3. **Contact support** at [support@caibo.digital](mailto:support@caibo.digital) with:
* Your merchant account ID
* Description of the issue
* Screenshots if applicable
## Integration Examples
### Environment Configuration
```bash .env theme={null}
# Test Environment
CAIBO_API_KEY=caibo_test_sk_your_test_key_here
CAIBO_BASE_URL=https://apay.caibo.digital
# Production Environment
CAIBO_API_KEY=caibo_live_sk_your_live_key_here
CAIBO_BASE_URL=https://apay.caibo.digital
```
```javascript config.js theme={null}
module.exports = {
caibo: {
apiKey: process.env.CAIBO_API_KEY,
baseUrl: process.env.CAIBO_BASE_URL || 'https://apay.caibo.digital'
}
};
```
```python config.py theme={null}
import os
CAIBO_CONFIG = {
'api_key': os.getenv('CAIBO_API_KEY'),
'base_url': os.getenv('CAIBO_BASE_URL', 'https://apay.caibo.digital')
}
```
## Related Documentation
Complete authentication setup and usage guide
Quick start guide for your first integration
Learn how to create and manage payment requests
Comprehensive security guidelines
# Payment Methods
Source: https://docs.caibo.digital/cpanel/settings/payment-methods
Enable or configure payment methods available for your tenant.
## Overview
* Methods such as cards, UPI, wallets may be available depending on your agreement
* Contact your Caibo representative for changes to enabled methods
## Related
* H2H Payment Methods overview: [/h2h/payment-methods](/h2h/payment-methods)
# Webhooks & Callbacks
Source: https://docs.caibo.digital/cpanel/settings/webhooks-callbacks
Configure callback endpoints for payment status updates.
## Configure webhooks
* Add your endpoint URL per environment
* Use secrets to verify signatures
## Related
* Callbacks reference: [/ipg/callbacks](/ipg/callbacks)
* Webhook signatures: [/cpanel/security/webhook-signatures](/cpanel/security/webhook-signatures)
# Filters & Exports
Source: https://docs.caibo.digital/cpanel/transactions/filters-and-exports
Filter transactions and export data for reconciliation.
## Filters
* Narrow results by date ranges, methods, currencies, amounts, or status
* Combine multiple filters and save common views (if available)
## Exports
* Export CSV for finance or BI tools
* Use consistent date ranges and timezones for reconciliation
## Related
* Transactions list: [/cpanel/transactions/transactions-list](/cpanel/transactions/transactions-list)
* Reconciliation: [/cpanel/transactions/reconciliation](/cpanel/transactions/reconciliation)
# Reconciliation
Source: https://docs.caibo.digital/cpanel/transactions/reconciliation
Best practices to reconcile transactions and settlements from the control panel.
## Overview
Use exports and filters to match transactions with settlements and your internal orders.
## Steps
1. Filter by date range and status
2. Export CSV and import into your finance tool
3. Match reference IDs and amounts
4. Investigate mismatches via transaction details
## Tips
* Use a consistent timezone for exports
* Include refunds in the same export window
## Related
* Filters & Exports: [/cpanel/transactions/filters-and-exports](/cpanel/transactions/filters-and-exports)
* Payment Status Reference: [/ipg/payment-requests/payment-status](/ipg/payment-requests/payment-status)
# Transactions List
Source: https://docs.caibo.digital/cpanel/transactions/transactions-list
View and analyze transactions in the control panel.
## List view
* Access via Transactions → List
* Columns typically include reference, amount, currency, status, method, created date
* Click a row for full details and activity
## Related
* Filters & Exports: [/cpanel/transactions/filters-and-exports](/cpanel/transactions/filters-and-exports)
* Payment Status: [/ipg/payment-requests/payment-status](/ipg/payment-requests/payment-status)
# FAQ
Source: https://docs.caibo.digital/cpanel/troubleshooting/faq
Frequently asked questions for the Merchant Control Panel.
## How do I get access?
Ask your tenant admin to invite you.
## Where do I find payment links?
Open a payment request and copy the generated link.
## How do I export transactions?
Use Transactions → Export as CSV.
# Payment Issues
Source: https://docs.caibo.digital/cpanel/troubleshooting/payment-issues
Diagnose common issues with payments initiated via the control panel.
## Checklist
* Verify payment request status
* Check activity log for provider updates
* Confirm webhook delivery and signature
## Related
* Payment Status Reference: [/ipg/payment-requests/payment-status](/ipg/payment-requests/payment-status)
* Webhooks & Callbacks: [/ipg/callbacks](/ipg/callbacks)
# Webhook Debugging
Source: https://docs.caibo.digital/cpanel/troubleshooting/webhook-debugging
How to debug webhook delivery and signature issues.
## Steps
1. Check delivery logs in your endpoint
2. Validate signature computation
3. Retry delivery if supported
## Related
* Webhook Signatures: [/cpanel/security/webhook-signatures](/cpanel/security/webhook-signatures)
* Callbacks reference: [/ipg/callbacks](/ipg/callbacks)
# Roles & Permissions
Source: https://docs.caibo.digital/cpanel/users-roles/roles-permissions
Control panel roles and what they can do.
## Typical roles
* Admin: full access
* Finance: exports, transactions, limited settings
* Support: view customers and transactions
## Notes
Role names and scopes may vary by tenant configuration.
# User Management
Source: https://docs.caibo.digital/cpanel/users-roles/user-management
Invite and manage access to the control panel.
## Invite users
* Admins can invite users by email
* Assign roles during or after invite
## Manage users
* Disable/enable access
* Reset 2FA (if enabled)
## Best practices
* Use named accounts per person; avoid shared logins
* Review access regularly
# Balances & Settlement
Source: https://docs.caibo.digital/cpanel/wallets/balances-and-settlement
Monitor balances and settlement cycles (if enabled).
## Overview
* Track balances for settlement cycles
* Review completed, pending, and refunded volumes
## Tips
* Align export time ranges with settlement windows
* Reconcile refunds within the same period
# Wallets Overview
Source: https://docs.caibo.digital/cpanel/wallets/wallets-overview
View balances and accounts (if enabled for your tenant).
## Overview
Some tenants may have a Wallets section showing balances and accounts used for settlements or internal accounting.
* Availability depends on your configuration
* Use exports to support finance reconciliation
## Related
* Balances & Settlement: [/cpanel/wallets/balances-and-settlement](/cpanel/wallets/balances-and-settlement)
# Changelog
Source: https://docs.caibo.digital/h2h/changelog
Version history, breaking changes, and deprecation policy for Caibo H2H API
# Changelog
Track API updates, new features, and breaking changes for Caibo Host-to-Host integration.
## Version 2.1.0 - January 15, 2024
### ✨ New Features
* **Apple Pay Support**: Added native Apple Pay integration for H2H payments
* **Enhanced 3D Secure**: Improved 3DS 2.0 support with better authentication flows
* **Webhook Retry Logic**: Configurable retry policies for webhook deliveries
### 🔧 Improvements
* **Response Times**: 25% improvement in API response times
* **Error Messages**: More descriptive error messages with actionable guidance
* **Documentation**: Comprehensive guides and interactive API explorer
### 🐛 Bug Fixes
* Fixed UPI timeout handling for slow network conditions
* Resolved webhook signature verification edge cases
* Corrected currency validation for multi-currency transactions
***
## Version 2.0.0 - December 1, 2023
### 🚨 Breaking Changes
* **API Versioning**: Introduced versioning in API endpoints
* **Authentication**: Migrated from Bearer tokens to `X-API-Key` header
* **Webhook Format**: Updated webhook payload structure
#### Migration Guide
```javascript theme={null}
// Old authentication (deprecated)
headers: {
'Authorization': 'Bearer your_token'
}
// New authentication (required)
headers: {
'X-API-Key': 'your_api_key'
}
```
### ✨ New Features
* **Google Pay Integration**: Full Google Pay support for web and mobile
* **Multi-Currency Support**: Process payments in 20+ currencies
* **Advanced Fraud Detection**: Enhanced security with machine learning
### 🔧 Improvements
* **Rate Limiting**: Increased limits for production accounts
* **Monitoring**: Real-time transaction monitoring dashboard
* **SDKs**: Updated JavaScript and Python SDKs
***
## Version 1.5.2 - October 20, 2023
### 🐛 Bug Fixes
* Fixed intermittent timeout issues with UPI payments
* Resolved webhook delivery delays during high traffic
* Corrected amount validation for zero-decimal currencies
### 🔧 Improvements
* **Performance**: Reduced payment processing latency by 15%
* **Logging**: Enhanced request/response logging for debugging
***
## Version 1.5.1 - September 15, 2023
### 🔧 Improvements
* **UPI Enhancements**: Better error handling for UPI transactions
* **Webhook Reliability**: Improved webhook delivery success rate
* **Documentation**: Added more code examples and use cases
### 🐛 Bug Fixes
* Fixed edge case in credit card validation
* Resolved timezone issues in webhook timestamps
***
## Version 1.5.0 - August 10, 2023
### ✨ New Features
* **UPI Integration**: Added support for UPI payments in India
* **QR Code Payments**: Generate QR codes for mobile payments
* **Sandbox Enhancements**: Improved testing environment with more scenarios
### 🔧 Improvements
* **Error Handling**: Standardized error response format
* **Security**: Enhanced API key validation and rotation
* **Performance**: Optimized database queries for faster responses
***
## Version 1.4.0 - June 25, 2023
### ✨ New Features
* **Alternative Payments**: Support for bank transfers and BNPL options
* **Webhook Signatures**: HMAC SHA512 signature verification
* **Payment Status Polling**: Real-time status updates
### 🔧 Improvements
* **API Documentation**: Interactive OpenAPI specification
* **Testing**: Comprehensive test card suite
* **Monitoring**: Enhanced error tracking and alerting
***
## Version 1.3.0 - May 5, 2023
### ✨ New Features
* **3D Secure Support**: Full 3DS authentication flow
* **Refund API**: Programmatic refund processing
* **Batch Operations**: Process multiple payments efficiently
### 🐛 Bug Fixes
* Fixed currency conversion edge cases
* Resolved webhook duplicate delivery issues
***
## Version 1.2.0 - March 20, 2023
### ✨ New Features
* **Multi-Gateway Support**: Route payments through multiple processors
* **Risk Management**: Advanced fraud detection rules
* **Reporting API**: Transaction reporting and analytics
### 🔧 Improvements
* **Rate Limiting**: Implemented fair usage policies
* **Caching**: Improved response times with intelligent caching
***
## Version 1.1.0 - February 1, 2023
### ✨ New Features
* **Webhook Notifications**: Real-time payment status updates
* **Payment Methods**: Expanded credit card support
* **Sandbox Environment**: Dedicated testing environment
### 🔧 Improvements
* **Error Messages**: More descriptive error responses
* **Validation**: Enhanced input validation and sanitization
***
## Version 1.0.0 - January 10, 2023
### 🎉 Initial Release
* **Core Payment Processing**: Credit card payment support
* **REST API**: RESTful API design with JSON responses
* **Security**: PCI DSS compliant payment processing
* **Documentation**: Comprehensive API documentation
***
## Deprecation Policy
### Timeline
* **Announcement**: 90 days notice for breaking changes
* **Deprecation**: 6 months support for deprecated features
* **Removal**: Complete removal after deprecation period
### Communication
* **Email Notifications**: Sent to registered developer emails
* **API Headers**: Deprecation warnings in API responses
* **Documentation**: Clear migration guides and timelines
### Current Deprecations
#### Bearer Token Authentication (Deprecated)
* **Deprecated**: December 1, 2023
* **Removal**: June 1, 2024
* **Migration**: Use `X-API-Key` header instead
```javascript theme={null}
// Deprecated (will be removed June 2024)
headers: {
'Authorization': 'Bearer your_token'
}
// Current (use this)
headers: {
'X-API-Key': 'your_api_key'
}
```
## Version Support
| Version | Status | Support Until |
| ------- | ----------- | ------------- |
| 2.1.x | Current | Active |
| 2.0.x | Supported | June 2024 |
| 1.5.x | Deprecated | March 2024 |
| 1.4.x | End of Life | - |
## Breaking Changes Guide
### How We Handle Breaking Changes
1. **Advance Notice**: 90 days minimum notice
2. **Migration Period**: 6 months overlap support
3. **Documentation**: Detailed migration guides
4. **Support**: Dedicated migration assistance
### What Constitutes a Breaking Change
* Removing API endpoints
* Changing required parameters
* Modifying response structure
* Authentication method changes
* Webhook payload changes
### Non-Breaking Changes
* Adding optional parameters
* Adding new response fields
* New API endpoints
* Performance improvements
* Bug fixes
## Staying Updated
### Notification Channels
* **Email**: Subscribe to developer updates
* **Webhook**: `api.version.deprecated` event
* **Documentation**: Version-specific documentation
* **Status Page**: System updates and maintenance
### API Versioning
```bash theme={null}
# Specify API version in requests
curl -X POST https://api.caibo.com/v2/payments/h2h/1 \
-H "X-API-Key: your_key" \
-H "X-API-Version: 2.1"
```
### Backward Compatibility
We maintain backward compatibility within major versions:
* **v2.x**: All 2.x versions are compatible
* **v1.x**: Legacy support until March 2024
## Migration Assistance
### Resources Available
* **Migration Guides**: Step-by-step instructions
* **Code Examples**: Before/after code samples
* **Testing Tools**: Validate your migration
* **Support Team**: Technical assistance
### Contact for Help
* **Email**: [migrations@caibo.com](mailto:migrations@caibo.com)
* **Documentation**: Version-specific guides
* **Support**: Priority support for migrations
## Next Steps
Current API documentation
Upgrade to latest version
Test your integration
Get migration help
# Errors & Troubleshooting
Source: https://docs.caibo.digital/h2h/errors
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
Frequently asked questions
Test error scenarios
Advanced webhook handling
Complete API documentation
# Alternative Payment Example
Source: https://docs.caibo.digital/h2h/examples/alternative-payment
Simple payment request without card details for alternative payment methods
# Overview
This example demonstrates a simplified payment request for alternative payment methods that don't require card details or browser information.
## Payment Request
```json theme={null}
{
"name": "Test User",
"email": "test.user@email.com",
"phoneNumber": "1234567890",
"address": "10 Unknown Street",
"city": "Far Town",
"state": "NA",
"postalCode": "123456",
"country": "US",
"amount": 10.50,
"unit": "USD",
"originDomain": "example.com",
"referenceId": "123-GA-456",
"notifyUrl": "https://notify.me",
"successUrl": "https://success.payment.com",
"failureUrl": "http://fail.payment.com"
}
```
## Key Features
### Simplified Structure
* **No Card Data**: No card number, expiration, or CVV required
* **No Browser Info**: No browserInfo object needed
* **Customer Focus**: Emphasis on customer identification and contact
### Customer Information
* **Name**: Customer full name for identification
* **Email**: Primary contact for notifications
* **Phone**: Secondary contact method
* **Address**: Complete billing/shipping address
### Transaction Details
* **Amount**: \$10.50 USD transaction
* **Reference**: Merchant tracking ID (123-GA-456)
* **Callback URLs**: Success, failure, and notification endpoints
## Use Cases
### Bank Transfers
* Direct bank account debits
* ACH transfers
* Wire transfers
* SEPA payments (Europe)
### Digital Wallets
* PayPal
* Skrill
* Neteller
* Regional wallet services
### Buy Now, Pay Later
* Klarna
* Afterpay
* Affirm
* Sezzle
### Cryptocurrency
* Bitcoin payments
* Ethereum payments
* Stablecoin transactions
* Other crypto assets
## Implementation
### JavaScript Example
```javascript theme={null}
const alternativePayment = {
name: "Test User",
email: "test.user@email.com",
phoneNumber: "1234567890",
address: "10 Unknown Street",
city: "Far Town",
state: "NA",
postalCode: "123456",
country: "US",
amount: 10.50,
unit: "USD",
originDomain: "example.com",
referenceId: "123-GA-456",
notifyUrl: "https://notify.me",
successUrl: "https://success.payment.com",
failureUrl: "http://fail.payment.com"
};
// Send payment request
const response = await fetch('https://your-h2h-endpoint.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'your-api-key'
},
body: JSON.stringify(alternativePayment)
});
const result = await response.json();
console.log('Payment created:', result.paymentRequestId);
console.log('Redirect URL:', result.redirectUrl);
```
### PHP Example
```php theme={null}
'Test User',
'email' => 'test.user@email.com',
'phoneNumber' => '1234567890',
'address' => '10 Unknown Street',
'city' => 'Far Town',
'state' => 'NA',
'postalCode' => '123456',
'country' => 'US',
'amount' => 10.50,
'unit' => 'USD',
'originDomain' => 'example.com',
'referenceId' => '123-GA-456',
'notifyUrl' => 'https://notify.me',
'successUrl' => 'https://success.payment.com',
'failureUrl' => 'http://fail.payment.com'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://your-h2h-endpoint.com');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($alternativePayment));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'X-API-Key: your-api-key'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$result = json_decode($response, true);
echo "Payment ID: " . $result['paymentRequestId'];
echo "Redirect URL: " . $result['redirectUrl'];
?>
```
## Payment Flow
### 1. Payment Creation
* Submit payment request with customer details
* Receive payment ID and redirect URL
* Store payment ID for status tracking
### 2. Customer Redirect
* Redirect customer to provided URL
* Customer completes payment on provider's page
* Customer returns via success/failure URL
### 3. Payment Completion
* Receive webhook notification
* Verify payment status
* Update order/account status
* Send confirmation to customer
## Advantages
### Simplicity
* **Minimal Data**: Only essential customer information required
* **No PCI Compliance**: No card data handling needed
* **Easy Integration**: Simple request structure
### Security
* **Reduced Risk**: No sensitive payment data stored
* **Provider Security**: Payment handled by specialized providers
* **Compliance**: Automatic regulatory compliance
### Customer Experience
* **Familiar Interface**: Customers use known payment methods
* **Trust**: Established payment provider brands
* **Convenience**: Saved payment methods and preferences
## Testing
### Test Data
```json theme={null}
{
"name": "John Doe",
"email": "john.doe@example.com",
"phoneNumber": "+1234567890",
"address": "123 Test Street",
"city": "Test City",
"state": "TS",
"postalCode": "12345",
"country": "US",
"amount": 25.00,
"unit": "USD",
"referenceId": "TEST-ORDER-001"
}
```
### Test Scenarios
1. **Successful Payment**: Complete payment flow
2. **Cancelled Payment**: Customer cancels during payment
3. **Failed Payment**: Insufficient funds or other errors
4. **Invalid Data**: Test validation error handling
## Best Practices
### Data Validation
* Validate email format and deliverability
* Verify phone number format
* Check address completeness
* Validate country and currency combinations
### Error Handling
* Handle network timeouts gracefully
* Provide clear error messages to customers
* Log errors for debugging
* Implement retry mechanisms
### Security
* Use HTTPS for all communications
* Validate webhook signatures
* Implement rate limiting
* Monitor for suspicious activity
## Next Steps
1. Choose appropriate alternative payment methods for your market
2. Implement webhook handling for payment notifications
3. Set up proper error handling and logging
4. Test with real payment providers
5. Monitor payment success rates and optimize
# Credit Card Payment Example
Source: https://docs.caibo.digital/h2h/examples/credit-card-payment
Complete credit card payment request with browserInfo for 3D Secure verification
# Overview
This example demonstrates a complete credit card payment request including all required fields and browser information for 3D Secure verification.
## Payment Request
```json theme={null}
{
"name": "Test User",
"number": "4111111111111111",
"expiration": "10/25",
"cvv": "123",
"email": "test.user@email.com",
"phoneNumber": "1234567890",
"address": "10 Unknown Street",
"city": "Far Town",
"state": "NA",
"postalCode": "123456",
"country": "US",
"amount": 10.50,
"unit": "USD",
"originDomain": "example.com",
"referenceId": "123-GA-456",
"notifyUrl": "https://notify.me",
"successUrl": "https://success.payment.com",
"failureUrl": "http://fail.payment.com",
"browserInfo": {
"browserAcceptHeader": "application/json, text/plain, */*",
"browserColorDepth": "24",
"browserIP": "127.0.0.1",
"browserJavaEnabled": false,
"browserJavascriptEnabled": true,
"browserLanguage": "en-US",
"browserScreenHeight": "1080",
"browserScreenWidth": "1920",
"browserTZ": "300",
"browserUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
}
}
```
## Key Features
### Card Information
* **Test Card**: Visa test card number (4111111111111111)
* **Expiration**: MM/YY format (10/25)
* **CVV**: 3-digit security code (123)
* **Cardholder**: Test User name
### Customer Details
* **Contact Info**: Email and phone number for notifications
* **Billing Address**: Complete address for verification
* **Country Code**: ISO 2-letter country code (US)
### Transaction Details
* **Amount**: \$10.50 USD
* **Reference**: Custom merchant reference (123-GA-456)
* **URLs**: Notification, success, and failure callback URLs
### Browser Information (3D Secure)
The browserInfo object contains essential data for 3D Secure authentication:
| Field | Value | Purpose |
| -------------------------- | ----------------------------------- | -------------------------- |
| `browserAcceptHeader` | `application/json, text/plain, */*` | Browser accept header |
| `browserColorDepth` | `24` | Screen color depth |
| `browserIP` | `127.0.0.1` | Customer's IP address |
| `browserJavaEnabled` | `false` | Java support status |
| `browserJavascriptEnabled` | `true` | JavaScript support status |
| `browserLanguage` | `en-US` | Browser language setting |
| `browserScreenHeight` | `1080` | Screen height in pixels |
| `browserScreenWidth` | `1920` | Screen width in pixels |
| `browserTZ` | `300` | Timezone offset in minutes |
| `browserUserAgent` | Chrome 126 string | Full browser user agent |
## Implementation
### JavaScript Example
```javascript theme={null}
const creditCardPayment = {
name: "Test User",
number: "4111111111111111",
expiration: "10/25",
cvv: "123",
email: "test.user@email.com",
phoneNumber: "1234567890",
address: "10 Unknown Street",
city: "Far Town",
state: "NA",
postalCode: "123456",
country: "US",
amount: 10.50,
unit: "USD",
originDomain: "example.com",
referenceId: "123-GA-456",
notifyUrl: "https://notify.me",
successUrl: "https://success.payment.com",
failureUrl: "http://fail.payment.com",
browserInfo: {
browserAcceptHeader: navigator.userAgent,
browserColorDepth: screen.colorDepth.toString(),
browserIP: "127.0.0.1", // Get from server
browserJavaEnabled: navigator.javaEnabled(),
browserJavascriptEnabled: true,
browserLanguage: navigator.language,
browserScreenHeight: screen.height.toString(),
browserScreenWidth: screen.width.toString(),
browserTZ: new Date().getTimezoneOffset().toString(),
browserUserAgent: navigator.userAgent
}
};
// Send payment request
const response = await fetch('https://your-h2h-endpoint.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'your-api-key'
},
body: JSON.stringify(creditCardPayment)
});
```
### Collecting Browser Info
```javascript theme={null}
function collectBrowserInfo() {
return {
browserAcceptHeader: document.querySelector('meta[http-equiv="Accept"]')?.content || "*/*",
browserColorDepth: screen.colorDepth.toString(),
browserIP: "127.0.0.1", // Must be collected server-side
browserJavaEnabled: navigator.javaEnabled ? navigator.javaEnabled() : false,
browserJavascriptEnabled: true,
browserLanguage: navigator.language || navigator.userLanguage,
browserScreenHeight: screen.height.toString(),
browserScreenWidth: screen.width.toString(),
browserTZ: new Date().getTimezoneOffset().toString(),
browserUserAgent: navigator.userAgent
};
}
```
## Security Considerations
### PCI DSS Compliance
* Never log or store complete card numbers
* Use HTTPS for all communications
* Implement proper input validation
* Follow PCI DSS requirements for card data handling
### 3D Secure Authentication
* Browser info is crucial for 3DS verification
* Collect accurate browser fingerprinting data
* Handle 3DS challenge flows properly
* Test with different browsers and devices
## Testing
### Test Cards
* **Visa**: 4111111111111111
* **Mastercard**: 5555555555554444
* **American Express**: 378282246310005
### Test Scenarios
1. **Successful Payment**: Use test card with valid data
2. **Declined Payment**: Use declined test card numbers
3. **3DS Challenge**: Test 3D Secure authentication flow
4. **Invalid Data**: Test validation error handling
## Next Steps
After implementing credit card payments:
1. Test with different card types and scenarios
2. Implement proper error handling
3. Set up webhook notifications
4. Add payment status checking
5. Consider implementing digital wallets
# UPI Payment Example
Source: https://docs.caibo.digital/h2h/examples/upi-payment
UPI payment request with browserInfo for Indian market payments
# UPI Payment Example
This example demonstrates a UPI (Unified Payments Interface) payment request for the Indian market, including browser information for verification.
## Payment Request
```json theme={null}
{
"name": "Test User",
"upiId": "upi-id",
"email": "test.user@email.com",
"phoneNumber": "1234567890",
"address": "10 Unknown Street",
"city": "Far Town",
"state": "NA",
"postalCode": "123456",
"country": "US",
"amount": 10.50,
"unit": "USD",
"originDomain": "example.com",
"referenceId": "123-GA-456",
"notifyUrl": "https://notify.me",
"successUrl": "https://success.payment.com",
"failureUrl": "http://fail.payment.com",
"browserInfo": {
"browserAcceptHeader": "application/json, text/plain, */*",
"browserColorDepth": "24",
"browserIP": "127.0.0.1",
"browserJavaEnabled": false,
"browserJavascriptEnabled": true,
"browserLanguage": "en-US",
"browserScreenHeight": "1080",
"browserScreenWidth": "1920",
"browserTZ": "300",
"browserUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
}
}
```
## Key Features
### UPI-Specific Fields
* **UPI ID**: Customer's UPI identifier (e.g., "customer\@paytm", "9876543210\@ybl")
* **Browser Info**: Required for transaction verification and fraud prevention
* **Indian Context**: Optimized for Indian payment ecosystem
### Customer Information
* **Name**: Account holder name matching UPI registration
* **Phone**: Mobile number linked to UPI account
* **Email**: Contact for transaction notifications
* **Address**: Billing address for verification
### Transaction Details
* **Amount**: Transaction amount (typically in INR for UPI)
* **Reference**: Merchant transaction reference
* **Callback URLs**: Success, failure, and notification endpoints
## UPI Overview
### What is UPI?
UPI (Unified Payments Interface) is India's instant real-time payment system developed by the National Payments Corporation of India (NPCI). It enables:
* Instant money transfers between bank accounts
* 24/7 availability
* Mobile-first payment experience
* QR code-based payments
* Merchant payments
### Popular UPI Apps
* **Google Pay** (@okaxis, @okhdfcbank)
* **PhonePe** (@ybl, @ibl)
* **Paytm** (@paytm)
* **Amazon Pay** (@apl)
* **BHIM** (@upi)
## Implementation
### JavaScript Example
```javascript theme={null}
const upiPayment = {
name: "Rajesh Kumar",
upiId: "rajesh.kumar@paytm",
email: "rajesh.kumar@email.com",
phoneNumber: "+919876543210",
address: "123 MG Road",
city: "Bangalore",
state: "Karnataka",
postalCode: "560001",
country: "IN",
amount: 500.00,
unit: "INR",
originDomain: "mystore.com",
referenceId: "ORDER-UPI-001",
notifyUrl: "https://mystore.com/webhook/upi",
successUrl: "https://mystore.com/payment/success",
failureUrl: "https://mystore.com/payment/failure",
browserInfo: {
browserAcceptHeader: navigator.userAgent,
browserColorDepth: screen.colorDepth.toString(),
browserIP: "127.0.0.1", // Get from server
browserJavaEnabled: navigator.javaEnabled(),
browserJavascriptEnabled: true,
browserLanguage: navigator.language,
browserScreenHeight: screen.height.toString(),
browserScreenWidth: screen.width.toString(),
browserTZ: new Date().getTimezoneOffset().toString(),
browserUserAgent: navigator.userAgent
}
};
// Send UPI payment request
const response = await fetch('https://your-h2h-endpoint.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'your-api-key'
},
body: JSON.stringify(upiPayment)
});
const result = await response.json();
console.log('UPI Payment ID:', result.paymentRequestId);
console.log('Payment URL:', result.redirectUrl);
```
### UPI ID Validation
```javascript theme={null}
function validateUpiId(upiId) {
// Basic UPI ID format: username@bankcode
const upiRegex = /^[a-zA-Z0-9.\-_]{2,256}@[a-zA-Z]{2,64}$/;
if (!upiRegex.test(upiId)) {
return false;
}
// Common UPI handles
const validHandles = [
'paytm', 'ybl', 'ibl', 'okaxis', 'okhdfcbank',
'okicici', 'oksbi', 'apl', 'upi', 'axl'
];
const handle = upiId.split('@')[1];
return validHandles.includes(handle);
}
// Usage
const isValid = validateUpiId("customer@paytm"); // true
const isInvalid = validateUpiId("invalid-upi"); // false
```
## Payment Flow
### 1. UPI Payment Initiation
* Customer enters UPI ID
* Validate UPI ID format
* Submit payment request with browser info
* Receive payment URL
### 2. UPI App Integration
* Customer redirected to UPI payment page
* UPI app opens automatically (mobile)
* Customer authorizes payment with UPI PIN
* Transaction processed instantly
### 3. Payment Completion
* Instant payment confirmation
* Webhook notification sent
* Customer redirected to success/failure page
* Transaction status updated
## UPI Advantages
### For Customers
* **Instant Transfers**: Real-time money movement
* **24/7 Availability**: No banking hour restrictions
* **Mobile Convenience**: Pay using smartphone
* **No Card Details**: No need to share card information
* **Free Transfers**: Most UPI transactions are free
### For Merchants
* **Low Cost**: Minimal transaction fees
* **Instant Settlement**: Immediate payment confirmation
* **High Success Rate**: Direct bank-to-bank transfer
* **Mobile Optimized**: Perfect for mobile commerce
* **Wide Adoption**: Popular across India
## Testing
### Test UPI IDs
```json theme={null}
{
"name": "Test User",
"upiId": "test@paytm",
"email": "test@example.com",
"phoneNumber": "+919999999999",
"country": "IN",
"amount": 100.00,
"unit": "INR"
}
```
### Test Scenarios
1. **Valid UPI ID**: Test with correct UPI format
2. **Invalid UPI ID**: Test validation error handling
3. **Successful Payment**: Complete UPI payment flow
4. **Failed Payment**: Insufficient balance or declined
5. **Timeout**: Customer doesn't complete payment
## Common UPI Handles
| Bank/Provider | UPI Handle | Example |
| ------------- | ----------- | -------------------- |
| Paytm | @paytm | customer\@paytm |
| PhonePe | @ybl | customer\@ybl |
| Google Pay | @okaxis | customer\@okaxis |
| Amazon Pay | @apl | customer\@apl |
| BHIM | @upi | customer\@upi |
| HDFC Bank | @okhdfcbank | customer\@okhdfcbank |
| ICICI Bank | @okicici | customer\@okicici |
| SBI | @oksbi | customer\@oksbi |
## Error Handling
### Common UPI Errors
* **Invalid UPI ID**: Incorrect format or non-existent ID
* **Insufficient Balance**: Customer account has insufficient funds
* **Transaction Limit**: Exceeds daily/monthly UPI limits
* **Bank Decline**: Issuing bank declined the transaction
* **Timeout**: Customer didn't complete payment in time
### Error Response Example
```json theme={null}
{
"error": {
"code": "038",
"message": "Invalid UPI",
"description": "The provided UPI ID is invalid or not found"
}
}
```
## Best Practices
### UPI ID Handling
* Validate UPI ID format before submission
* Support popular UPI handles
* Provide clear error messages for invalid IDs
* Allow customers to edit UPI ID easily
### Mobile Optimization
* Optimize for mobile browsers
* Support UPI app deep linking
* Handle app switching gracefully
* Provide fallback options
### Security
* Always use HTTPS
* Validate webhook signatures
* Log transactions for audit
* Monitor for suspicious patterns
## Regional Considerations
### Indian Market
* **Currency**: Use INR (Indian Rupees)
* **Phone Format**: +91 country code
* **Address**: Indian address format
* **Language**: Support Hindi and regional languages
* **Timezone**: IST (Indian Standard Time)
### Compliance
* **RBI Guidelines**: Follow Reserve Bank of India regulations
* **NPCI Rules**: Adhere to NPCI UPI guidelines
* **KYC Requirements**: Ensure proper customer verification
* **Transaction Limits**: Respect UPI transaction limits
## Next Steps
1. Integrate with UPI payment gateway
2. Implement UPI ID validation
3. Set up webhook handling for instant notifications
4. Test with different UPI apps and scenarios
5. Optimize mobile user experience
6. Monitor transaction success rates
# FAQ
Source: https://docs.caibo.digital/h2h/faq
Frequently asked questions about Caibo H2H integration
# Frequently Asked Questions
Common questions and answers for Caibo Host-to-Host payment integration.
## Getting Started
### Q: How do I get API keys for testing?
**A:** Sign up for a Caibo merchant account and access your dashboard to retrieve sandbox API keys. Production keys are available after account verification.
### Q: What's the difference between sandbox and production?
**A:**
* **Sandbox**: Testing environment with simulated responses, test cards, and fake transactions
* **Production**: Live environment processing real payments with actual money
### Q: How long does account verification take?
**A:** Typically 1-3 business days. You can start testing with sandbox immediately while verification is in progress.
## Integration
### Q: Which programming languages are supported?
**A:** Caibo H2H is a REST API that works with any language that can make HTTP requests. We provide examples in:
* JavaScript/Node.js
* Python
* PHP
* cURL
### Q: Do I need to store card details?
**A:** No, Caibo H2H is designed for server-to-server payments without storing sensitive card data on your servers. Card details are handled securely by our payment processors.
### Q: Can I use H2H for mobile apps?
**A:** H2H is designed for server-to-server communication. For mobile apps, use our mobile SDKs or implement H2H on your backend server.
## Payment Methods
### Q: Which payment methods are supported?
**A:**
* Credit/Debit Cards (Visa, Mastercard, Amex, Discover)
* UPI (India)
* Google Pay
* Apple Pay
* Alternative payments (bank transfers, BNPL)
### Q: How do I add new payment methods?
**A:** Contact our support team to enable additional payment methods for your account. Some methods may require additional verification.
### Q: Are there country restrictions?
**A:** Payment method availability varies by country. Check our payment methods guide for specific regional support.
## Webhooks
### Q: Are webhooks required?
**A:** While not mandatory, webhooks are strongly recommended for real-time payment status updates and better user experience.
### Q: What happens if my webhook endpoint is down?
**A:** We retry webhook deliveries with exponential backoff for up to 24 hours. You can also poll the payment status endpoint.
### Q: How do I verify webhook authenticity?
**A:** Use HMAC SHA512 signature verification with your webhook secret:
```javascript theme={null}
const crypto = require('crypto');
function verifyWebhook(payload, signature, secret) {
const expectedSignature = crypto
.createHmac('sha512', secret)
.update(payload)
.digest('hex');
return signature === expectedSignature;
}
```
## Security
### Q: How secure is the H2H API?
**A:**
* PCI DSS Level 1 compliant
* TLS 1.2+ encryption
* API key authentication
* Webhook signature verification
* Fraud detection and prevention
### Q: Should I validate payments on my server?
**A:** Yes, always verify payment status using our API or webhooks. Never rely solely on client-side confirmation.
### Q: How do I handle sensitive data?
**A:**
* Never log API keys or webhook secrets
* Use environment variables for credentials
* Implement proper access controls
* Follow PCI DSS guidelines
## Testing
### Q: What test cards should I use?
**A:** Use our provided test cards:
* Success: `4111111111111111`
* Declined: `4000000000000002`
* 3DS Required: `4000000000003220`
See our [Testing Guide](/h2h/testing-sandbox) for complete test data.
### Q: How do I test webhooks locally?
**A:** Use ngrok to expose your local server:
```bash theme={null}
ngrok http 3000
# Use the HTTPS URL as your webhook endpoint
```
### Q: Can I test 3D Secure flows?
**A:** Yes, use specific test cards that trigger 3DS authentication in sandbox mode.
## Errors & Troubleshooting
### Q: Why am I getting 401 Unauthorized?
**A:** Check that:
* API key is correct
* `X-API-Key` header is included
* Using the right environment (sandbox/production)
### Q: Payment shows as pending but never completes
**A:**
* Check webhook delivery
* Verify webhook signature handling
* Poll payment status endpoint
* Review error logs
### Q: How do I handle rate limits?
**A:** Implement exponential backoff and respect the `Retry-After` header:
```javascript theme={null}
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;
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
throw error;
}
}
}
```
## Payments & Transactions
### Q: What's the maximum transaction amount?
**A:** Limits vary by payment method and region:
* Credit Cards: Typically \$10,000 USD
* UPI: ₹1,00,000 INR per transaction
* Contact support for higher limits
### Q: How long do payments take to process?
**A:**
* Credit Cards: Instant (few seconds)
* UPI: Instant
* Bank transfers: 1-3 business days
* Alternative payments: Varies by method
### Q: Can I refund payments?
**A:** Yes, use the refund endpoint or contact support. Refund availability depends on the payment method and processor.
### Q: How do I handle partial payments?
**A:** H2H processes full amounts only. For partial payments, create multiple payment requests or implement split payments in your application logic.
## Business & Billing
### Q: What are the transaction fees?
**A:** Fees vary by payment method, transaction volume, and region. Contact our sales team for detailed pricing.
### Q: When do I get paid?
**A:** Settlement schedules depend on your merchant agreement, typically:
* Daily settlements for established merchants
* Weekly settlements for new merchants
### Q: Can I use multiple currencies?
**A:** Yes, we support multiple currencies. Available currencies depend on your account configuration and payment methods.
## Development
### Q: Is there a Postman collection?
**A:** Yes, we provide a Postman collection with pre-configured requests and environments. Contact support for access.
### Q: How do I handle timeouts?
**A:** Set appropriate timeouts and implement retry logic:
```javascript theme={null}
const axios = require('axios');
const client = axios.create({
timeout: 30000, // 30 seconds
retry: 3,
retryDelay: 1000
});
```
### Q: Can I customize the payment flow?
**A:** H2H provides server-to-server payment processing. For custom UI flows, combine H2H with our frontend SDKs or build your own interface.
### Q: How do I migrate from another payment provider?
**A:**
1. Set up Caibo account and test integration
2. Run parallel processing during transition
3. Gradually migrate traffic
4. Contact our migration team for assistance
## Support
### Q: How do I contact support?
**A:**
* **Email**: [support@caibo.com](mailto:support@caibo.com)
* **Documentation**: Browse our guides
* **Emergency**: [emergency@caibo.com](mailto:emergency@caibo.com) (production issues)
### Q: What information should I include in support requests?
**A:**
* Error codes and messages
* Request IDs
* Timestamps
* Steps to reproduce
* Code samples (remove sensitive data)
### Q: Do you offer implementation support?
**A:** Yes, we provide technical support during integration. Premium support packages are available for complex implementations.
## Compliance
### Q: Are you PCI compliant?
**A:** Yes, Caibo is PCI DSS Level 1 compliant. Your H2H integration doesn't handle card data directly, reducing your PCI scope.
### Q: What about GDPR compliance?
**A:** We're GDPR compliant and provide data processing agreements. Ensure your implementation follows GDPR requirements for customer data.
### Q: Do you support Strong Customer Authentication (SCA)?
**A:** Yes, we support 3D Secure 2.0 for SCA compliance in European markets.
## Still Have Questions?
Get help from our technical team
Troubleshoot common issues
Test your integration
Complete API documentation
# Getting Started
Source: https://docs.caibo.digital/h2h/getting-started
Platform overview, API keys, environments, and base URLs for Caibo Host-to-Host integration
# Getting Started with Caibo H2H
Welcome to Caibo's Host-to-Host (H2H) payment integration. This guide covers the essential setup steps to start processing payments through our server-to-server API.
## Platform Overview
Caibo H2H enables direct server-to-server payment processing with:
* **Multiple Payment Methods**: Credit cards, UPI, Google Pay, Apple Pay, alternative payments
* **Global Coverage**: Support for international and regional payment methods
* **Enterprise Security**: PCI DSS compliant with advanced fraud protection
* **Real-time Processing**: Instant payment processing and status updates
* **Webhook Notifications**: Real-time payment status updates
## Server URL
* Use a single API base URL for both Test and Production, as assigned by Caibo for your merchant.
* Environment selection is driven by your API key and the H2H payment method ID you use in the path.
## 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.
## API Authentication
### API Keys
All API requests require authentication using your API key in the `X-API-Key` header:
```bash theme={null}
curl -X POST "$Caibo_H2H_ENDPOINT/payments/h2h/$Caibo_H2H_METHOD_ID" \
-H "X-API-Key: $Caibo_API_KEY" \
-H "Content-Type: application/json"
```
### Environment Variables
Set up your environment variables (same base URL for Test and Production; change API key and method ID per environment):
```bash theme={null}
# Server base URL (assigned by Caibo)
export Caibo_H2H_ENDPOINT="https://YOUR_API_BASE"
# Test credentials
export Caibo_API_KEY="your_test_api_key_here"
export Caibo_H2H_METHOD_ID="your_test_method_id"
# Production credentials
# export Caibo_API_KEY="your_live_api_key_here"
# export Caibo_H2H_METHOD_ID="your_live_method_id"
```
## Getting Your API Keys
1. **Sign up** for a Caibo merchant account
2. **Complete verification** process
3. **Access your dashboard** to retrieve API keys
4. **Configure webhooks** for payment notifications
Keep your API keys secure and never expose them in client-side code or public repositories.
## Basic Request Structure
All H2H payment requests follow this structure:
```json theme={null}
{
"name": "Customer Name",
"email": "customer@example.com",
"phoneNumber": "+1234567890",
"address": "123 Main Street",
"city": "New York",
"state": "NY",
"postalCode": "10001",
"country": "US",
"amount": 99.99,
"unit": "USD",
"originDomain": "your-store.com",
"notifyUrl": "https://your-server.com/webhook",
"successUrl": "https://your-store.com/success",
"failureUrl": "https://your-store.com/failure"
}
```
## Response Format
All API responses follow a consistent format:
```json theme={null}
{
"paymentRequestId": "pr_1234567890",
"status": "pending",
"redirectUrl": "https://payment-gateway.com/process",
"message": "Payment initiated successfully"
}
```
## Rate Limits
* **Sandbox**: 100 requests per minute
* **Production**: 1000 requests per minute
* **Burst**: Up to 2x rate limit for short periods
## Next Steps
Complete your first H2H payment in 10 minutes
Explore available payment methods
Test cards, UPI IDs, and sandbox data
Set up real-time payment notifications
## Support
* **Documentation**: Browse our comprehensive guides
* **API Reference**: Interactive API explorer
* **Support**: Contact our technical support team
* **Status Page**: Check system status and uptime
# Glossary
Source: https://docs.caibo.digital/h2h/glossary
Merchant-friendly definitions and terminology for Caibo H2H integration
# Glossary
Essential terms and definitions for Caibo Host-to-Host payment integration.
## A
### API (Application Programming Interface)
A set of protocols and tools for building software applications. Caibo's API allows your system to communicate with our payment processing platform.
### API Key
A unique identifier used to authenticate requests to the Caibo API. Keep this secret and secure.
### Authorization
The process of verifying that a payment method has sufficient funds and is valid for the transaction amount.
### Alternative Payment Methods
Payment options beyond traditional credit/debit cards, such as bank transfers, digital wallets, and buy-now-pay-later services.
## B
### Base64 Encoding
A method of encoding binary data into text format, commonly used for API authentication and data transmission.
### Browser Info
Information about the customer's browser and device, required for 3D Secure authentication and fraud prevention.
## C
### Capture
The process of actually charging a payment method after authorization. Some payments are authorized first, then captured later.
### Card Verification Value (CVV)
The 3 or 4-digit security code on credit/debit cards used to verify the cardholder has physical possession of the card.
### Chargeback
A reversal of a payment initiated by the cardholder's bank, typically due to fraud or dispute.
### Currency Code
Three-letter ISO 4217 code representing a currency (e.g., USD, EUR, GBP, INR).
## D
### Decline
When a payment is rejected by the issuing bank or payment processor due to various reasons (insufficient funds, invalid card, etc.).
### 3D Secure (3DS)
An authentication protocol that adds an extra layer of security for online credit card transactions.
## E
### Endpoint
A specific URL where API requests are sent to perform different operations (e.g., create payment, check status).
### Environment
Different deployment stages:
* **Sandbox**: Testing environment with simulated responses
* **Production**: Live environment processing real payments
## F
### Fraud Detection
Automated systems that analyze transactions for suspicious patterns and potential fraudulent activity.
## G
### Gateway
A service that processes payment transactions between merchants and payment networks.
### Google Pay
Google's digital wallet platform that allows customers to make payments using stored payment methods.
## H
### H2H (Host-to-Host)
Server-to-server payment processing where your backend communicates directly with Caibo's API without customer interaction.
### HMAC (Hash-based Message Authentication Code)
A cryptographic method used to verify webhook authenticity and integrity.
### HTTP Status Code
Numeric codes that indicate the result of an HTTP request (200 = success, 400 = bad request, 401 = unauthorized, etc.).
## I
### Idempotency
The property that allows the same operation to be performed multiple times without changing the result beyond the initial application.
### Issuer
The bank or financial institution that issued the customer's payment method (credit card, debit card, etc.).
## J
### JSON (JavaScript Object Notation)
A lightweight data format used for API requests and responses.
### JWT (JSON Web Token)
A secure way to transmit information between parties, sometimes used in payment tokenization.
## L
### Luhn Algorithm
A checksum formula used to validate credit card numbers and detect simple errors in typing.
## M
### Merchant
A business that accepts payments through Caibo's platform.
### Merchant ID
A unique identifier assigned to your business account with Caibo.
## O
### OpenAPI
A specification format for describing REST APIs, used to generate interactive documentation.
## P
### Payment Method
The way a customer pays for goods or services (credit card, UPI, Google Pay, bank transfer, etc.).
### Payment Request
An API call to initiate a payment transaction with customer and transaction details.
### Payment Request ID
A unique identifier assigned to each payment request for tracking and reference.
### PCI DSS (Payment Card Industry Data Security Standard)
Security standards for organizations that handle credit card information.
### Processor
A company that handles the technical aspects of processing payment transactions.
## Q
### QR Code
A two-dimensional barcode that can contain payment information for mobile payment apps.
## R
### Rate Limiting
Restrictions on the number of API requests you can make within a specific time period.
### Redirect URL
URLs where customers are sent after completing or canceling a payment:
* **Success URL**: Where customers go after successful payment
* **Failure URL**: Where customers go after failed payment
### Refund
Returning money to a customer's original payment method.
### Request ID
A unique identifier for each API request, useful for debugging and support.
## S
### Sandbox
A testing environment that simulates the production API without processing real payments.
### Settlement
The process of transferring funds from payment transactions to your merchant account.
### Signature Verification
The process of validating webhook authenticity using cryptographic signatures.
### Strong Customer Authentication (SCA)
European regulation requiring additional authentication for online payments.
## T
### Tokenization
Replacing sensitive payment data with non-sensitive tokens for secure storage and processing.
### Transaction ID
A unique identifier assigned to each completed payment transaction.
### 3D Secure
See "3D Secure (3DS)" above.
## U
### UPI (Unified Payments Interface)
India's instant payment system that allows money transfer between bank accounts through mobile apps.
### UPI ID
A unique identifier used in UPI transactions, typically in the format username\@bankcode.
## V
### Validation
The process of checking that data meets required formats and constraints before processing.
### Void
Canceling a payment transaction before it's settled, typically within the same business day.
## W
### Webhook
An HTTP callback that Caibo sends to your server to notify you of payment status changes in real-time.
### Webhook Secret
A secret key used to generate HMAC signatures for webhook verification.
### Webhook URL
The endpoint on your server where Caibo sends webhook notifications.
## Common Abbreviations
| Abbreviation | Full Term |
| ------------ | -------------------------------------------- |
| API | Application Programming Interface |
| CVV | Card Verification Value |
| H2H | Host-to-Host |
| HMAC | Hash-based Message Authentication Code |
| HTTP | Hypertext Transfer Protocol |
| JSON | JavaScript Object Notation |
| PCI DSS | Payment Card Industry Data Security Standard |
| REST | Representational State Transfer |
| SCA | Strong Customer Authentication |
| SDK | Software Development Kit |
| TLS | Transport Layer Security |
| UPI | Unified Payments Interface |
| URL | Uniform Resource Locator |
## Payment Status Values
| Status | Description |
| ------------ | --------------------------------------------- |
| `pending` | Payment initiated but not yet completed |
| `processing` | Payment is being processed |
| `completed` | Payment successfully completed |
| `failed` | Payment failed or was declined |
| `cancelled` | Payment was cancelled by customer or merchant |
| `refunded` | Payment was refunded to customer |
## Currency Codes (Common)
| Code | Currency |
| ---- | ----------------- |
| USD | US Dollar |
| EUR | Euro |
| GBP | British Pound |
| INR | Indian Rupee |
| CAD | Canadian Dollar |
| AUD | Australian Dollar |
| JPY | Japanese Yen |
| SGD | Singapore Dollar |
## HTTP Status Codes (Common)
| Code | Meaning | Description |
| ---- | --------------------- | -------------------------- |
| 200 | OK | Request successful |
| 400 | Bad Request | Invalid request parameters |
| 401 | Unauthorized | Invalid API key |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource not found |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server error |
## Need More Information?
Learn the basics of H2H integration
Frequently asked questions
Complete API documentation
Contact our support team
# Host-to-Host (H2H) Integration
Source: https://docs.caibo.digital/h2h/h2h-overview
Direct server-to-server payment processing with Caibo IPG for merchants who want full control over the payment experience.
## Overview
Host-to-Host (H2H) integration provides direct server-to-server communication between your application and Caibo IPG, giving you complete control over the payment experience. This integration method is ideal for merchants who want to handle payment processing entirely within their own systems.
## Key Features
* **Direct API Integration**: Server-to-server communication without redirects
* **Full Payment Control**: Complete control over the payment flow and user experience
* **Multiple Payment Methods**: Support for credit cards, digital wallets, UPI, and alternative payment methods
* **Real-time Processing**: Immediate payment processing and status updates
* **Custom UI/UX**: Build your own payment forms and interfaces
* **Enhanced Security**: Direct communication reduces exposure points
## Supported Payment Methods
### Credit Card Payments
* Direct credit card processing with 3D Secure support
* Tokenization for recurring payments
* Multiple currency support
### Digital Wallets
* Apple Pay integration with encrypted token processing
* Google Pay support for seamless mobile payments
* Secure token handling and validation
### Alternative Payment Methods
* UPI (Unified Payments Interface) for India market
* QR code payment generation and processing
* Bank transfer and direct debit options
## H2H Endpoints
| Payment Method | Endpoint | Description |
| -------------- | -------------------------------- | ---------------------------- |
| Credit Card | `POST /payments/h2h/{id}` | Process credit card payments |
| Apple Pay | `POST /payments/h2h/48-51,56-59` | Apple Pay token processing |
| Google Pay | `POST /payments/h2h/44-47,52-55` | Google Pay token processing |
| UPI | `POST /payments/h2h/30-31` | UPI payment processing |
| Alternative | `POST /payments/h2h/27,43` | Alternative payment methods |
## Integration Flow
### 1. Initialize Payment
Create a payment request with amount, currency, and merchant details.
### 2. Collect Payment Data
Gather payment information directly in your application:
* Credit card details
* Digital wallet tokens
* Customer information
### 3. Process Payment
Send payment data directly to Caibo H2H endpoints for processing.
### 4. Handle Response
Process the payment response and update your system accordingly.
## Security Considerations
### PCI Compliance
When handling credit card data directly, ensure your system meets PCI DSS requirements:
* Secure data transmission (HTTPS/TLS)
* Proper data encryption
* Secure storage practices
* Regular security audits
### 3D Secure Authentication
Implement 3D Secure for enhanced card transaction security:
* Challenge flow handling
* Authentication result processing
* Fallback mechanisms
### Token Security
For digital wallet payments:
* Validate payment tokens
* Verify merchant authentication
* Handle token expiration
## Error Handling
### Common Error Scenarios
* Invalid payment data
* Insufficient funds
* Card declined
* 3DS authentication failure
* Network timeouts
### Retry Logic
Implement appropriate retry mechanisms:
* Transient error handling
* Exponential backoff
* Maximum retry limits
## Testing
### Sandbox Environment
Use the sandbox environment for testing:
* Test all payment methods
* Simulate various scenarios
* Validate error handling
### Test Data
Use provided test credentials:
* Test card numbers
* Mock wallet tokens
* Simulated responses
## 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.
* Method availability in Production depends on your tenant's configuration and compliance enablement.
* See the list of supported methods in the H2H Payment Methods page: `/h2h/payment-methods`.
## Next Steps
Explore detailed H2H endpoint documentation
View code examples for H2H integration
Learn about H2H security best practices
# H2H Notifications
Source: https://docs.caibo.digital/h2h/notifications
Webhook notifications for Host-to-Host payment status updates and handling
# H2H Notifications
Host-to-Host API provides real-time payment status notifications through webhooks, enabling automatic updates when payment statuses change. This guide covers webhook setup, handling, and security best practices.
## Webhook Overview
### Notification System
* **Real-time Updates**: Automatic payment status notifications via webhooks
* **HTTP POST**: Notifications sent as HTTP POST requests
* **Content Type**: `application/x-www-form-urlencoded`
* **Requirement**: Notifications only sent if notify URL is configured
### Configuration
* **Dashboard Setup**: Set notify URL in dashboard profile page
* **Per-Request Override**: Override notify URL in individual payment requests
* **Multiple Endpoints**: Configure different URLs for different notification types
## Notification Fields
| Field | Description |
| ------------------------ | ---------------------------------------------- |
| `id` | Payment request identifier |
| `transactionId` | Payment request transaction identifier |
| `transactionStatusId` | Transaction status: 1 – approved, 2 – declined |
| `paymentRequestStatusId` | Payment status: 1 – paid, 2 – unpaid |
| `merchantId` | Merchant identifier (from control panel) |
| `unit` | Payment currency |
| `grossAmount` | Payment gross amount including fees |
| `fee` | Payment fee amount |
| `netAmount` | Net amount deposited to merchant wallet |
| `referenceId` | Custom reference details |
| `notes` | Payment notes |
| `clientId` | Payment sender customer identifier |
| `clientName` | Payment sender customer name |
| `clientEmail` | Payment sender customer email |
| `clientPhone` | Payment sender customer phone |
| `clientMemberId` | Payment sender customer member identifier |
| `message` | Payment failure reason message |
| `code` | Payment failure reason code |
## Example Notification
```
id=16772761082427695&transactionId=265111&transactionStatusId=1&paymentRequestStatusId=1&merchantId=16762420400394816&unit=USD&grossAmount=10&fee=0.5&netAmount=9.5&referenceId=12345¬es=Payment notes&clientId=16772748432912191&clientName=Client Name&clientEmail=client@email.com&clientPhone=1234567890&clientMemberId=12345&message=Stolen Card&code=008
```
## Webhook Handler Implementation
### Basic Webhook Handler
```javascript theme={null}
// Handle payment status notifications
app.post('/webhooks/payment-notification', (req, res) => {
try {
const notification = req.body;
// Verify notification authenticity (implement signature verification)
if (!verifyNotificationSignature(req)) {
return res.status(401).send('Unauthorized');
}
// Process payment status update
const {
transactionId,
merchantReference,
status,
amount,
currency,
timestamp
} = notification;
// Update your database
updatePaymentStatus(merchantReference, {
transactionId,
status,
amount,
currency,
updatedAt: timestamp
});
// Handle different status types
switch (status) {
case 'completed':
handleSuccessfulPayment(merchantReference);
break;
case 'failed':
handleFailedPayment(merchantReference, notification.errorCode);
break;
case 'pending':
handlePendingPayment(merchantReference);
break;
case 'cancelled':
handleCancelledPayment(merchantReference);
break;
}
// Always return 200 OK to acknowledge receipt
res.status(200).send('OK');
} catch (error) {
console.error('Webhook processing error:', error);
res.status(200).send('OK'); // Still return 200 to prevent retries
}
});
```
### Advanced Webhook Handler
```javascript theme={null}
const crypto = require('crypto');
// Enhanced webhook handler with validation and processing
app.post('/webhooks/payment-notification', async (req, res) => {
const startTime = Date.now();
try {
// Parse notification data
const notification = parseNotificationData(req.body);
// Verify webhook signature
if (!verifyWebhookSignature(req, notification)) {
console.warn('Invalid webhook signature');
return res.status(401).json({ error: 'Unauthorized' });
}
// Check for duplicate notifications
if (await isDuplicateNotification(notification.id, notification.transactionId)) {
console.log('Duplicate notification ignored');
return res.status(200).send('OK');
}
// Process notification
await processPaymentNotification(notification);
// Log successful processing
const processingTime = Date.now() - startTime;
console.log(`Webhook processed successfully in ${processingTime}ms`);
res.status(200).send('OK');
} catch (error) {
console.error('Webhook processing failed:', error);
// Log error details for debugging
await logWebhookError(req, error);
// Return 200 to prevent webhook retries for non-recoverable errors
res.status(200).send('OK');
}
});
function parseNotificationData(body) {
// Parse URL-encoded data
const params = new URLSearchParams(body);
return {
id: params.get('id'),
transactionId: params.get('transactionId'),
transactionStatusId: parseInt(params.get('transactionStatusId')),
paymentRequestStatusId: parseInt(params.get('paymentRequestStatusId')),
merchantId: params.get('merchantId'),
unit: params.get('unit'),
grossAmount: parseFloat(params.get('grossAmount')),
fee: parseFloat(params.get('fee')),
netAmount: parseFloat(params.get('netAmount')),
referenceId: params.get('referenceId'),
notes: params.get('notes'),
clientId: params.get('clientId'),
clientName: params.get('clientName'),
clientEmail: params.get('clientEmail'),
clientPhone: params.get('clientPhone'),
clientMemberId: params.get('clientMemberId'),
message: params.get('message'),
code: params.get('code')
};
}
```
## Notification Verification
### Signature Verification
Verify notification authenticity using HMAC SHA512 signature:
```javascript theme={null}
function verifyNotificationSignature(req) {
const signature = req.headers['x-signature'];
const payload = req.body;
const apiKey = process.env.Caibo_API_KEY;
if (!signature || !payload || !apiKey) {
return false;
}
const hash = crypto
.createHmac('sha512', apiKey)
.update(payload)
.digest('base64');
return hash === signature;
}
```
### Verification Process
1. **Header Check**: Check `X-Signature` header in notification request
2. **Algorithm**: HMAC SHA512 hash in Base64 format
3. **Key**: Use your API key from the control panel
```javascript theme={null}
// Complete signature verification example
function verifyWebhookSignature(req, notification) {
const receivedSignature = req.headers['x-signature'];
if (!receivedSignature) {
console.warn('Missing X-Signature header');
return false;
}
const payload = req.rawBody || req.body;
const apiKey = process.env.Caibo_API_KEY;
const expectedSignature = crypto
.createHmac('sha512', apiKey)
.update(payload, 'utf8')
.digest('base64');
// Use timing-safe comparison
return crypto.timingSafeEqual(
Buffer.from(receivedSignature),
Buffer.from(expectedSignature)
);
}
```
## Status Processing
### Payment Status Mapping
```javascript theme={null}
function mapPaymentStatus(transactionStatusId, paymentRequestStatusId) {
// Transaction Status: 0 – waiting, 1 – approved, 2 – declined, 3 – pending
// Payment Request Status: 1 – paid, 2 – unpaid, 3 – cancelled
if (transactionStatusId === 1 && paymentRequestStatusId === 1) {
return 'completed';
} else if (transactionStatusId === 2) {
return 'failed';
} else if (transactionStatusId === 3) {
return 'pending';
} else if (paymentRequestStatusId === 3) {
return 'cancelled';
} else {
return 'unknown';
}
}
```
### Business Logic Processing
```javascript theme={null}
async function processPaymentNotification(notification) {
const status = mapPaymentStatus(
notification.transactionStatusId,
notification.paymentRequestStatusId
);
// Update payment record
await updatePaymentRecord(notification.referenceId, {
transactionId: notification.transactionId,
status: status,
grossAmount: notification.grossAmount,
fee: notification.fee,
netAmount: notification.netAmount,
updatedAt: new Date()
});
// Execute business logic based on status
switch (status) {
case 'completed':
await handlePaymentSuccess(notification);
break;
case 'failed':
await handlePaymentFailure(notification);
break;
case 'pending':
await handlePaymentPending(notification);
break;
case 'cancelled':
await handlePaymentCancelled(notification);
break;
}
// Send internal notifications
await sendInternalNotification(notification, status);
}
async function handlePaymentSuccess(notification) {
// Fulfill order
await fulfillOrder(notification.referenceId);
// Send confirmation email
await sendPaymentConfirmation(notification.clientEmail, {
amount: notification.netAmount,
currency: notification.unit,
transactionId: notification.transactionId
});
// Update inventory
await updateInventory(notification.referenceId);
}
async function handlePaymentFailure(notification) {
// Cancel order
await cancelOrder(notification.referenceId);
// Send failure notification
await sendPaymentFailureNotification(notification.clientEmail, {
reason: notification.message,
code: notification.code
});
// Release inventory
await releaseInventory(notification.referenceId);
}
```
## Error Handling
### Duplicate Prevention
```javascript theme={null}
async function isDuplicateNotification(paymentId, transactionId) {
const key = `webhook_${paymentId}_${transactionId}`;
// Check if we've already processed this notification
const exists = await redis.exists(key);
if (exists) {
return true;
}
// Mark as processed (expire after 24 hours)
await redis.setex(key, 86400, '1');
return false;
}
```
### Retry Logic
```javascript theme={null}
async function processWithRetry(notification, maxRetries = 3) {
let attempt = 0;
while (attempt < maxRetries) {
try {
await processPaymentNotification(notification);
return; // Success
} catch (error) {
attempt++;
if (attempt >= maxRetries) {
// Final attempt failed, log and alert
await logCriticalError(notification, error);
await sendAlertToAdmins(notification, error);
throw error;
}
// Wait before retry (exponential backoff)
await delay(Math.pow(2, attempt) * 1000);
}
}
}
```
## Security Best Practices
### Webhook Security
1. **Signature Verification**: Always verify webhook signatures
2. **HTTPS Only**: Use HTTPS endpoints for webhook URLs
3. **IP Whitelisting**: Restrict webhook sources to known IPs
4. **Rate Limiting**: Implement rate limiting on webhook endpoints
### Data Protection
1. **Sensitive Data**: Never log sensitive payment information
2. **PCI Compliance**: Follow PCI DSS guidelines for payment data
3. **Access Control**: Restrict access to webhook processing systems
4. **Audit Logging**: Maintain audit logs of all webhook processing
### Error Handling
1. **Graceful Failures**: Handle errors gracefully without exposing system details
2. **Monitoring**: Monitor webhook processing success rates
3. **Alerting**: Set up alerts for webhook processing failures
4. **Backup Processing**: Implement backup processing for failed webhooks
## Testing and Validation
### Webhook Testing
```javascript theme={null}
// Test webhook endpoint
async function testWebhookEndpoint() {
const testNotification = {
id: 'test_12345',
transactionId: 'test_txn_67890',
transactionStatusId: 1,
paymentRequestStatusId: 1,
merchantId: 'test_merchant',
unit: 'USD',
grossAmount: 10.00,
fee: 0.50,
netAmount: 9.50,
referenceId: 'test_order_123'
};
// Send test notification
const response = await fetch('/webhooks/payment-notification', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Signature': generateTestSignature(testNotification)
},
body: new URLSearchParams(testNotification).toString()
});
console.log('Test webhook response:', response.status);
}
```
## Best Practices
### Implementation
1. **Idempotency**: Handle duplicate notifications gracefully
2. **Fast Response**: Respond quickly to webhook requests (\< 30 seconds)
3. **Async Processing**: Process notifications asynchronously when possible
4. **Status Codes**: Return appropriate HTTP status codes
### Monitoring
1. **Success Rates**: Monitor webhook processing success rates
2. **Response Times**: Track webhook processing response times
3. **Error Patterns**: Analyze error patterns and common failures
4. **Alert Thresholds**: Set up appropriate alerting thresholds
### Reliability
1. **Retry Mechanisms**: Implement retry logic for failed processing
2. **Dead Letter Queue**: Use dead letter queues for failed notifications
3. **Backup Processing**: Implement backup processing mechanisms
4. **Health Checks**: Regular health checks on webhook endpoints
## Next Steps
Learn about H2H API request format and parameters
Understand H2H API response handling
Explore available payment methods and implementations
# Apple Pay Payment
Source: https://docs.caibo.digital/h2h/payment-api/apple-payment
POST /payments/apple/{id}
Process Apple Pay payment endpoint
# Apple Pay Session
Source: https://docs.caibo.digital/h2h/payment-api/apple-session
GET /payments/apple-session/{id}
Create Apple Pay payment session endpoint
# Apple Pay Session Validation
Source: https://docs.caibo.digital/h2h/payment-api/apple-session-validation
GET /payments/validate-apple-session
Validate Apple Pay session endpoint
# Card Member Payment
Source: https://docs.caibo.digital/h2h/payment-api/card-member
POST /payments/cardMember/{id}
Process card member payment endpoint
# Card Member Confirmation
Source: https://docs.caibo.digital/h2h/payment-api/card-member-confirm
POST /payments/cardMemberConfirm/{id}
Process card member confirmation endpoint
# Credit Card Payment
Source: https://docs.caibo.digital/h2h/payment-api/credit-card-endpoint
POST /payments/creditCard/{id}
Process credit card payment endpoint
# Credit Card Status
Source: https://docs.caibo.digital/h2h/payment-api/credit-card-status
GET /payments/creditCard/status/{paymentId}
Check credit card payment status endpoint
# Credit Card Token Payment
Source: https://docs.caibo.digital/h2h/payment-api/credit-card-token
POST /payments/creditCardToken/{id}
Process tokenized credit card payment endpoint
# Google Pay Payment
Source: https://docs.caibo.digital/h2h/payment-api/google-pay-endpoint
POST /payments/google/{id}
Process Google Pay payment endpoint
# H2H Payment Processing
Source: https://docs.caibo.digital/h2h/payment-api/h2h-payment
POST /payments/h2h/{id}
Process Host-to-Host payment endpoint
# H2H Payment Refund
Source: https://docs.caibo.digital/h2h/payment-api/h2h-refund
GET /payments/h2h/refund/{transactionId}
Process H2H payment refund endpoint
# QR Code Payment
Source: https://docs.caibo.digital/h2h/payment-api/qr-payment
POST /payments/qr/{id}
Process QR code payment endpoint
# 3D Secure Redirect
Source: https://docs.caibo.digital/h2h/payment-api/threeds-redirect
GET /payments/threeds/redirect/{transactionId}
Handle 3D Secure redirect endpoint
# 3D Secure Status
Source: https://docs.caibo.digital/h2h/payment-api/threeds-status
GET /payments/threeds/status/{transaction3dsId}
Check 3D Secure transaction status endpoint
# UPI Payment
Source: https://docs.caibo.digital/h2h/payment-api/upi-endpoint
POST /payments/upi/{id}
Process UPI payment endpoint
# Payment Methods
Source: https://docs.caibo.digital/h2h/payment-methods
Choose your payment integration method with detailed examples and implementation guides
# Overview
Explore different payment integration options with comprehensive examples and step-by-step implementation guides.
## Credit Card Payments
Complete credit card payment with 3D Secure authentication, browser fingerprinting, and PCI compliance features.
**Features:**
* 3D Secure authentication
* Browser info collection
* Multiple card types (Visa, Mastercard, Amex)
* CVV verification
## Alternative Payments
Simplified payment requests for bank transfers, digital wallets, and other non-card payment methods.
**Features:**
* No card details required
* Simplified customer data
* Bank transfers and ACH
* Buy now, pay later options
## Regional Payment Methods
Unified Payments Interface (UPI) integration for instant payments in the Indian market with real-time processing.
**Features:**
* Instant real-time transfers
* UPI ID validation
* Mobile-optimized flow
* 24/7 availability
## Digital Wallets
Secure Google Pay integration with token-based authentication and seamless mobile checkout experience.
**Features:**
* Token-based security
* Mobile-first design
* Instant checkout
* Biometric authentication
Native Apple Pay integration with Touch ID/Face ID authentication and secure element protection.
**Features:**
* Touch ID/Face ID support
* Secure element encryption
* Safari integration
* Device-specific tokens
## Advanced Integration
Advanced wallet payment combining card details with wallet authentication for enhanced security.
**Features:**
* Card + wallet authentication
* Enhanced security
* Fraud prevention
* Multi-factor verification
High-volume batch payment processing using SFTP file uploads for enterprise-scale transactions.
**Features:**
* Bulk payment processing
* CSV file format
* Automated workflows
* Enterprise scalability
## Payment Monitoring
Real-time payment status monitoring with comprehensive transaction tracking and reporting.
**Features:**
* Real-time status updates
* Transaction history
* Status polling
* Detailed reporting
Automated payment notifications with secure webhook verification and real-time updates.
**Features:**
* Instant notifications
* HMAC signature verification
* Retry mechanisms
* Event filtering
## Implementation Guides
Complete Host-to-Host API integration guide with authentication, endpoints, and best practices.
Comprehensive error code reference with troubleshooting guides and resolution strategies.
Security best practices, PCI compliance guidelines, and fraud prevention strategies.
## Getting Started
1. **Choose Payment Method**: Select the payment methods that best fit your business needs
2. **Review Examples**: Study the detailed implementation examples for your chosen methods
3. **Test Integration**: Use the provided test data to implement and test your integration
4. **Go Live**: Deploy with confidence using our comprehensive guides and best practices
## Need Help?
* **API Reference**: Complete endpoint documentation with OpenAPI specification
* **Test Environment**: Sandbox environment for safe testing and development
* **Support**: Technical support and integration assistance available
* **Features**: Direct server integration, full merchant control
* **Security**: Enhanced PCI requirements
### H2H Digital Wallets
* **Apple Pay H2H**: `POST /payments/h2h/48-51,56-59`
* **Google Pay H2H**: `POST /payments/h2h/44-47,52-55`
* **Features**: Server-to-server token processing
### H2H Alternative Methods
* **UPI H2H**: `POST /payments/h2h/30-31`
* **Alternative Methods**: `POST /payments/h2h/27,43`
## Payment Status & Monitoring
### Status Checking
* **Credit Card Status**: `GET /payments/creditCard/status/{paymentId}`
* **3DS Status**: `GET /payments/threeds/status/{transaction3dsId}`
* **3DS Redirect**: `GET /payments/threeds/redirect/{transactionId}`
### Transaction Management
* **Transaction Details**: `GET /transactions/{id}`
* **H2H Refunds**: `GET /payments/h2h/refund/{transactionId}`
## Integration Considerations
### Security Requirements
* **PCI DSS Compliance**: Required for direct card data handling
* **3D Secure**: Recommended for enhanced security
* **Tokenization**: Use for recurring payments
### Regional Compliance
* **Europe**: Strong Customer Authentication (SCA) compliance
* **India**: RBI guidelines for UPI transactions
* **Global**: Anti-money laundering (AML) requirements
### Error Handling
* **Common Errors**: Invalid card details, insufficient funds, expired cards
* **Retry Logic**: Implement appropriate retry mechanisms
* **Fallback Options**: Configure alternative payment methods
## Best Practices
### Payment Method Selection
1. **Analyze Customer Base**: Choose methods popular in your target markets
2. **Conversion Optimization**: Offer multiple options to reduce cart abandonment
3. **Mobile Optimization**: Prioritize mobile-friendly payment methods
### Implementation Tips
1. **Progressive Enhancement**: Start with basic card processing, add advanced methods
2. **Testing Strategy**: Thoroughly test all payment flows in sandbox
3. **Monitoring**: Implement comprehensive logging and monitoring
### Performance Optimization
1. **Tokenization**: Use tokens for returning customers
2. **Caching**: Cache payment method configurations
3. **Async Processing**: Handle callbacks asynchronously
## Next Steps
Learn how to create and manage payment requests
Explore direct server-to-server integration
Handle payment status notifications
# Alternative Payment Methods
Source: https://docs.caibo.digital/h2h/payments/alternative
Process alternative payments through Host-to-Host API including bank transfers, digital wallets, and BNPL options
# Alternative Payment Methods
Process alternative payment methods through the Host-to-Host API without requiring card details. This includes bank transfers, ACH payments, digital wallets, and buy-now-pay-later options.
## Overview
Alternative payment methods provide:
* **No Card Required**: Process payments without credit/debit card details
* **Simplified Flow**: Reduced customer data requirements
* **Regional Support**: Local payment methods for different markets
* **Lower Fees**: Often lower processing fees than card payments
* **Bank Integration**: Direct bank account payments
## Required Parameters
### Customer Information
| Parameter | Description | Required | Example |
| ------------- | ------------------------- | -------- | --------------------------------------------- |
| `name` | Customer full name | YES | "Jane Smith" |
| `email` | Customer email address | YES | "[jane@example.com](mailto:jane@example.com)" |
| `phoneNumber` | Customer phone number | YES | "+1234567890" |
| `address` | Customer address | YES | "456 Oak Avenue" |
| `city` | Customer city | YES | "Los Angeles" |
| `state` | State or province | YES | "CA" |
| `postalCode` | ZIP or postal code | YES | "90210" |
| `country` | Country code (ISO 3166-1) | YES | "US" |
### Transaction Details
| Parameter | Description | Required | Example |
| -------------- | ------------------ | -------- | ------------------- |
| `amount` | Payment amount | YES | 150.00 |
| `unit` | Currency code | YES | "USD" |
| `originDomain` | Merchant domain | YES | "store.example.com" |
| `referenceId` | Merchant reference | NO | "INV-67890" |
## Complete Request Example
```json theme={null}
{
"name": "Jane Smith",
"email": "jane@example.com",
"phoneNumber": "+1234567890",
"address": "456 Oak Avenue",
"city": "Los Angeles",
"state": "CA",
"postalCode": "90210",
"country": "US",
"amount": 150.00,
"unit": "USD",
"originDomain": "store.example.com",
"referenceId": "INV-67890",
"notifyUrl": "https://api.example.com/webhook",
"successUrl": "https://store.example.com/success",
"failureUrl": "https://store.example.com/failure"
}
```
## Implementation Example
```javascript theme={null}
async function processAlternativePayment(paymentData) {
const apiEndpoint = process.env.Caibo_H2H_ENDPOINT;
const apiKey = process.env.Caibo_API_KEY;
try {
const response = await fetch(apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': apiKey
},
body: JSON.stringify({
name: paymentData.customerName,
email: paymentData.customerEmail,
phoneNumber: paymentData.customerPhone,
address: paymentData.customerAddress.street,
city: paymentData.customerAddress.city,
state: paymentData.customerAddress.state,
postalCode: paymentData.customerAddress.postalCode,
country: paymentData.customerAddress.country,
amount: paymentData.amount,
unit: paymentData.currency,
originDomain: paymentData.merchantDomain,
referenceId: paymentData.invoiceId,
notifyUrl: paymentData.webhookUrl,
successUrl: paymentData.successUrl,
failureUrl: paymentData.failureUrl
})
});
const result = await response.json();
if (response.ok) {
return {
success: true,
paymentRequestId: result.paymentRequestId,
redirectUrl: result.redirectUrl,
status: result.status
};
} else {
return {
success: false,
error: result.error,
message: result.message
};
}
} catch (error) {
return {
success: false,
error: 'NETWORK_ERROR',
message: error.message
};
}
}
```
## Supported Methods
### Bank Transfers
* **ACH Payments**: Direct bank account transfers
* **Wire Transfers**: International bank transfers
* **SEPA**: European bank transfers
* **Faster Payments**: UK instant bank transfers
### Digital Wallets
* **PayPal**: PayPal account payments
* **Skrill**: Skrill wallet payments
* **Neteller**: Neteller wallet payments
* **Regional Wallets**: Local digital wallet solutions
### Buy Now, Pay Later
* **Klarna**: Klarna payment plans
* **Afterpay**: Afterpay installments
* **Affirm**: Affirm financing
* **Sezzle**: Sezzle payment plans
## Error Handling
### Common Error Codes
* **INVALID\_BANK\_ACCOUNT**: Invalid bank account details
* **INSUFFICIENT\_FUNDS**: Insufficient funds in account
* **BANK\_DECLINED**: Bank declined the transaction
* **PAYMENT\_METHOD\_UNAVAILABLE**: Selected method not available
## Next Steps
Learn about UPI payment integration
Track alternative payment status
# Credit Card Payments
Source: https://docs.caibo.digital/h2h/payments/credit-card-payments
POST /payments/creditCard/{id}
Complete guide to processing credit card payments through Host-to-Host API with 3D Secure support
# Credit Card Payments
Process credit card payments directly through the Host-to-Host API with full control over the payment flow, including 3D Secure authentication and advanced fraud protection.
## Overview
Credit card processing through H2H API provides:
* **Direct Processing**: Server-to-server credit card processing
* **3D Secure Support**: Enhanced security with 3DS authentication
* **Multiple Card Types**: Support for Visa, Mastercard, American Express, and more
* **Real-time Processing**: Immediate payment processing and response
* **Fraud Protection**: Advanced fraud detection and prevention
## Required Parameters
### Core Credit Card Fields
| Parameter | Description | Required | Example |
| ------------ | ----------------------- | -------- | ------------------ |
| `name` | Card holder full name | YES | "John Doe" |
| `number` | Credit card number | YES | "4111111111111111" |
| `expiration` | Card expiration (MM/YY) | YES | "12/25" |
| `cvv` | Card verification value | YES | "123" |
### Customer Information
| Parameter | Description | Required | Example |
| ------------- | ------------------------- | -------- | --------------------------------------------- |
| `email` | Customer email address | YES | "[john@example.com](mailto:john@example.com)" |
| `phoneNumber` | Customer phone number | YES | "+1234567890" |
| `address` | Billing address | YES | "123 Main St" |
| `city` | Billing city | YES | "New York" |
| `state` | State or province | YES | "NY" |
| `postalCode` | ZIP or postal code | YES | "10001" |
| `country` | Country code (ISO 3166-1) | YES | "US" |
### Transaction Details
| Parameter | Description | Required | Example |
| -------------- | ------------------ | -------- | ------------------ |
| `amount` | Payment amount | YES | 99.99 |
| `unit` | Currency code | YES | "USD" |
| `originDomain` | Merchant domain | YES | "shop.example.com" |
| `referenceId` | Merchant reference | NO | "ORDER-12345" |
### Optional Parameters
| Parameter | Description | Required | Example |
| ------------------- | ------------------------- | -------- | ---------------------------------------------------------------------- |
| `captureDelayHours` | Capture delay (0-7 hours) | NO | 0 |
| `notifyUrl` | Webhook notification URL | NO | "[https://api.example.com/webhook](https://api.example.com/webhook)" |
| `successUrl` | Success redirect URL | NO | "[https://shop.example.com/success](https://shop.example.com/success)" |
| `failureUrl` | Failure redirect URL | NO | "[https://shop.example.com/failure](https://shop.example.com/failure)" |
| `browserInfo` | 3DS browser information | NO | See browser info object |
## Browser Info Object
For 3D Secure authentication, include browser information:
```json theme={null}
{
"browserAcceptHeader": "application/json, text/plain, */*",
"browserColorDepth": "24",
"browserIP": "192.168.1.100",
"browserJavaEnabled": false,
"browserJavascriptEnabled": true,
"browserLanguage": "en-US",
"browserScreenHeight": "1080",
"browserScreenWidth": "1920",
"browserTZ": "300",
"browserUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
```
## Complete Request Example
```json theme={null}
{
"name": "John Doe",
"number": "4111111111111111",
"expiration": "12/25",
"cvv": "123",
"email": "john@example.com",
"phoneNumber": "+1234567890",
"address": "123 Main Street",
"city": "New York",
"state": "NY",
"postalCode": "10001",
"country": "US",
"amount": 99.99,
"unit": "USD",
"originDomain": "shop.example.com",
"referenceId": "ORDER-12345",
"notifyUrl": "https://api.example.com/webhook",
"successUrl": "https://shop.example.com/success",
"failureUrl": "https://shop.example.com/failure",
"captureDelayHours": 0,
"browserInfo": {
"browserAcceptHeader": "application/json, text/plain, */*",
"browserColorDepth": "24",
"browserIP": "192.168.1.100",
"browserJavaEnabled": false,
"browserJavascriptEnabled": true,
"browserLanguage": "en-US",
"browserScreenHeight": "1080",
"browserScreenWidth": "1920",
"browserTZ": "300",
"browserUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
}
}
```
## Implementation Example
### JavaScript/Node.js
```javascript theme={null}
async function processCreditCardPayment(paymentData) {
const apiEndpoint = process.env.Caibo_H2H_ENDPOINT;
const apiKey = process.env.Caibo_API_KEY;
try {
const response = await fetch(apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': apiKey
},
body: JSON.stringify({
// Card details
name: paymentData.cardholderName,
number: paymentData.cardNumber,
expiration: paymentData.expiryDate,
cvv: paymentData.cvv,
// Customer info
email: paymentData.customerEmail,
phoneNumber: paymentData.customerPhone,
address: paymentData.billingAddress.street,
city: paymentData.billingAddress.city,
state: paymentData.billingAddress.state,
postalCode: paymentData.billingAddress.postalCode,
country: paymentData.billingAddress.country,
// Transaction
amount: paymentData.amount,
unit: paymentData.currency,
originDomain: paymentData.merchantDomain,
referenceId: paymentData.orderId,
// URLs
notifyUrl: paymentData.webhookUrl,
successUrl: paymentData.successUrl,
failureUrl: paymentData.failureUrl,
// 3DS
browserInfo: paymentData.browserInfo
})
});
const result = await response.json();
if (response.ok) {
return {
success: true,
paymentRequestId: result.paymentRequestId,
redirectUrl: result.redirectUrl,
status: result.status
};
} else {
return {
success: false,
error: result.error,
message: result.message
};
}
} catch (error) {
return {
success: false,
error: 'NETWORK_ERROR',
message: error.message
};
}
}
```
### PHP
```php theme={null}
$paymentData['cardholderName'],
'number' => $paymentData['cardNumber'],
'expiration' => $paymentData['expiryDate'],
'cvv' => $paymentData['cvv'],
// Customer info
'email' => $paymentData['customerEmail'],
'phoneNumber' => $paymentData['customerPhone'],
'address' => $paymentData['billingAddress']['street'],
'city' => $paymentData['billingAddress']['city'],
'state' => $paymentData['billingAddress']['state'],
'postalCode' => $paymentData['billingAddress']['postalCode'],
'country' => $paymentData['billingAddress']['country'],
// Transaction
'amount' => $paymentData['amount'],
'unit' => $paymentData['currency'],
'originDomain' => $paymentData['merchantDomain'],
'referenceId' => $paymentData['orderId'],
// URLs
'notifyUrl' => $paymentData['webhookUrl'],
'successUrl' => $paymentData['successUrl'],
'failureUrl' => $paymentData['failureUrl'],
// 3DS
'browserInfo' => $paymentData['browserInfo']
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiEndpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'X-API-Key: ' . $apiKey
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode($response, true);
if ($httpCode === 200) {
return [
'success' => true,
'paymentRequestId' => $result['paymentRequestId'],
'redirectUrl' => $result['redirectUrl'] ?? null,
'status' => $result['status']
];
} else {
return [
'success' => false,
'error' => $result['error'] ?? 'UNKNOWN_ERROR',
'message' => $result['message'] ?? 'Payment processing failed'
];
}
}
?>
```
## 3D Secure Authentication
### 3DS Flow
1. **Initial Request**: Submit payment with browser info
2. **3DS Check**: System determines if 3DS is required
3. **Challenge**: Customer completes 3DS challenge if needed
4. **Final Processing**: Payment processed after authentication
### Browser Info Collection
```javascript theme={null}
function collectBrowserInfo() {
return {
browserAcceptHeader: navigator.userAgent,
browserColorDepth: screen.colorDepth.toString(),
browserIP: '', // Server-side detection
browserJavaEnabled: navigator.javaEnabled(),
browserJavascriptEnabled: true,
browserLanguage: navigator.language,
browserScreenHeight: screen.height.toString(),
browserScreenWidth: screen.width.toString(),
browserTZ: new Date().getTimezoneOffset().toString(),
browserUserAgent: navigator.userAgent
};
}
```
## Error Handling
### Common Error Codes
* **INVALID\_CARD**: Invalid card number or format
* **EXPIRED\_CARD**: Card has expired
* **INSUFFICIENT\_FUNDS**: Insufficient funds on card
* **CARD\_DECLINED**: Card declined by issuer
* **CVV\_MISMATCH**: CVV verification failed
* **3DS\_FAILED**: 3D Secure authentication failed
### Error Response Example
```json theme={null}
{
"success": false,
"error": "CARD_DECLINED",
"message": "The card was declined by the issuing bank",
"code": "002",
"details": {
"declineReason": "Insufficient funds",
"issuerResponse": "51"
}
}
```
## Security Best Practices
### PCI DSS Compliance
* **Never Store**: Never store card numbers, CVV, or expiration dates
* **Secure Transmission**: Use HTTPS for all API communications
* **Data Minimization**: Only collect necessary card data
* **Access Control**: Restrict access to payment processing systems
### Implementation Security
* **API Key Protection**: Store API keys securely
* **Input Validation**: Validate all input parameters
* **Error Handling**: Don't expose sensitive information in errors
* **Logging**: Log transactions without sensitive data
## Testing
### Test Card Numbers
| Card Type | Number | CVV | Expiry |
| ---------------- | ---------------- | ---- | ------ |
| Visa | 4111111111111111 | 123 | 12/25 |
| Mastercard | 5555555555554444 | 123 | 12/25 |
| American Express | 378282246310005 | 1234 | 12/25 |
### Test Scenarios
* **Successful Payment**: Use valid test card numbers
* **Declined Payment**: Use specific test numbers for declines
* **3DS Challenge**: Test 3D Secure authentication flows
* **Network Errors**: Test timeout and network failure scenarios
## Best Practices
### Implementation
1. **Validation**: Validate card data before API calls
2. **Error Handling**: Implement comprehensive error handling
3. **Retry Logic**: Use appropriate retry mechanisms
4. **Monitoring**: Monitor payment success rates
### User Experience
1. **Real-time Validation**: Validate card details as user types
2. **Clear Errors**: Provide clear, actionable error messages
3. **Loading States**: Show processing indicators
4. **Security Indicators**: Display security badges and SSL indicators
### Performance
1. **Connection Pooling**: Use HTTP connection pooling
2. **Timeout Handling**: Set appropriate timeout values
3. **Async Processing**: Handle responses asynchronously
4. **Caching**: Cache non-sensitive configuration data
## Next Steps
Learn about 3D Secure authentication implementation
Track credit card payment status
Handle payment status notifications
# Google Pay Integration
Source: https://docs.caibo.digital/h2h/payments/google-pay
Process Google Pay payments through Host-to-Host API with enhanced security and seamless mobile experience
# Google Pay Integration
Process Google Pay payments through the Host-to-Host API with enhanced security features, tokenization, and optimized mobile experience for both Android and web platforms.
## Overview
Google Pay integration provides:
* **Enhanced Security**: Tokenized payments with device authentication
* **Mobile Optimized**: Native Android and web integration
* **Quick Checkout**: Streamlined payment experience
* **Biometric Auth**: Fingerprint and face authentication support
* **Global Reach**: Available in 40+ countries
* **Fraud Protection**: Advanced fraud detection and prevention
## Required Parameters
### Google Pay Specific Fields
| Parameter | Description | Required | Example |
| -------------- | ------------------------ | -------- | ------------------------- |
| `paymentToken` | Google Pay payment token | YES | "eyJhbGciOiJSUzI1NiIs..." |
| `name` | Customer full name | YES | "John Smith" |
### Customer Information
| Parameter | Description | Required | Example |
| ------------- | ------------------------- | -------- | --------------------------------------------- |
| `email` | Customer email address | YES | "[john@example.com](mailto:john@example.com)" |
| `phoneNumber` | Customer phone number | YES | "+1234567890" |
| `address` | Customer address | YES | "123 Main Street" |
| `city` | Customer city | YES | "New York" |
| `state` | State or province | YES | "NY" |
| `postalCode` | ZIP or postal code | YES | "10001" |
| `country` | Country code (ISO 3166-1) | YES | "US" |
### Transaction Details
| Parameter | Description | Required | Example |
| -------------- | ------------------ | -------- | ------------------ |
| `amount` | Payment amount | YES | 99.99 |
| `unit` | Currency code | YES | "USD" |
| `originDomain` | Merchant domain | YES | "shop.example.com" |
| `referenceId` | Merchant reference | NO | "GPY-54321" |
## Complete Request Example
```json theme={null}
{
"name": "John Smith",
"paymentToken": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJHb29nbGUiLCJhdWQiOiJtZXJjaGFudC5leGFtcGxlLmNvbSIsInBheW1lbnRNZXRob2QiOnsiZGlzcGxheU5hbWUiOiJWaXNhIOKAoiDigoExMjM0IiwidHlwZSI6IkNBUkQifX0",
"email": "john@example.com",
"phoneNumber": "+1234567890",
"address": "123 Main Street",
"city": "New York",
"state": "NY",
"postalCode": "10001",
"country": "US",
"amount": 99.99,
"unit": "USD",
"originDomain": "shop.example.com",
"referenceId": "GPY-54321",
"notifyUrl": "https://api.example.com/webhook",
"successUrl": "https://shop.example.com/success",
"failureUrl": "https://shop.example.com/failure",
"browserInfo": {
"browserAcceptHeader": "application/json, text/plain, */*",
"browserColorDepth": "24",
"browserIP": "192.168.1.100",
"browserJavaEnabled": false,
"browserJavascriptEnabled": true,
"browserLanguage": "en-US",
"browserScreenHeight": "1080",
"browserScreenWidth": "1920",
"browserTZ": "-300",
"browserUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
}
```
## Implementation Example
### JavaScript/Web Integration
```javascript theme={null}
// Google Pay API configuration
const baseRequest = {
apiVersion: 2,
apiVersionMinor: 0
};
const allowedCardNetworks = ["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"];
const allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];
const tokenizationSpecification = {
type: 'PAYMENT_GATEWAY',
parameters: {
'gateway': 'caibo',
'gatewayMerchantId': process.env.Caibo_MERCHANT_ID
}
};
const baseCardPaymentMethod = {
type: 'CARD',
parameters: {
allowedAuthMethods: allowedCardAuthMethods,
allowedCardNetworks: allowedCardNetworks
}
};
const cardPaymentMethod = Object.assign(
{},
baseCardPaymentMethod,
{
tokenizationSpecification: tokenizationSpecification
}
);
const paymentDataRequest = Object.assign({}, baseRequest);
paymentDataRequest.allowedPaymentMethods = [cardPaymentMethod];
paymentDataRequest.transactionInfo = {
totalPriceStatus: 'FINAL',
totalPriceLabel: 'Total',
totalPrice: '99.99',
currencyCode: 'USD',
countryCode: 'US'
};
paymentDataRequest.merchantInfo = {
merchantId: process.env.GOOGLE_PAY_MERCHANT_ID,
merchantName: 'Example Store'
};
// Initialize Google Pay
function initializeGooglePay() {
const paymentsClient = new google.payments.api.PaymentsClient({
environment: 'TEST' // Change to 'PRODUCTION' for live
});
return paymentsClient;
}
// Process Google Pay payment
async function processGooglePayPayment(paymentData, customerInfo) {
const apiEndpoint = process.env.Caibo_H2H_ENDPOINT;
const apiKey = process.env.Caibo_API_KEY;
try {
const response = await fetch(apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': apiKey
},
body: JSON.stringify({
// Google Pay specific
name: customerInfo.name,
paymentToken: paymentData.paymentMethodData.tokenizationData.token,
// Customer info
email: customerInfo.email,
phoneNumber: customerInfo.phoneNumber,
address: customerInfo.address.street,
city: customerInfo.address.city,
state: customerInfo.address.state,
postalCode: customerInfo.address.postalCode,
country: customerInfo.address.country,
// Transaction
amount: paymentData.transactionInfo.totalPrice,
unit: paymentData.transactionInfo.currencyCode,
originDomain: window.location.hostname,
referenceId: customerInfo.orderId,
// URLs
notifyUrl: customerInfo.webhookUrl,
successUrl: customerInfo.successUrl,
failureUrl: customerInfo.failureUrl,
// Browser info
browserInfo: collectBrowserInfo()
})
});
const result = await response.json();
if (response.ok) {
return {
success: true,
paymentRequestId: result.paymentRequestId,
status: result.status,
transactionId: result.transactionId
};
} else {
return {
success: false,
error: result.error,
message: result.message
};
}
} catch (error) {
return {
success: false,
error: 'NETWORK_ERROR',
message: error.message
};
}
}
// Complete Google Pay flow
async function handleGooglePayPayment() {
const paymentsClient = initializeGooglePay();
try {
// Request payment data from Google Pay
const paymentData = await paymentsClient.loadPaymentData(paymentDataRequest);
// Process payment with Caibo
const result = await processGooglePayPayment(paymentData, {
name: 'John Smith',
email: 'john@example.com',
phoneNumber: '+1234567890',
address: {
street: '123 Main Street',
city: 'New York',
state: 'NY',
postalCode: '10001',
country: 'US'
},
orderId: 'GPY-54321',
webhookUrl: 'https://api.example.com/webhook',
successUrl: 'https://shop.example.com/success',
failureUrl: 'https://shop.example.com/failure'
});
if (result.success) {
// Payment successful
window.location.href = '/success?id=' + result.paymentRequestId;
} else {
// Handle payment error
displayError(result.message);
}
} catch (error) {
console.error('Google Pay error:', error);
displayError('Google Pay payment failed');
}
}
```
### Android Integration
```kotlin theme={null}
// Google Pay Android integration
class GooglePayActivity : AppCompatActivity() {
private lateinit var paymentsClient: PaymentsClient
private val loadPaymentDataRequestCode = 991
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Initialize Google Pay
val walletOptions = Wallet.WalletOptions.Builder()
.setEnvironment(WalletConstants.ENVIRONMENT_TEST) // Change to PRODUCTION
.build()
paymentsClient = Wallet.getPaymentsClient(this, walletOptions)
// Check if Google Pay is available
checkGooglePayAvailability()
}
private fun checkGooglePayAvailability() {
val request = IsReadyToPayRequest.fromJson(isReadyToPayRequestJson())
paymentsClient.isReadyToPay(request)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
// Google Pay is available
showGooglePayButton()
} else {
// Google Pay is not available
hideGooglePayButton()
}
}
}
private fun requestPayment() {
val paymentDataRequest = PaymentDataRequest.fromJson(paymentDataRequestJson())
AutoResolveHelper.resolveTask(
paymentsClient.loadPaymentData(paymentDataRequest),
this,
loadPaymentDataRequestCode
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
loadPaymentDataRequestCode -> {
when (resultCode) {
Activity.RESULT_OK -> {
data?.let { intent ->
val paymentData = PaymentData.getFromIntent(intent)
handlePaymentSuccess(paymentData)
}
}
Activity.RESULT_CANCELED -> {
// User cancelled
}
AutoResolveHelper.RESULT_ERROR -> {
val status = AutoResolveHelper.getStatusFromIntent(data)
handlePaymentError(status)
}
}
}
}
}
private fun handlePaymentSuccess(paymentData: PaymentData) {
val paymentInfo = paymentData.toJson()
// Process with Caibo API
processCaiboPayment(paymentInfo)
}
private fun processCaiboPayment(paymentInfo: String) {
// Implementation to call Caibo H2H API
// Similar to JavaScript example but using Android HTTP client
}
}
```
## Google Pay Button Integration
### HTML Button
```html theme={null}
```
### CSS Styling
```css theme={null}
#google-pay-button {
background: #000;
border: none;
border-radius: 4px;
padding: 12px 24px;
cursor: pointer;
transition: background-color 0.2s;
}
#google-pay-button:hover {
background: #333;
}
#google-pay-button:disabled {
background: #ccc;
cursor: not-allowed;
}
```
## Payment Token Structure
### Google Pay Token Format
```json theme={null}
{
"protocolVersion": "ECv2",
"signature": "MEQCIH6Q4OwQ0jAceFEkGF0JID...",
"intermediateSigningKey": {
"signedKey": "{\"keyExpiration\":\"1234567890123\",\"keyValue\":\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\"}",
"signatures": ["MEQCIH6Q4OwQ0jAceFEkGF0JID..."]
},
"signedMessage": "{\"tag\":\"jpGz1F1Bcoi/fCNxI9n7Qrsw7i7KHrGtlaN4PK1a/ccDmqJDOLReKbQAjjeLHuQ0...\",\"ephemeralPublicKey\":\"BPhVspn70Zj2Kkgu9t8+ApEuUWsI/zos5whGCQBlgOkuYagOis7qN3RStgeV/QNFqJdN...\",\"encryptedMessage\":\"adMHdWxSfCiTMwXXdMrAgtznpjqecZ...\"}"
}
```
## Error Handling
### Common Google Pay Errors
```javascript theme={null}
function handleGooglePayError(error) {
switch (error.statusCode) {
case 'BUYER_ACCOUNT_ERROR':
displayError('There was an issue with your Google Pay account');
break;
case 'CANCELED':
// User cancelled - no action needed
break;
case 'DEVELOPER_ERROR':
console.error('Google Pay configuration error:', error);
displayError('Payment system configuration error');
break;
case 'INTERNAL_ERROR':
displayError('An internal error occurred. Please try again');
break;
case 'MERCHANT_ACCOUNT_ERROR':
displayError('Merchant account error. Please contact support');
break;
default:
displayError('Payment failed. Please try again');
}
}
```
### Error Response Example
```json theme={null}
{
"success": false,
"error": "GOOGLE_PAY_TOKEN_INVALID",
"message": "Invalid Google Pay payment token",
"code": "GP001",
"details": {
"tokenValidation": "failed",
"reason": "Token signature verification failed"
}
}
```
## Security Features
### Token Security
* **Cryptographic Signatures**: All tokens are cryptographically signed
* **Time-bound Tokens**: Tokens expire after a short period
* **Device Binding**: Tokens are bound to specific devices
* **Network Tokenization**: Card numbers are replaced with secure tokens
### Implementation Security
```javascript theme={null}
// Secure token validation
function validateGooglePayToken(token) {
try {
// Parse token
const tokenData = JSON.parse(token);
// Validate required fields
if (!tokenData.protocolVersion || !tokenData.signature || !tokenData.signedMessage) {
throw new Error('Invalid token structure');
}
// Validate protocol version
if (tokenData.protocolVersion !== 'ECv2') {
throw new Error('Unsupported protocol version');
}
return {
valid: true,
tokenData: tokenData
};
} catch (error) {
return {
valid: false,
error: error.message
};
}
}
```
## Testing
### Test Environment Setup
```javascript theme={null}
// Test configuration
const testConfig = {
environment: 'TEST',
merchantId: '01234567890123456789',
merchantName: 'Test Merchant'
};
// Test payment data
const testPaymentRequest = {
apiVersion: 2,
apiVersionMinor: 0,
allowedPaymentMethods: [{
type: 'CARD',
parameters: {
allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],
allowedCardNetworks: ['VISA', 'MASTERCARD']
},
tokenizationSpecification: {
type: 'PAYMENT_GATEWAY',
parameters: {
gateway: 'caibo',
gatewayMerchantId: 'test_merchant_123'
}
}
}],
transactionInfo: {
totalPriceStatus: 'FINAL',
totalPrice: '1.00',
currencyCode: 'USD'
},
merchantInfo: testConfig
};
```
### Test Cards
Google Pay test environment provides these test cards:
* **Visa**: 4111111111111111
* **Mastercard**: 5555555555554444
* **Amex**: 378282246310005
## Production Checklist
### Before Going Live
1. **Change Environment**: Switch from TEST to PRODUCTION
2. **Update Merchant IDs**: Use production merchant IDs
3. **SSL Certificate**: Ensure valid SSL certificate
4. **Domain Verification**: Verify domain with Google
5. **Test Thoroughly**: Test all payment flows
6. **Monitor Transactions**: Set up transaction monitoring
### Production Configuration
```javascript theme={null}
// Production configuration
const productionConfig = {
environment: 'PRODUCTION',
merchantId: 'your_production_merchant_id',
merchantName: 'Your Store Name'
};
```
## Best Practices
### User Experience
1. **Button Placement**: Place Google Pay button prominently
2. **Loading States**: Show loading indicators during processing
3. **Error Messages**: Provide clear, actionable error messages
4. **Fallback Options**: Offer alternative payment methods
### Technical Implementation
1. **Token Validation**: Always validate payment tokens
2. **Error Handling**: Implement comprehensive error handling
3. **Logging**: Log all payment attempts for debugging
4. **Security**: Follow PCI DSS compliance guidelines
### Performance
1. **Lazy Loading**: Load Google Pay API only when needed
2. **Caching**: Cache availability checks
3. **Timeout Handling**: Set appropriate timeouts
4. **Retry Logic**: Implement retry logic for failed requests
## Next Steps
Learn about Apple Pay payment integration
Track Google Pay payment status
Handle Google Pay payment notifications
# UPI Payments
Source: https://docs.caibo.digital/h2h/payments/upi
Process UPI (Unified Payments Interface) payments through Host-to-Host API for instant Indian market transactions
# UPI Payments
Process UPI (Unified Payments Interface) payments through the Host-to-Host API for instant, real-time transactions in the Indian market with 24/7 availability.
## Overview
UPI payment processing provides:
* **Instant Transfers**: Real-time payment processing
* **24/7 Availability**: Round-the-clock payment processing
* **Mobile Optimized**: Designed for mobile-first experience
* **UPI ID Validation**: Automatic UPI ID format validation
* **Low Fees**: Cost-effective payment processing
* **Bank Integration**: Direct integration with Indian banks
## Required Parameters
### UPI-Specific Fields
| Parameter | Description | Required | Example |
| --------- | ------------------ | -------- | -------------- |
| `upiId` | UPI identifier | YES | "user\@paytm" |
| `name` | Customer full name | YES | "Rajesh Kumar" |
### Customer Information
| Parameter | Description | Required | Example |
| ------------- | --------------------------- | -------- | ------------------------------------------------- |
| `email` | Customer email address | YES | "[rajesh@example.com](mailto:rajesh@example.com)" |
| `phoneNumber` | Customer phone number | YES | "+919876543210" |
| `address` | Customer address | YES | "123 MG Road" |
| `city` | Customer city | YES | "Mumbai" |
| `state` | State or province | YES | "Maharashtra" |
| `postalCode` | PIN code | YES | "400001" |
| `country` | Country code (IN for India) | YES | "IN" |
### Transaction Details
| Parameter | Description | Required | Example |
| -------------- | ------------------- | -------- | ------------------ |
| `amount` | Payment amount | YES | 1500.00 |
| `unit` | Currency code (INR) | YES | "INR" |
| `originDomain` | Merchant domain | YES | "shop.example.com" |
| `referenceId` | Merchant reference | NO | "UPI-12345" |
## Complete Request Example
```json theme={null}
{
"name": "Rajesh Kumar",
"upiId": "rajesh@paytm",
"email": "rajesh@example.com",
"phoneNumber": "+919876543210",
"address": "123 MG Road",
"city": "Mumbai",
"state": "Maharashtra",
"postalCode": "400001",
"country": "IN",
"amount": 1500.00,
"unit": "INR",
"originDomain": "shop.example.com",
"referenceId": "UPI-12345",
"notifyUrl": "https://api.example.com/webhook",
"successUrl": "https://shop.example.com/success",
"failureUrl": "https://shop.example.com/failure",
"browserInfo": {
"browserAcceptHeader": "application/json, text/plain, */*",
"browserColorDepth": "24",
"browserIP": "103.21.58.66",
"browserJavaEnabled": false,
"browserJavascriptEnabled": true,
"browserLanguage": "en-IN",
"browserScreenHeight": "1080",
"browserScreenWidth": "1920",
"browserTZ": "330",
"browserUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
}
```
## Implementation Example
### JavaScript/Node.js
```javascript theme={null}
async function processUPIPayment(paymentData) {
const apiEndpoint = process.env.Caibo_H2H_ENDPOINT;
const apiKey = process.env.Caibo_API_KEY;
try {
const response = await fetch(apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': apiKey
},
body: JSON.stringify({
// UPI specific
name: paymentData.customerName,
upiId: paymentData.upiId,
// Customer info
email: paymentData.customerEmail,
phoneNumber: paymentData.customerPhone,
address: paymentData.customerAddress.street,
city: paymentData.customerAddress.city,
state: paymentData.customerAddress.state,
postalCode: paymentData.customerAddress.postalCode,
country: paymentData.customerAddress.country,
// Transaction
amount: paymentData.amount,
unit: paymentData.currency,
originDomain: paymentData.merchantDomain,
referenceId: paymentData.orderId,
// URLs
notifyUrl: paymentData.webhookUrl,
successUrl: paymentData.successUrl,
failureUrl: paymentData.failureUrl,
// Browser info for enhanced security
browserInfo: paymentData.browserInfo
})
});
const result = await response.json();
if (response.ok) {
return {
success: true,
paymentRequestId: result.paymentRequestId,
redirectUrl: result.redirectUrl,
status: result.status
};
} else {
return {
success: false,
error: result.error,
message: result.message
};
}
} catch (error) {
return {
success: false,
error: 'NETWORK_ERROR',
message: error.message
};
}
}
```
### Python
```python theme={null}
import requests
import json
import os
def process_upi_payment(payment_data):
api_endpoint = os.getenv('Caibo_H2H_ENDPOINT')
api_key = os.getenv('Caibo_API_KEY')
headers = {
'Content-Type': 'application/json',
'X-API-Key': api_key
}
request_data = {
# UPI specific
'name': payment_data['customer_name'],
'upiId': payment_data['upi_id'],
# Customer info
'email': payment_data['customer_email'],
'phoneNumber': payment_data['customer_phone'],
'address': payment_data['customer_address']['street'],
'city': payment_data['customer_address']['city'],
'state': payment_data['customer_address']['state'],
'postalCode': payment_data['customer_address']['postal_code'],
'country': payment_data['customer_address']['country'],
# Transaction
'amount': payment_data['amount'],
'unit': payment_data['currency'],
'originDomain': payment_data['merchant_domain'],
'referenceId': payment_data['order_id'],
# URLs
'notifyUrl': payment_data['webhook_url'],
'successUrl': payment_data['success_url'],
'failureUrl': payment_data['failure_url'],
# Browser info
'browserInfo': payment_data['browser_info']
}
try:
response = requests.post(api_endpoint, headers=headers, json=request_data)
result = response.json()
if response.status_code == 200:
return {
'success': True,
'payment_request_id': result['paymentRequestId'],
'redirect_url': result.get('redirectUrl'),
'status': result['status']
}
else:
return {
'success': False,
'error': result.get('error', 'UNKNOWN_ERROR'),
'message': result.get('message', 'UPI payment processing failed')
}
except requests.RequestException as e:
return {
'success': False,
'error': 'NETWORK_ERROR',
'message': str(e)
}
```
## UPI ID Validation
### Valid UPI ID Formats
* **Format**: `username@bankcode`
* **Examples**:
* `user@paytm`
* `9876543210@ybl`
* `john.doe@oksbi`
* `mobile@paytm`
### UPI ID Validation Function
```javascript theme={null}
function validateUPIId(upiId) {
// UPI ID format: username@bankcode
const upiRegex = /^[a-zA-Z0-9.\-_]{2,256}@[a-zA-Z][a-zA-Z0-9.\-_]{2,64}$/;
if (!upiRegex.test(upiId)) {
return {
valid: false,
error: 'Invalid UPI ID format'
};
}
const [username, bankCode] = upiId.split('@');
// Check username length
if (username.length < 2 || username.length > 256) {
return {
valid: false,
error: 'Username must be between 2-256 characters'
};
}
// Check bank code
if (bankCode.length < 3 || bankCode.length > 64) {
return {
valid: false,
error: 'Bank code must be between 3-64 characters'
};
}
return {
valid: true,
username: username,
bankCode: bankCode
};
}
```
## Payment Flow
### 1. UPI Payment Initiation
```javascript theme={null}
// Validate UPI ID first
const upiValidation = validateUPIId(paymentData.upiId);
if (!upiValidation.valid) {
throw new Error(upiValidation.error);
}
// Process UPI payment
const paymentResult = await processUPIPayment({
customerName: 'Rajesh Kumar',
upiId: 'rajesh@paytm',
customerEmail: 'rajesh@example.com',
customerPhone: '+919876543210',
customerAddress: {
street: '123 MG Road',
city: 'Mumbai',
state: 'Maharashtra',
postalCode: '400001',
country: 'IN'
},
amount: 1500.00,
currency: 'INR',
merchantDomain: 'shop.example.com',
orderId: 'UPI-12345',
webhookUrl: 'https://api.example.com/webhook',
successUrl: 'https://shop.example.com/success',
failureUrl: 'https://shop.example.com/failure',
browserInfo: collectBrowserInfo()
});
```
### 2. Handle UPI Response
```javascript theme={null}
if (paymentResult.success) {
if (paymentResult.redirectUrl) {
// Redirect to UPI app or payment page
window.location.href = paymentResult.redirectUrl;
} else {
// Payment initiated successfully
showPaymentPending(paymentResult.paymentRequestId);
}
} else {
// Handle UPI payment error
displayUPIError(paymentResult.message);
}
```
## Popular UPI Providers
### Major UPI Apps
| Provider | Bank Code | Example UPI ID |
| -------------- | ------------------------ | -------------- |
| **Paytm** | `@paytm` | `user@paytm` |
| **Google Pay** | `@okaxis`, `@okhdfcbank` | `user@okaxis` |
| **PhonePe** | `@ybl`, `@ibl` | `user@ybl` |
| **Amazon Pay** | `@apl` | `user@apl` |
| **BHIM** | `@upi` | `user@upi` |
### Bank UPI Handles
| Bank | UPI Handle | Example |
| ------------- | ----------- | --------------- |
| **SBI** | `@sbi` | `user@sbi` |
| **HDFC** | `@hdfcbank` | `user@hdfcbank` |
| **ICICI** | `@icici` | `user@icici` |
| **Axis Bank** | `@axisbank` | `user@axisbank` |
| **Kotak** | `@kotak` | `user@kotak` |
## Error Handling
### Common UPI Error Codes
* **INVALID\_UPI\_ID**: UPI ID format is invalid
* **UPI\_ID\_NOT\_FOUND**: UPI ID does not exist
* **INSUFFICIENT\_FUNDS**: Insufficient balance in UPI account
* **UPI\_DECLINED**: Transaction declined by UPI provider
* **UPI\_TIMEOUT**: UPI transaction timeout
* **DAILY\_LIMIT\_EXCEEDED**: Daily transaction limit exceeded
### Error Response Example
```json theme={null}
{
"success": false,
"error": "UPI_DECLINED",
"message": "Transaction declined by UPI provider",
"code": "U001",
"details": {
"declineReason": "Invalid UPI PIN",
"upiResponse": "U30"
}
}
```
## Transaction Limits
### UPI Transaction Limits
* **Per Transaction**: ₹1,00,000 (1 Lakh INR)
* **Daily Limit**: ₹1,00,000 (1 Lakh INR)
* **Monthly Limit**: ₹20,00,000 (20 Lakh INR)
* **Minimum Amount**: ₹1 (1 INR)
Limits may vary by bank and UPI provider. Always check with the specific provider for current limits.
## Security Features
### UPI Security
* **Two-Factor Authentication**: UPI PIN + device authentication
* **Encrypted Communication**: End-to-end encryption
* **Device Binding**: UPI apps are bound to specific devices
* **Transaction Limits**: Built-in transaction limits for security
### Implementation Security
```javascript theme={null}
// Secure UPI payment processing
function secureUPIPayment(paymentData) {
// Validate UPI ID format
if (!validateUPIId(paymentData.upiId).valid) {
throw new Error('Invalid UPI ID');
}
// Sanitize input data
const sanitizedData = {
...paymentData,
upiId: paymentData.upiId.toLowerCase().trim(),
amount: parseFloat(paymentData.amount).toFixed(2)
};
// Check amount limits
if (sanitizedData.amount > 100000) {
throw new Error('Amount exceeds UPI transaction limit');
}
return processUPIPayment(sanitizedData);
}
```
## Testing
### Test UPI IDs
For testing purposes, use these test UPI IDs:
* **Success**: `success@paytm`
* **Failure**: `failure@paytm`
* **Timeout**: `timeout@paytm`
* **Insufficient Funds**: `insufficient@paytm`
### Test Scenarios
```javascript theme={null}
// Test successful UPI payment
const testPayment = {
customerName: 'Test User',
upiId: 'success@paytm',
customerEmail: 'test@example.com',
customerPhone: '+919876543210',
amount: 100.00,
currency: 'INR'
};
```
## Best Practices
### Implementation
1. **UPI ID Validation**: Always validate UPI ID format
2. **Amount Validation**: Check transaction limits
3. **Mobile Optimization**: Optimize for mobile devices
4. **Real-time Status**: Provide real-time payment status
### User Experience
1. **UPI App Integration**: Deep link to UPI apps when possible
2. **QR Code Option**: Provide QR code for easy scanning
3. **Clear Instructions**: Provide clear payment instructions
4. **Status Updates**: Keep users informed of payment progress
### Compliance
1. **RBI Guidelines**: Follow Reserve Bank of India guidelines
2. **Data Protection**: Protect customer financial data
3. **Transaction Records**: Maintain proper transaction records
4. **Audit Trail**: Keep audit trail of all UPI transactions
## Next Steps
Learn about Google Pay payment integration
Track UPI payment status
Handle UPI payment notifications
# 10-Minute Quickstart
Source: https://docs.caibo.digital/h2h/quickstart-h2h
Complete your first H2H payment with webhook verification in under 10 minutes
# 10-Minute H2H Quickstart
Get your first Host-to-Host payment running in under 10 minutes with this step-by-step guide.
## Prerequisites
* Caibo merchant account with API keys ([Get API Keys](/ipg/authentication))
* Development environment (Node.js, Python, or PHP)
* Webhook endpoint capability
**Need API Keys?** If you don't have API keys yet, follow our [Authentication Guide](/ipg/authentication) to learn how to log into the Control Panel and generate your API keys.
## Step 1: Environment Setup (2 minutes)
Set your environment variables:
```bash theme={null}
export Caibo_H2H_ENDPOINT="https://apay.caibo.digital"
export Caibo_API_KEY="your_sandbox_api_key"
export WEBHOOK_URL="https://your-server.com/webhook"
```
Your API key should start with `caibo_test_sk_` for sandbox or `caibo_live_sk_` for production. Learn more about [API key formats](/ipg/authentication#key-types).
## Step 2: Create Payment Request (3 minutes)
```javascript Node.js theme={null}
const axios = require('axios');
async function createPayment() {
const response = await axios.post(
`${process.env.Caibo_H2H_ENDPOINT}/payments/h2h/1`,
{
name: "John Doe",
email: "john@example.com",
phoneNumber: "+1234567890",
address: "123 Main St",
city: "New York",
state: "NY",
postalCode: "10001",
country: "US",
amount: 10.00,
unit: "USD",
originDomain: "localhost",
notifyUrl: process.env.WEBHOOK_URL,
successUrl: "http://localhost:3000/success",
failureUrl: "http://localhost:3000/failure"
},
{
headers: {
'X-API-Key': process.env.Caibo_API_KEY,
'Content-Type': 'application/json'
}
}
);
console.log('Payment created:', response.data);
return response.data;
}
createPayment();
```
```python Python theme={null}
import requests
import os
def create_payment():
response = requests.post(
f"{os.getenv('Caibo_H2H_ENDPOINT')}/payments/h2h/1",
json={
"name": "John Doe",
"email": "john@example.com",
"phoneNumber": "+1234567890",
"address": "123 Main St",
"city": "New York",
"state": "NY",
"postalCode": "10001",
"country": "US",
"amount": 10.00,
"unit": "USD",
"originDomain": "localhost",
"notifyUrl": os.getenv('WEBHOOK_URL'),
"successUrl": "http://localhost:3000/success",
"failureUrl": "http://localhost:3000/failure"
},
headers={
'X-API-Key': os.getenv('Caibo_API_KEY'),
'Content-Type': 'application/json'
}
)
print('Payment created:', response.json())
return response.json()
create_payment()
```
```php PHP theme={null}
'John Doe',
'email' => 'john@example.com',
'phoneNumber' => '+1234567890',
'address' => '123 Main St',
'city' => 'New York',
'state' => 'NY',
'postalCode' => '10001',
'country' => 'US',
'amount' => 10.00,
'unit' => 'USD',
'originDomain' => 'localhost',
'notifyUrl' => $webhookUrl,
'successUrl' => 'http://localhost:3000/success',
'failureUrl' => 'http://localhost:3000/failure'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$endpoint/payments/h2h/1");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-API-Key: ' . $apiKey,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo 'Payment created: ' . $response;
?>
```
## Step 3: Handle Webhook (3 minutes)
```javascript Node.js theme={null}
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.json());
app.post('/webhook', (req, res) => {
const signature = req.headers['x-caibo-signature'];
const payload = JSON.stringify(req.body);
// Verify webhook signature
const expectedSignature = crypto
.createHmac('sha512', process.env.WEBHOOK_SECRET)
.update(payload)
.digest('hex');
if (signature !== expectedSignature) {
return res.status(401).send('Invalid signature');
}
const { paymentRequestId, status, transactionId } = req.body;
console.log(`Payment ${paymentRequestId} status: ${status}`);
// Process payment status
switch (status) {
case 'completed':
console.log('✅ Payment successful!');
break;
case 'failed':
console.log('❌ Payment failed');
break;
case 'pending':
console.log('⏳ Payment pending');
break;
}
res.status(200).send('OK');
});
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});
```
```python Python theme={null}
from flask import Flask, request, jsonify
import hmac
import hashlib
import json
import os
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
signature = request.headers.get('X-Caibo-Signature')
payload = request.get_data()
# Verify webhook signature
expected_signature = hmac.new(
os.getenv('WEBHOOK_SECRET').encode(),
payload,
hashlib.sha512
).hexdigest()
if signature != expected_signature:
return 'Invalid signature', 401
data = request.json
payment_id = data['paymentRequestId']
status = data['status']
print(f'Payment {payment_id} status: {status}')
# Process payment status
if status == 'completed':
print('✅ Payment successful!')
elif status == 'failed':
print('❌ Payment failed')
elif status == 'pending':
print('⏳ Payment pending')
return 'OK', 200
if __name__ == '__main__':
app.run(port=3000)
```
```php PHP theme={null}
```
## Step 4: Check Payment Status (2 minutes)
```javascript Node.js theme={null}
async function checkPaymentStatus(paymentRequestId) {
const response = await axios.get(
`${process.env.Caibo_H2H_ENDPOINT}/payment-requests/status/${paymentRequestId}`,
{
headers: {
'X-API-Key': process.env.Caibo_API_KEY
}
}
);
console.log('Payment status:', response.data);
return response.data;
}
// Check status every 5 seconds
setInterval(() => {
checkPaymentStatus('your_payment_request_id');
}, 5000);
```
```python Python theme={null}
import time
def check_payment_status(payment_request_id):
response = requests.get(
f"{os.getenv('Caibo_H2H_ENDPOINT')}/payment-requests/status/{payment_request_id}",
headers={'X-API-Key': os.getenv('Caibo_API_KEY')}
)
print('Payment status:', response.json())
return response.json()
# Check status every 5 seconds
while True:
check_payment_status('your_payment_request_id')
time.sleep(5)
```
```php PHP theme={null}
```
## Testing Your Integration
### Test with Sandbox Data
Use these test values in sandbox:
```json theme={null}
{
"name": "Test User",
"email": "test@example.com",
"phoneNumber": "+1234567890",
"amount": 10.00,
"unit": "USD"
}
```
### Expected Flow
1. **Payment Created** → Status: `pending`
2. **User Completes Payment** → Webhook received
3. **Payment Confirmed** → Status: `completed`
## Troubleshooting
### Common Issues
| Issue | Solution |
| -------------------- | ----------------------------------- |
| 401 Unauthorized | Check API key in `X-API-Key` header |
| 400 Bad Request | Validate required fields |
| Webhook not received | Check webhook URL and firewall |
| Invalid signature | Verify webhook secret |
### Debug Checklist
* ✅ API key is correct
* ✅ Webhook URL is accessible
* ✅ Webhook signature verification
* ✅ Required fields provided
* ✅ Amount format is correct
## Next Steps
Learn about API key management and security
Implement credit card processing
Add UPI payment support
Comprehensive testing scenarios
Handle errors and edge cases
## Success! 🎉
You've successfully:
* Created your first H2H payment request
* Set up webhook handling with signature verification
* Implemented payment status checking
* Tested the complete payment flow
Your H2H integration is now ready for production!
# H2H Request Structure
Source: https://docs.caibo.digital/h2h/request-structure
Complete guide to Host-to-Host API request parameters, objects, and authentication
# H2H Request Structure
Host-to-Host API requests use a standardized JSON structure with specific parameters for different payment methods. This guide covers all request components, authentication, and parameter requirements.
## API Specification
### Request Details
* **API Endpoint**: Custom URL obtained from dashboard (varies by provider)
* **HTTP Method**: `POST`
* **Content Type**: `application/json`
* **Authentication**: `X-API-Key` header with your API key
### Authentication Header
```http theme={null}
X-API-Key: your-api-key-from-dashboard
```
## Core Request Parameters
| Name | Description | Required |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `name` | Debit/credit card holder name | YES |
| `number` | Debit/credit card number | YES (for credit card payment) NO (for alternative payment) NO (for UPI payment) NO (for Google Pay) |
| `expiration` | Debit/credit card expiration date in format MM/YY | YES (for credit card payment) NO (for alternative payment) NO (for UPI payment) NO (for Google Pay) |
| `cvv` | Debit/credit card CVV code | YES (for credit card payment) NO (for alternative payment) NO (for UPI payment) NO (for Google Pay) |
| `upiId` | UPI identifier | YES (for UPI payment) NO (for credit card payment) NO (for alternative payment) NO (for Google Pay) |
| `token` | Google Pay token | YES (for Google Pay and Apple Pay) NO (for UPI payment) NO (for credit card payment) NO (for alternative payment) |
| `address` | Payer address | YES |
| `email` | Payer email address | YES |
| `phoneNumber` | Payer phone number | YES |
| `city` | Payer city name | YES |
| `state` | Payer state name or code. For example, Florida or FL | YES |
| `postalCode` | Payer postal code | YES |
| `country` | Payer country 2-letter code by ISO-3166-1 alpha 2. For example, US | YES |
| `amount` | Payment amount. For example, 10.50 | YES |
| `unit` | Payment currency. For example, USD, EUR, BTC, USDT | YES |
| `originDomain` | Origin domain name where from is performing payment request | YES |
| `referenceId` | Merchant custom reference ID. Free text identifier to recognize a payment by merchant on receiving a payment notification | NO |
| `notifyUrl` | Webhook URL to notify about a payment status. Overrides merchant level notify URL defined in a merchant profile | NO |
| `successUrl` | Redirect URL on success payment for payment request. Overrides merchant level notify URL defined in a merchant profile | NO |
| `failureUrl` | Redirect URL on fail payment for payment request. Overrides merchant level notify URL defined in a merchant profile | NO |
| `captureDelayHours` | Payment capture delay in hours for credit card payments. Allows the values range 0 – 7. The value 0 means to capture a payment immediately. | NO |
| `browserInfo` | User browser info for 3DS verification – browser info object | NO |
| `wallet` | User Google or Apple wallet details – wallet object | YES (for wallet payment) NO (for credit card payment or alternative payment) |
## Browser Info Object
The `browserInfo` object is used for 3D Secure verification and contains browser-specific information:
| Name | Description | Required |
| -------------------------- | ----------------------------------- | -------- |
| `browserAcceptHeader` | Request header parameter Accept | NO |
| `browserLanguage` | Browser language | NO |
| `browserScreenHeight` | User screen height | NO |
| `browserScreenWidth` | User screen width | NO |
| `browserTZ` | User time zone offset in minutes | NO |
| `browserUserAgent` | Request header parameter User-Agent | NO |
| `browserColorDepth` | Browser color depth | NO |
| `browserIP` | User IP address | NO |
| `browserJavaEnabled` | Browser Java enabled state | NO |
| `browserJavascriptEnabled` | Browser JavaScript enabled state | NO |
### Browser Info Example
```json theme={null}
{
"browserAcceptHeader": "application/json, text/plain, */*",
"browserColorDepth": "24",
"browserIP": "127.0.0.1",
"browserJavaEnabled": false,
"browserJavascriptEnabled": true,
"browserLanguage": "en-US",
"browserScreenHeight": "1080",
"browserScreenWidth": "1920",
"browserTZ": "300",
"browserUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
}
```
## Wallet Object
The `wallet` object contains digital wallet information for Google Pay and Apple Pay payments. All values should be obtained from Google Pay or Apple Pay wallets:
| Name | Description | Required |
| --------------------- | -------------------------------------------------------- | -------- |
| `authenticationValue` | Wallet unencrypted authentication data | YES |
| `walletType` | Wallet type G – Google wallet A – Apple wallet | YES |
| `xid` | Wallet XID | NO |
| `eci` | Wallet ECI | YES |
### Wallet Object Example
```json theme={null}
{
"authenticationValue": "ABCDE12345FGHJK67890\u0012e",
"walletType": "A",
"xid": "11111",
"eci": "05"
}
```
## Complete Request Examples
### Credit Card Payment
```json theme={null}
{
"name": "Test User",
"number": "4111111111111111",
"expiration": "10/25",
"cvv": "123",
"email": "test.user@email.com",
"phoneNumber": "1234567890",
"address": "10 Unknown Street",
"city": "Far Town",
"state": "NA",
"postalCode": "123456",
"country": "US",
"amount": 10.50,
"unit": "USD",
"originDomain": "example.com",
"referenceId": "123-GA-456",
"notifyUrl": "https://notify.me",
"successUrl": "https://success.payment.com",
"failureUrl": "http://fail.payment.com",
"captureDelayHours": 0,
"browserInfo": {
"browserAcceptHeader": "application/json, text/plain, */*",
"browserColorDepth": "24",
"browserIP": "127.0.0.1",
"browserJavaEnabled": false,
"browserJavascriptEnabled": true,
"browserLanguage": "en-US",
"browserScreenHeight": "1080",
"browserScreenWidth": "1920",
"browserTZ": "300",
"browserUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
}
}
```
### Alternative Payment
```json theme={null}
{
"name": "Test User",
"email": "test.user@email.com",
"phoneNumber": "1234567890",
"address": "10 Unknown Street",
"city": "Far Town",
"state": "NA",
"postalCode": "123456",
"country": "US",
"amount": 10.50,
"unit": "USD",
"originDomain": "example.com",
"referenceId": "123-GA-456",
"notifyUrl": "https://notify.me",
"successUrl": "https://success.payment.com",
"failureUrl": "http://fail.payment.com"
}
```
### UPI Payment
```json theme={null}
{
"name": "Test User",
"upiId": "upi-id",
"email": "test.user@email.com",
"phoneNumber": "1234567890",
"address": "10 Unknown Street",
"city": "Far Town",
"state": "NA",
"postalCode": "123456",
"country": "US",
"amount": 10.50,
"unit": "USD",
"originDomain": "example.com",
"referenceId": "123-GA-456",
"notifyUrl": "https://notify.me",
"successUrl": "https://success.payment.com",
"failureUrl": "http://fail.payment.com",
"browserInfo": {
"browserAcceptHeader": "application/json, text/plain, */*",
"browserColorDepth": "24",
"browserIP": "127.0.0.1",
"browserJavaEnabled": false,
"browserJavascriptEnabled": true,
"browserLanguage": "en-US",
"browserScreenHeight": "1080",
"browserScreenWidth": "1920",
"browserTZ": "300",
"browserUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
}
}
```
### Google Pay Payment
```json theme={null}
{
"name": "Test User",
"token": "Google Pay token",
"email": "test.user@email.com",
"phoneNumber": "1234567890",
"address": "10 Unknown Street",
"city": "Far Town",
"state": "NA",
"postalCode": "123456",
"country": "US",
"amount": 10.50,
"unit": "USD",
"originDomain": "example.com",
"referenceId": "123-GA-456",
"notifyUrl": "https://notify.me",
"successUrl": "https://success.payment.com",
"failureUrl": "http://fail.payment.com",
"browserInfo": {
"browserAcceptHeader": "application/json, text/plain, */*",
"browserColorDepth": "24",
"browserIP": "127.0.0.1",
"browserJavaEnabled": false,
"browserJavascriptEnabled": true,
"browserLanguage": "en-US",
"browserScreenHeight": "1080",
"browserScreenWidth": "1920",
"browserTZ": "300",
"browserUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
}
}
```
### Apple Pay Payment
```json theme={null}
{
"name": "Test User",
"token": "Apple Pay token",
"email": "test.user@email.com",
"phoneNumber": "1234567890",
"address": "10 Unknown Street",
"city": "Far Town",
"state": "NA",
"postalCode": "123456",
"country": "US",
"amount": 10.50,
"unit": "USD",
"originDomain": "example.com",
"referenceId": "123-GA-456",
"notifyUrl": "https://notify.me",
"successUrl": "https://success.payment.com",
"failureUrl": "http://fail.payment.com",
"browserInfo": {
"browserAcceptHeader": "application/json, text/plain, */*",
"browserColorDepth": "24",
"browserIP": "127.0.0.1",
"browserJavaEnabled": false,
"browserJavascriptEnabled": true,
"browserLanguage": "en-US",
"browserScreenHeight": "1080",
"browserScreenWidth": "1920",
"browserTZ": "300",
"browserUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
}
}
```
### Wallet Payment (Apple Pay Example)
```json theme={null}
{
"name": "Test User",
"number": "4111111111111111",
"expiration": "10/25",
"email": "test.user@email.com",
"phoneNumber": "1234567890",
"address": "10 Unknown Street",
"city": "Far Town",
"state": "NA",
"postalCode": "123456",
"country": "US",
"amount": 10.50,
"unit": "USD",
"originDomain": "example.com",
"referenceId": "123-GA-456",
"notifyUrl": "https://notify.me",
"successUrl": "https://success.payment.com",
"failureUrl": "http://fail.payment.com",
"browserInfo": {
"browserAcceptHeader": "application/json, text/plain, */*",
"browserColorDepth": "24",
"browserIP": "127.0.0.1",
"browserJavaEnabled": false,
"browserJavascriptEnabled": true,
"browserLanguage": "en-US",
"browserScreenHeight": "1080",
"browserScreenWidth": "1920",
"browserTZ": "300",
"browserUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
},
"wallet": {
"authenticationValue": "ABCDE12345FGHJK67890\u0012e",
"walletType": "A",
"xid": "11111",
"eci": "05"
}
}
```
## Best Practices
### Request Construction
1. **Parameter Validation**: Validate all required parameters before sending requests
2. **Data Sanitization**: Sanitize input data to prevent injection attacks
3. **Currency Formatting**: Use proper decimal formatting for amounts
4. **Country Codes**: Use ISO-3166-1 alpha-2 country codes
### Security
1. **HTTPS Only**: Always use HTTPS for API requests
2. **API Key Protection**: Never expose API keys in client-side code
3. **Data Encryption**: Encrypt sensitive data before transmission
4. **Request Signing**: Consider implementing request signing for additional security
### Error Prevention
1. **Required Fields**: Ensure all required fields are included based on payment method
2. **Format Validation**: Validate data formats (dates, phone numbers, emails)
3. **Length Limits**: Respect field length limitations
4. **Character Encoding**: Use UTF-8 encoding for all text fields
## Next Steps
Learn about H2H API response format and handling
Explore available payment methods and implementations
Set up webhook notifications for payment status updates
# H2H Response Structure
Source: https://docs.caibo.digital/h2h/response-structure
Understanding Host-to-Host API response format, status codes, and error handling
# H2H Response Structure
Host-to-Host API responses provide essential information for tracking and completing payment processes. This guide covers response formats, status handling, and implementation patterns.
## Response Overview
The API returns a payment response containing essential information for tracking and completing the payment process.
### Response Structure
The payment response includes:
* **Payment Request Identifier**: A unique identifier for the created payment request that can be used to pull payment request status
* **Redirect URL**: A URL to complete the payment if necessary (for payment methods requiring customer interaction)
### Response Fields
| Field | Description | Type |
| ------------------ | ------------------------------------- | -------------- |
| `paymentRequestId` | Created payment request identifier | string/integer |
| `redirectUrl` | URL to complete payment (if required) | string |
| `status` | Initial payment status | string |
## Response Usage
### 1. Status Tracking
Use the payment request identifier to check payment status via status endpoints:
```javascript theme={null}
// Track payment status
async function checkPaymentStatus(paymentRequestId) {
const response = await fetch(`/api/payment-status/${paymentRequestId}`, {
headers: {
'X-API-Key': apiKey
}
});
const status = await response.json();
return status;
}
```
### 2. Payment Completion
Redirect customers to the provided URL for payment methods requiring user interaction:
```javascript theme={null}
// Handle redirect if required
if (paymentResponse.redirectUrl) {
// Redirect customer to complete payment
window.location.href = paymentResponse.redirectUrl;
} else {
// Payment completed directly
handlePaymentComplete(paymentResponse);
}
```
### 3. Transaction Management
Store the identifier for future reference and reconciliation:
```javascript theme={null}
// Store payment reference
const paymentRecord = {
paymentRequestId: paymentResponse.paymentRequestId,
merchantReference: orderData.referenceId,
amount: orderData.amount,
currency: orderData.unit,
status: paymentResponse.status,
createdAt: new Date().toISOString()
};
await savePaymentRecord(paymentRecord);
```
## Implementation Examples
### Basic H2H Payment Processing
```javascript theme={null}
// H2H Payment Processing
async function processH2HPayment(paymentData) {
const apiEndpoint = "https://api.caibo.com/h2h/payments"; // From dashboard
const apiKey = "your-api-key-from-dashboard";
try {
const response = await fetch(apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': apiKey
},
body: JSON.stringify({
amount: paymentData.amount,
currency: paymentData.currency,
paymentMethod: {
type: "credit_card",
cardNumber: paymentData.cardNumber,
expiryMonth: paymentData.expiryMonth,
expiryYear: paymentData.expiryYear,
cvv: paymentData.cvv,
cardholderName: paymentData.cardholderName
},
customer: {
email: paymentData.customerEmail,
phone: paymentData.customerPhone
},
billingAddress: paymentData.billingAddress,
merchantReference: paymentData.orderId,
notificationUrl: "https://yoursite.com/webhooks/payment-notification"
})
});
const result = await response.json();
if (response.ok) {
console.log('Payment processed successfully:', result);
return {
success: true,
transactionId: result.transactionId,
status: result.status,
data: result
};
} else {
console.error('Payment failed:', result);
return {
success: false,
error: result.error,
message: result.message
};
}
} catch (error) {
console.error('Network error:', error);
return {
success: false,
error: 'NETWORK_ERROR',
message: error.message
};
}
}
```
### Multiple Provider Handling
```javascript theme={null}
// Handle multiple API endpoints for different providers
const providerEndpoints = {
'provider1': 'https://api1.caibo.com/h2h/payments',
'provider2': 'https://api2.caibo.com/h2h/payments',
'provider3': 'https://api3.caibo.com/h2h/payments'
};
async function processPaymentWithFailover(paymentData, preferredProvider = 'provider1') {
const providers = [preferredProvider, ...Object.keys(providerEndpoints).filter(p => p !== preferredProvider)];
for (const provider of providers) {
try {
const endpoint = providerEndpoints[provider];
const result = await processH2HPayment({
...paymentData,
endpoint: endpoint
});
if (result.success) {
console.log(`Payment successful with ${provider}`);
return result;
}
} catch (error) {
console.warn(`Provider ${provider} failed, trying next...`);
continue;
}
}
throw new Error('All payment providers failed');
}
```
## Error Handling
### Common Error Codes
* **INVALID\_API\_KEY**: API key is missing or invalid
* **INSUFFICIENT\_FUNDS**: Customer's account has insufficient funds
* **CARD\_DECLINED**: Payment method was declined by issuer
* **INVALID\_CARD**: Card number or details are invalid
* **EXPIRED\_CARD**: Payment method has expired
* **NETWORK\_ERROR**: Communication error with payment provider
### Retry Logic
```javascript theme={null}
async function processPaymentWithRetry(paymentData, maxRetries = 3) {
let attempt = 0;
let lastError;
while (attempt < maxRetries) {
try {
const result = await processH2HPayment(paymentData);
if (result.success) {
return result;
}
// Check if error is retryable
if (isRetryableError(result.error)) {
attempt++;
await delay(Math.pow(2, attempt) * 1000); // Exponential backoff
continue;
} else {
// Non-retryable error, fail immediately
return result;
}
} catch (error) {
lastError = error;
attempt++;
if (attempt < maxRetries) {
await delay(Math.pow(2, attempt) * 1000);
}
}
}
throw new Error(`Payment failed after ${maxRetries} attempts: ${lastError.message}`);
}
function isRetryableError(errorCode) {
const retryableErrors = [
'NETWORK_ERROR',
'TIMEOUT',
'TEMPORARY_UNAVAILABLE',
'RATE_LIMITED'
];
return retryableErrors.includes(errorCode);
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
```
## Status Management
### Payment Status Types
* **pending**: Payment is being processed
* **completed**: Payment was successful
* **failed**: Payment failed
* **cancelled**: Payment was cancelled
* **expired**: Payment request expired
### Status Polling
```javascript theme={null}
async function pollPaymentStatus(paymentRequestId, maxAttempts = 30, interval = 2000) {
let attempts = 0;
while (attempts < maxAttempts) {
try {
const status = await checkPaymentStatus(paymentRequestId);
// Terminal states
if (['completed', 'failed', 'cancelled', 'expired'].includes(status.status)) {
return status;
}
// Continue polling for pending status
await delay(interval);
attempts++;
} catch (error) {
console.error('Status check failed:', error);
attempts++;
await delay(interval);
}
}
throw new Error('Payment status polling timeout');
}
```
## Response Validation
### Validate Response Structure
```javascript theme={null}
function validatePaymentResponse(response) {
const requiredFields = ['paymentRequestId', 'status'];
for (const field of requiredFields) {
if (!response[field]) {
throw new Error(`Missing required field: ${field}`);
}
}
// Validate status values
const validStatuses = ['pending', 'completed', 'failed', 'cancelled', 'expired'];
if (!validStatuses.includes(response.status)) {
throw new Error(`Invalid status: ${response.status}`);
}
return true;
}
```
### Response Processing
```javascript theme={null}
async function handlePaymentResponse(response) {
try {
// Validate response structure
validatePaymentResponse(response);
// Store payment record
await savePaymentRecord({
paymentRequestId: response.paymentRequestId,
status: response.status,
redirectUrl: response.redirectUrl,
timestamp: new Date().toISOString()
});
// Handle based on status
switch (response.status) {
case 'completed':
await handleSuccessfulPayment(response);
break;
case 'pending':
await handlePendingPayment(response);
break;
case 'failed':
await handleFailedPayment(response);
break;
default:
console.warn('Unexpected payment status:', response.status);
}
return response;
} catch (error) {
console.error('Response handling error:', error);
throw error;
}
}
```
## Best Practices
### Response Handling
1. **Immediate Validation**: Validate response structure immediately
2. **Status Tracking**: Always track payment status changes
3. **Error Logging**: Log all errors for debugging and monitoring
4. **Timeout Handling**: Implement appropriate timeout values
### Performance
1. **Connection Pooling**: Use HTTP connection pooling for better performance
2. **Async Processing**: Handle responses asynchronously when possible
3. **Caching**: Cache non-sensitive response data appropriately
4. **Monitoring**: Monitor response times and success rates
### Security
1. **Response Validation**: Always validate response data
2. **Sensitive Data**: Never log sensitive payment information
3. **Error Messages**: Sanitize error messages before displaying to users
4. **Audit Trail**: Maintain audit trail of all payment responses
## Next Steps
Learn about H2H API request format and parameters
Set up webhook notifications for real-time status updates
Explore available payment methods and implementations
# Testing & Sandbox
Source: https://docs.caibo.digital/h2h/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
Handle errors and troubleshooting
Deploy to production environment
Advanced webhook configuration
Complete API documentation
# Caibo IPG API Documentation
Source: https://docs.caibo.digital/index
Complete API reference and integration guide for Caibo's Integrated Payment Gateway (IPG). Access comprehensive documentation, code examples, and testing resources for seamless payment integration.
## Overview
Welcome to the Caibo Integrated Payment Gateway (IPG) API documentation. This comprehensive guide provides everything you need to integrate Caibo's payment processing capabilities into your applications, enabling secure and efficient payment transactions across multiple channels and payment methods.
## About Caibo IPG
Caibo IPG is a robust payment gateway solution that supports a wide range of payment methods including credit cards, digital wallets (Apple Pay, Google Pay), UPI payments, and alternative payment methods. Our platform is designed to handle high-volume transactions with enterprise-grade security and reliability.
### Key Features
* **Multi-Payment Method Support**: Credit cards, digital wallets, UPI, QR codes, and alternative payment methods
* **3D Secure Authentication**: Enhanced security with 3DS support for card transactions
* **Host-to-Host (H2H) Integration**: Direct server-to-server payment processing
* **Real-time Transaction Status**: Instant payment status updates and webhooks
* **Multi-Currency Support**: Process payments in multiple currencies with automatic conversion
* **Comprehensive Callback System**: Support for various payment provider callbacks
* **Sandbox Environment**: Full-featured testing environment for development and integration
## Supported Payment Methods
Caibo IPG supports a comprehensive range of payment methods to meet diverse customer preferences:
### Credit & Debit Cards
* **Visa, Mastercard, American Express**: Full support for major card networks
* **3D Secure Authentication**: Enhanced security with 3DS 1.0 and 2.0 support
* **Tokenization**: Secure card token storage for recurring payments
* **Multi-Currency Processing**: Accept payments in multiple currencies
### Digital Wallets
* **Apple Pay**: Seamless integration with Apple's payment ecosystem
* **Google Pay**: Support for Google's digital wallet solution
* **Secure Token Processing**: Handle encrypted payment tokens securely
### Alternative Payment Methods
* **UPI (Unified Payments Interface)**: Support for India's UPI payment system
* **QR Code Payments**: Generate and process QR code-based payments
* **Bank Transfers**: Direct bank account debits and transfers
## Integration Options
### Payment Request Flow
Create payment requests and handle customer payments through our hosted payment pages or direct API integration.
### Host-to-Host (H2H) Integration
Direct server-to-server integration for merchants who want full control over the payment experience.
### Callback & Webhook System
Real-time notifications for payment status updates from various payment providers including:
## API Endpoints Overview
| Endpoint Category | Description | Key Operations |
| -------------------- | ---------------------------------- | --------------------------------------------- |
| **Payment Requests** | Create and manage payment requests | Create, retrieve, handle payment methods |
| **Payments** | Process various payment types | Credit card, digital wallet, UPI, QR payments |
| **Transactions** | Transaction management and status | Get transaction details and status |
| **Customers** | Customer data management | Create and update customer information |
| **Exchanges** | Currency conversion | Get exchange rates and convert amounts |
| **Callbacks** | Payment provider webhooks | Handle provider-specific callbacks |
## Getting Started
### 1. Environment Setup
Use a single base URL for both Test and Production:
* **Server URL**: `https://apaycaibo.digital`
Test vs Production: The base URL is the same. The only difference is which H2H payment method IDs are enabled for your tenant. Endpoints, request/response schemas, and error codes are identical.
H2H IDs:
* Test: 35
* Live: 36
Use POST `/payments/h2h/{id}` and set `id` accordingly.
### 2. Authentication
All API requests require proper authentication using API keys generated from the Caibo Control Panel. Learn how to obtain and use API keys for secure payment processing.
Learn how to authenticate with Caibo IPG APIs using Control Panel-generated API keys
### 3. Create Your First Payment Request
```json theme={null}
{
"amount": 100.00,
"unit": "USD",
"referenceId": "ORDER-123",
"notifyUrl": "https://your-site.com/webhook",
"successUrl": "https://your-site.com/success",
"failureUrl": "https://your-site.com/failure"
}
```
### 4. Handle Payment Processing
Process payments using various methods:
* Redirect customers to hosted payment pages
* Integrate payment forms directly in your application
* Use server-to-server H2H integration
## Testing & Development
### Sandbox Environment
* Full-featured testing environment
* Test all payment methods and scenarios
* No real money transactions
* Complete API access for development
### Test Cards & Credentials
Use provided test card numbers and credentials for different payment scenarios including successful payments, declined transactions, and 3DS authentication flows.
## Next Steps
Set up authentication and generate API keys from the Control Panel
Explore the complete API reference with detailed endpoint documentation
Learn about supported payment methods and integration options
Step-by-step integration guide with code examples
# Create Customer
Source: https://docs.caibo.digital/ipg/customer/create_customer
api POST /customers
Create customer profiles in the Caibo IPG system for payment processing and account management.
# Overview
Customer creation is the first step in establishing a relationship with your users for payment processing. The Caibo IPG API allows you to create comprehensive customer profiles that include personal information, contact details, and preferences for future payment transactions.
Customer creation typically happens during the registration or onboarding process and is essential for tracking payment history, managing saved payment methods, and providing personalized payment experiences.
## Why Create Customer Profiles?
Creating customer profiles provides several benefits:
* **Payment History Tracking**: Maintain a complete record of all customer transactions
* **Saved Payment Methods**: Enable customers to store payment methods for faster checkout
* **Personalized Experience**: Customize payment flows based on customer preferences
* **Compliance**: Meet regulatory requirements for customer identification and verification
* **Analytics**: Generate insights on customer payment behavior and preferences
## Required Parameters
When creating a new customer, the following information is typically required:
* **name**: Customer's full name (required)
* **email**: Customer's email address (required)
* **phone**: Customer's phone number (optional)
* **address**: Customer's billing address (optional)
* **memberId**: Customer member identifier for integration with existing systems (optional)
## Customer Data Structure
### Essential Information
* **Personal Details**: Name, email, phone number, date of birth
* **Contact Information**: Primary email and phone for notifications
* **Unique Identifier**: System-generated customer ID for tracking
### Optional Information
* **Address Details**: Billing and shipping addresses for payment verification
* **Member Integration**: Connection with existing membership or loyalty systems
* **Preferences**: Payment method preferences, currency, and notification settings
## Security & Privacy
### Data Protection
* **PCI Compliance**: All payment data handled according to PCI DSS standards
* **Encryption**: Customer data encrypted in transit and at rest
* **Access Control**: Role-based access to customer information
* **Audit Trail**: Complete audit log of customer data access and changes
### Privacy Controls
* **Data Retention**: Configurable data retention policies
* **Right to Deletion**: Support for customer data deletion requests
* **Consent Management**: Track and manage customer consent preferences
* **Data Export**: Provide customer data exports upon request
## Integration Examples
### Update Customer Information
```javascript theme={null}
// Update customer profile
const updateData = {
email: 'newemail@example.com',
phone: '+1234567890',
preferences: {
currency: 'USD',
notifications: true
}
};
const response = await fetch('/api/customers/12345', {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
},
body: JSON.stringify(updateData)
});
```
### Get Payment Methods
```javascript theme={null}
// Retrieve user's saved payment methods
const paymentMethods = await fetch('/api/users/payment-methods/12345', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
}
});
const methods = await paymentMethods.json();
console.log('Saved payment methods:', methods);
```
## Error Handling
### Common Error Scenarios
* **Customer Not Found**: HTTP 404 when customer ID doesn't exist
* **Unauthorized Access**: HTTP 401 for invalid authentication
* **Validation Errors**: HTTP 400 for invalid customer data
* **Server Errors**: HTTP 500 for internal processing errors
### Error Response Format
```json theme={null}
{
"error": {
"code": "CUSTOMER_NOT_FOUND",
"message": "Customer with ID 12345 not found",
"details": {
"customerId": "12345",
"timestamp": "2024-01-15T10:30:00Z"
}
}
}
```
## Best Practices
### Customer Data Management
1. **Regular Updates**: Keep customer information current
2. **Validation**: Validate all customer data before storage
3. **Deduplication**: Prevent duplicate customer records
4. **Segmentation**: Use customer data for targeted experiences
### Performance Optimization
1. **Caching**: Cache frequently accessed customer data
2. **Pagination**: Use pagination for large customer lists
3. **Selective Loading**: Load only required customer data fields
4. **Async Processing**: Handle bulk operations asynchronously
### Security Best Practices
1. **Access Control**: Implement proper role-based access
2. **Data Minimization**: Store only necessary customer data
3. **Regular Audits**: Conduct regular security audits
4. **Incident Response**: Have procedures for data breaches
## Compliance Considerations
### GDPR Compliance
* **Lawful Basis**: Ensure lawful basis for data processing
* **Data Subject Rights**: Support all GDPR data subject rights
* **Privacy by Design**: Implement privacy-first architecture
* **DPO Consultation**: Consult with Data Protection Officer
### PCI DSS Requirements
* **Secure Storage**: Never store sensitive payment data
* **Access Logging**: Log all access to customer payment data
* **Network Security**: Secure network transmission of data
* **Regular Testing**: Conduct regular security testing
## Monitoring & Analytics
### Key Metrics
* **Customer Growth**: Track new customer registrations
* **Profile Completeness**: Monitor customer profile completion rates
* **Payment Method Usage**: Analyze payment method preferences
* **Customer Lifetime Value**: Calculate customer value metrics
### Reporting
* **Customer Demographics**: Age, location, and preference analysis
* **Payment Behavior**: Payment method and frequency analysis
* **Support Metrics**: Customer service interaction tracking
* **Retention Analysis**: Customer retention and churn analysis
## Next Steps
Explore available payment methods
Learn about API authentication
Set up payment status notifications
# Update Customer
Source: https://docs.caibo.digital/ipg/customer/update_customer
api PUT /customers/{id}
Update existing customer profiles and information through Caibo IPG API
# Overview
Update existing customer profiles in the Caibo IPG system to maintain accurate customer information and payment preferences. This endpoint is essential for maintaining accurate customer data and ensuring optimal payment processing experiences.
Customer updates should be performed whenever customer information changes, such as address updates, contact information changes, or preference modifications.
## API Endpoint
* **Method**: `PUT`
* **Path**: `/customers/{id}`
* **id** (required): The unique identifier of the customer to update
* Type: `integer (int64)`
* Example: `12345`
## Path Parameters
* **id** (required): The unique identifier of the customer to update
* Type: `integer (int64)`
* Example: `12345`
## Request Body
The request body should contain a `Client` object with the updated customer information. You only need to include the fields you want to update.
### Updatable Fields
* **Personal Information**
* Name
* Email address
* Phone number
* Date of birth
* **Address Information**
* Billing address
* Shipping address
* Country and region
* **Account Preferences**
* Default currency
* Language preference
* Notification settings
* Communication preferences
* **Account Status**
* Active/inactive status
* Account verification status
* Subscription preferences
## Integration Examples
### Basic Customer Update
```javascript theme={null}
// Update customer information
const customerId = 12345;
const updateData = {
email: "newemail@example.com",
phone: "+1234567890",
address: {
street: "456 New Street",
city: "San Francisco",
state: "CA",
zipCode: "94105",
country: "US"
}
};
const response = await fetch(`/api/customers/${customerId}`, {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
},
body: JSON.stringify(updateData)
});
if (response.ok) {
console.log('Customer updated successfully');
} else {
console.error('Update failed:', response.statusText);
}
```
### Partial Customer Update
```javascript theme={null}
// Update only specific fields
const customerId = 12345;
const partialUpdate = {
preferences: {
currency: "EUR",
notifications: false,
language: "fr"
}
};
const response = await fetch(`/api/customers/${customerId}`, {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
},
body: JSON.stringify(partialUpdate)
});
```
### Update with Validation
```javascript theme={null}
// Update customer with validation
async function updateCustomer(customerId, updateData) {
try {
// Validate update data
if (updateData.email && !isValidEmail(updateData.email)) {
throw new Error('Invalid email format');
}
if (updateData.phone && !isValidPhone(updateData.phone)) {
throw new Error('Invalid phone format');
}
const response = await fetch(`/api/customers/${customerId}`, {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
},
body: JSON.stringify(updateData)
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`Update failed: ${errorData.message}`);
}
return await response.json();
} catch (error) {
console.error('Customer update error:', error);
throw error;
}
}
```
## Response Codes
### Success Response
* **200 OK**: Customer updated successfully
### Error Responses
* **400 Bad Request**: Invalid request data or validation errors
* **401 Unauthorized**: Invalid or missing authentication credentials
* **404 Not Found**: Customer with specified ID does not exist
## Error Handling
### Common Error Scenarios
1. **Customer Not Found**
* Status: `404 Not Found`
* Cause: Invalid customer ID or customer has been deleted
* Solution: Verify the customer ID exists before attempting update
2. **Validation Errors**
* Status: `400 Bad Request`
* Cause: Invalid data format, missing required fields, or constraint violations
* Solution: Validate data before sending the request
3. **Authentication Errors**
* Status: `401 Unauthorized`
* Cause: Invalid, expired, or missing authentication token
* Solution: Refresh authentication token and retry
### Error Response Format
```json theme={null}
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"detail": "Invalid email format",
"instance": "/customers/12345"
}
```
## Best Practices
### Data Validation
1. **Client-Side Validation**: Validate data before sending to reduce server errors
2. **Format Checking**: Ensure email, phone, and address formats are correct
3. **Required Fields**: Check that all required fields are provided
4. **Data Sanitization**: Clean and sanitize user input before processing
### Update Strategy
1. **Partial Updates**: Only send fields that have changed to minimize data transfer
2. **Optimistic Updates**: Update UI immediately, then sync with server
3. **Conflict Resolution**: Handle cases where data has been modified by another process
4. **Audit Trail**: Log all customer updates for compliance and debugging
### Security Considerations
1. **Authorization**: Ensure users can only update their own profiles or have proper permissions
2. **Data Validation**: Validate all input data to prevent injection attacks
3. **Rate Limiting**: Implement rate limiting to prevent abuse
4. **Sensitive Data**: Handle sensitive information with extra care
## Use Cases
### Profile Management
* **Contact Updates**: When customers change email or phone numbers
* **Address Changes**: When customers move or update billing/shipping addresses
* **Preference Updates**: When customers modify notification or payment preferences
### Account Management
* **Status Changes**: Activating, deactivating, or suspending customer accounts
* **Verification Updates**: Updating verification status after identity checks
* **Subscription Changes**: Modifying subscription levels or preferences
### Compliance Updates
* **GDPR Compliance**: Updating consent preferences and data processing agreements
* **KYC Updates**: Refreshing Know Your Customer information as required
* **Tax Information**: Updating tax-related customer information
## Integration Considerations
### Before Updating
1. **Fetch Current Data**: Get current customer information to avoid overwriting unchanged fields
2. **User Permissions**: Verify the requesting user has permission to update the customer
3. **Data Backup**: Consider backing up current data before major updates
### After Updating
1. **Confirmation**: Send confirmation to customer about profile changes
2. **Audit Logging**: Log the update for compliance and troubleshooting
3. **Cache Invalidation**: Clear any cached customer data to ensure consistency
4. **Downstream Systems**: Notify other systems that depend on customer data
## Next Steps
Learn how to create new customer profiles
Manage customer's saved payment methods
Implement secure customer authentication
# Browser Support & Notes
Source: https://docs.caibo.digital/ipg/iframe-checkout/browser-support
Browser compatibility matrix for the Caibo embedded checkout SDK and important integration notes covering 3DS, wallets, scroll lock, and CSP.
# Overview
The embedded checkout SDK targets all evergreen desktop and mobile browsers. The matrix below summarizes support for the SDK itself and for the wallet payment methods that work inside the iframe.
## Browser Compatibility
| Browser | Embedded Checkout | Apple Pay | Google Pay |
| ----------- | :---------------: | :------------------------: | :--------: |
| Chrome 90+ | Yes | No (iOS/macOS Safari only) | Yes |
| Safari 14+ | Yes | Yes | Yes |
| Firefox 88+ | Yes | No | Yes |
| Edge 90+ | Yes | No | Yes |
Apple Pay availability follows Apple's platform restrictions and is independent of the SDK — it requires Safari on iOS or macOS.
## Important Notes
3-D Secure authentication navigates **within the iframe** — this is the expected behavior. The final authentication result is delivered to the parent window via `postMessage`, so your `onSuccess` / `onFailure` callbacks fire as usual.
Both wallets work normally inside the iframe; no extra configuration is required on your side. Make sure your domain is registered with the wallet provider as part of your merchant onboarding.
Opening the checkout URL directly (without the SDK) behaves as before — full-page redirects are used. The `embedded=true` flag is appended only when launched through `CaiboCheckout.init()`.
While the modal is open, the SDK sets `document.body.style.overflow = 'hidden'` to prevent background scrolling. The original value is restored automatically when `destroy()` runs (either via a terminal event or a manual call).
The SDK accepts `postMessage` from the checkout origin only. For stricter Content Security Policy setups, configure `frame-ancestors` on the backend so only your approved origins can embed the iframe.
Tokens are valid for 15 minutes from issuance. If a customer leaves the page open past that, the iframe will start receiving `401 Unauthorized` for every API call and the checkout UI will appear stuck. Mint a fresh token server-side and re-open the iframe to recover. See [Mint a Checkout Session Token](/ipg/iframe-checkout/checkout-session-token).
## Troubleshooting Quick Checks
Open DevTools inside the iframe. The most common causes are: (1) `paymentUrl` is missing the `token=` parameter, (2) the token expired (15-minute TTL — check the Network tab for `401`s), or (3) `originDomain` on the payment request does not match the page hosting the iframe.
Confirm the SDK script loaded and that `CaiboCheckout.init()` returned without error. Check the browser console for cross-origin warnings.
The token is being sent to an endpoint that is not on the token's [allow-list](/ipg/iframe-checkout/checkout-session-token), or the `paymentRequestId` in the URL/query does not match the bound id. Mint a token bound to the correct payment request.
Backdrop click, **×**, and **Esc** all fire `onCancel`. If you bound `onCancel` to a no-op, the modal will still tear down via `destroy()`.
Apple Pay only renders on Safari (iOS / macOS). Google Pay needs an HTTPS context and a supported Chromium-based browser.
The checkout page emits a `console.warn` if the iframe URL still carries `apiKey=`. Migrate to [checkout session tokens](/ipg/iframe-checkout/checkout-session-token) — the `apiKey` is a long-lived secret and must not appear in browser URLs.
## Next Steps
* [How Embedded Checkout Works](/ipg/iframe-checkout/how-it-works) — architecture and event flow.
* [SDK API Reference](/ipg/iframe-checkout/sdk-api-reference) — full option and payload list.
# Mint a Checkout Session Token
Source: https://docs.caibo.digital/ipg/iframe-checkout/checkout-session-token
Issue a short-lived, single-purpose token bound to one payment request and use it to drive the embedded checkout widget without exposing your merchant apiKey.
# Overview
A **checkout session token** is a short-lived secret that lets the embedded checkout iframe authenticate against the Caibo payment API without ever seeing your merchant `apiKey`. Your backend mints the token using your `apiKey`, hands it to the browser, and the SDK passes it to the checkout page in the `paymentUrl`.
Never embed your merchant `apiKey` in the iframe URL, in client-side code, in browser history, or in any URL that leaves your server. The `apiKey` is a long-lived bearer secret with full merchant access. Always exchange it for a checkout session token on the server.
## Security model
| Property | Merchant `apiKey` | Checkout session token |
| ---------------------- | ------------------------------------- | --------------------------------------------------------------- |
| Lifetime | Long-lived (until rotated) | **15 minutes** from issuance |
| Scope | Full merchant API access | Read **one** payment request + submit its payment |
| Bound to | The merchant | A single `paymentRequestId` |
| Where it lives | Merchant backend only | Browser session (sessionStorage) and a single URL/header |
| Where to transmit it | `X-API-Key` header — server-to-server | `X-Checkout-Token` header, or `?token=` in the iframe `src` URL |
| Mintable from a token? | n/a | **No** — tokens cannot mint more tokens |
A leaked checkout token can only act on the bound payment request, and only for the next 15 minutes. A leaked `apiKey` can drain the account.
## Endpoint
```http theme={null}
POST {api_base}/payment-requests/{paymentRequestId}/checkout-session
Header: X-API-Key:
Content-Type: application/json
```
| Parameter | In | Type | Description |
| ------------------ | ---- | ------ | ------------------------------------------------------------------------------------------- |
| `paymentRequestId` | path | number | The id returned by [Create a Payment Request](/ipg/iframe-checkout/create-payment-request). |
The request body is empty (`{}`). The token derives its scope entirely from the path id and the authenticated merchant.
This call MUST originate from your backend. The browser must never see your `apiKey`. The whole point of this endpoint is to keep the long-lived secret on the server.
## Response
```json theme={null}
{
"token": "bhMlOWTW16rHxnmOugI9Uu1qNJk4IzD0-EZfGsRLJDU",
"paymentRequestId": 17784899067150744,
"expiresAt": "2026-05-11T13:25:33Z",
"ttlSeconds": 900
}
```
| Field | Type | Description |
| ------------------ | ------ | ---------------------------------------------------------------------- |
| `token` | string | URL-safe base64 secret. 32 random bytes ≈ 43 characters. |
| `paymentRequestId` | number | The payment request the token is bound to. |
| `expiresAt` | string | ISO-8601 UTC timestamp when the token stops being accepted. |
| `ttlSeconds` | number | Total lifetime of the token in seconds (currently `900` = 15 minutes). |
## Using the token
### As a URL parameter (iframe `src`)
The iframe must boot from a URL — it cannot set a custom header on its initial document load — so the SDK accepts the token as a `?token=` query parameter. The Caibo checkout page consumes the value on bootstrap, stores it in `sessionStorage`, then sends it on every subsequent request as `X-Checkout-Token`.
```text theme={null}
https://pay.caibo.digital/main?requestId=REQUEST_ID&token=TOKEN
```
Notice there is **no `apiKey`** and **no `merchantId`** in the URL. The token already binds the merchant and the request server-side.
### As a header (server-to-server calls from a non-browser client)
If your integration calls a permitted endpoint outside the iframe SDK, send the token as a header instead:
```http theme={null}
X-Checkout-Token: bhMlOWTW16rHxnmOugI9Uu1qNJk4IzD0-EZfGsRLJDU
```
## What a token is allowed to do
A request bearing a checkout session token is authorised for a small, fixed allow-list of endpoints, and every endpoint that carries a `paymentRequestId` (in the path or query string) must match the bound id exactly. Anything else returns `403 Forbidden`.
| Method | Path | Notes |
| ------ | ---------------------------------------------------- | ----------------------------------------------------------------------------- |
| `GET` | `/payment-requests/{id}` | Must equal the bound id. |
| `GET` | `/users/settings/{merchantId}` | Branding / theme. |
| `GET` | `/users/payment-methods/{merchantId}?requestId={id}` | `requestId` must equal the bound id. |
| `GET` | `/users/logos/{merchantId}` | Merchant logo. |
| `GET` | `/users/addresses/{merchantId}` | Merchant address (used by Apple Pay domain check). |
| `GET` | `/payments/wallet-config` | Apple / Google Pay configuration. |
| `POST` | `/payments/creditCard/{id}` | Must equal the bound id. Same for `creditCardToken`, `googlePay`, `applePay`. |
| `GET` | `/payments/creditCard/status/{transactionId}` | Polling. |
| `GET` | `/payments/threeds/status/{transactionId}` | 3DS polling. |
| `GET` | `/payments/threeds/redirect/{transactionId}` | 3DS redirect. |
| `POST` | `/payments/threeds/ddc/{transactionId}` | 3DS device data collection. |
A checkout token explicitly **cannot** call `POST /payment-requests/{id}/checkout-session` — tokens cannot mint additional tokens. Use your `apiKey` to re-mint when one expires.
## Lifecycle
`POST /payment-requests` with `X-API-Key`. Save the returned `id`.
`POST /payment-requests/{id}/checkout-session` with `X-API-Key`. Save `token` and `expiresAt`.
Return the `token` (and `requestId`) to your frontend via your own authenticated endpoint. The browser must not see the `apiKey`.
Construct `paymentUrl = .../main?requestId=…&token=…` and call `CaiboCheckout.init({ paymentUrl, ... })`.
If the customer is still on the page when the token expires, mint a fresh one server-side and re-open the iframe. The token is not auto-refreshed.
## Error responses
| Status | Cause |
| ------ | ----------------------------------------------------------------------- |
| `401` | `apiKey` missing or invalid on the mint call. |
| `403` | Caller authenticated with a checkout token (cannot mint another token). |
| `404` | No payment request with the given `paymentRequestId`. |
Once issued, errors when **using** a token surface as:
| Status | Cause |
| ------ | ------------------------------------------------------------------------------------------- |
| `401` | Token unknown, expired, revoked, or exhausted. |
| `403` | Endpoint is not on the token's allow-list, or the path/query `paymentRequestId` mismatches. |
## Backward compatibility
Legacy integrations that still pass `?apiKey=` in the `paymentUrl` continue to work, but the checkout page emits a `console.warn` deprecation notice on every load. Plan a migration to the token flow — leaking an `apiKey` through the browser history or `Referer` header is a serious incident.
## Next Steps
* [Quick Start — Inline & Modal](/ipg/iframe-checkout/quick-start) — paste-ready mint + init snippets.
* [Framework Examples](/ipg/iframe-checkout/framework-examples) — full backend-mints + frontend-uses pattern in React, Angular, Vue.
* [SDK API Reference](/ipg/iframe-checkout/sdk-api-reference) — every option, event, and payload.
# Create a Payment Request
Source: https://docs.caibo.digital/ipg/iframe-checkout/create-payment-request
Create a payment request before initializing the embedded checkout SDK and obtain the requestId required by CaiboCheckout.init().
# Overview
Before initializing the checkout SDK, you must create a payment request via the API and obtain its `id`. The `requestId` is a required parameter in the `paymentUrl` passed to `CaiboCheckout.init()`. The accompanying `token` is obtained in the next step ([Mint a Checkout Session Token](/ipg/iframe-checkout/checkout-session-token)).
This call is made from your **backend** so your `X-API-Key` is never exposed to the browser. The returned payment request `id` is the value you'll use as `requestId` in the SDK.
## Endpoint
```http theme={null}
POST {api_base}/payment-requests?send=null
Header: X-API-KEY:
Content-Type: application/json
```
## Sample Request Body
```json theme={null}
{
"amount": 49.99,
"unit": "EUR",
"referenceId": "ORDER-12345",
"notifyUrl": "https://merchant.example.com/ipg/webhook",
"successUrl": "https://merchant.example.com/thank-you",
"failureUrl": "https://merchant.example.com/payment-failed",
"originDomain": "shop.example.com",
"client": {
"name": "Jane Doe",
"email": "jane@example.com",
"address": "123 Main St",
"phone": "+15551234567",
"memberId": "CUST-001"
}
}
```
## Field Reference
| Field | Type | Required | Description |
| -------------- | ------ | -------- | ------------------------------------------------------------------------ |
| `amount` | number | Yes | Total amount to charge. |
| `unit` | string | Yes | ISO 4217 currency code (e.g. `EUR`, `USD`). |
| `referenceId` | string | No | Your internal order identifier; echoed back on webhooks. |
| `notifyUrl` | string | No | Server-to-server webhook URL for status updates. |
| `successUrl` | string | No | URL the SDK delivers in the `payment.success` event payload. |
| `failureUrl` | string | No | URL the SDK delivers in the `payment.failure` event payload. |
| `originDomain` | string | No | Origin allow-list entry that must match the page hosting the SDK iframe. |
| `client` | object | No | Optional customer details prefilled into the checkout UI. |
## Use the Response
The response includes the payment request `id`. Pass that value as `requestId` when constructing the `paymentUrl` for `CaiboCheckout.init()`. Pair it with a freshly minted checkout session token:
```text theme={null}
https://pay.caibo.digital/main?requestId=REQUEST_ID&token=CHECKOUT_TOKEN
```
Do **not** put your `apiKey` in this URL. Use a short-lived checkout session token instead — see [Mint a Checkout Session Token](/ipg/iframe-checkout/checkout-session-token). The `apiKey` belongs only on your server.
Replace `REQUEST_ID` with the `id` from the response above, and `CHECKOUT_TOKEN` with the `token` returned by the [mint endpoint](/ipg/iframe-checkout/checkout-session-token).
## Next Steps
* [Mint a Checkout Session Token](/ipg/iframe-checkout/checkout-session-token) — required server-side step before opening the iframe.
* [Quick Start — Inline & Modal](/ipg/iframe-checkout/quick-start)
* [SDK API Reference](/ipg/iframe-checkout/sdk-api-reference)
# Framework Examples
Source: https://docs.caibo.digital/ipg/iframe-checkout/framework-examples
Embed Caibo checkout SDK in React, Angular, and Vue 3 applications with copy-ready code snippets.
# Overview
The embedded checkout SDK is framework-agnostic. The snippets below show idiomatic integrations for the three most common frontend frameworks.
The pattern is the same in each: your backend creates the payment request and mints a [checkout session token](/ipg/iframe-checkout/checkout-session-token), the frontend asks your backend for `{ requestId, token }`, then lazy-loads the SDK and calls `CaiboCheckout.init()` with a `paymentUrl` that carries the token. **Your merchant `apiKey` never reaches the browser.**
## 1) Backend: mint the token
The frontend frameworks below assume an endpoint on your own server that creates the payment request, mints the token, and returns both. A minimal Node.js sketch:
```js theme={null}
// POST /api/checkout/session (your own auth -- session cookie, JWT, ...)
app.post('/api/checkout/session', requireAuth, async (req, res) => {
// 1) Create the payment request
const pr = await fetch('https://apay.caibo.digital/payment-requests', {
method: 'POST',
headers: {
'X-API-Key': process.env.CAIBO_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({ amount: req.body.amount, unit: req.body.currency, /* ... */ })
}).then(r => r.json());
// 2) Mint a checkout session token bound to that request
const session = await fetch(
`https://apay.caibo.digital/payment-requests/${pr.id}/checkout-session`,
{
method: 'POST',
headers: {
'X-API-Key': process.env.CAIBO_API_KEY,
'Content-Type': 'application/json'
},
body: '{}'
}
).then(r => r.json());
// 3) Return ONLY the values the browser actually needs
res.json({ requestId: pr.id, token: session.token, expiresAt: session.expiresAt });
});
```
Never expose `process.env.CAIBO_API_KEY` to the browser. The whole purpose of the token is to keep the `apiKey` server-side.
## 2) Frontend: open the iframe with the token
```jsx theme={null}
import { useState } from 'react';
function CheckoutButton({ amount, currency, onSuccess, onFailure }) {
const [busy, setBusy] = useState(false);
function loadSdk() {
return new Promise((resolve) => {
if (window.CaiboCheckout) { resolve(); return; }
const s = document.createElement('script');
s.src = 'https://pay.caibo.digital/assets/js/checkout-sdk.js';
s.onload = resolve;
document.head.appendChild(s);
});
}
async function pay() {
setBusy(true);
try {
// Your backend creates the PR and mints the token in one call.
const { requestId, token } = await fetch('/api/checkout/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ amount, currency })
}).then(r => r.json());
await loadSdk();
window.CaiboCheckout.init({
mode: 'modal',
paymentUrl: `https://pay.caibo.digital/main?requestId=${requestId}&token=${token}`,
onSuccess,
onFailure
});
} finally {
setBusy(false);
}
}
return ;
}
```
```ts theme={null}
async pay(): Promise {
// Your backend creates the PR and mints the token in one call.
const { requestId, token } = await firstValueFrom(
this.http.post<{ requestId: string; token: string }>(
'/api/checkout/session',
{ amount: this.amount, currency: this.currency }
)
);
await this.loadSdk();
(window as any).CaiboCheckout.init({
mode: 'modal',
paymentUrl: `https://pay.caibo.digital/main?requestId=${requestId}&token=${token}`,
onSuccess: (data: any) => this.handleSuccess(data),
onFailure: (data: any) => this.handleFailure(data),
onCancel: () => this.handleCancel()
});
}
private loadSdk(): Promise {
return new Promise((resolve) => {
if ((window as any).CaiboCheckout) { resolve(); return; }
const script = document.createElement('script');
script.src = 'https://pay.caibo.digital/assets/js/checkout-sdk.js';
script.onload = () => resolve();
document.head.appendChild(script);
});
}
```
```js theme={null}
async function pay() {
// Your backend creates the PR and mints the token in one call.
const { requestId, token } = await fetch('/api/checkout/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ amount, currency })
}).then(r => r.json());
await loadSdk('https://pay.caibo.digital/assets/js/checkout-sdk.js');
window.CaiboCheckout.init({
mode: 'modal',
paymentUrl: `https://pay.caibo.digital/main?requestId=${requestId}&token=${token}`,
onSuccess: (data) => emit('success', data),
onFailure: (data) => emit('failure', data)
});
}
function loadSdk(src) {
return new Promise((resolve) => {
if (window.CaiboCheckout) { resolve(); return; }
const s = document.createElement('script');
s.src = src;
s.onload = resolve;
document.head.appendChild(s);
});
}
```
## Common Patterns
Mint the token the moment the user clicks **Pay**, not on page load. The token is valid for 15 minutes; minting it lazily avoids wasted tokens for users who never check out.
Inject the script tag only when the user clicks **Pay**, so first-page-load performance is not affected.
If the customer leaves the iframe open past 15 minutes, mint a fresh token server-side and re-open the iframe. The SDK does not auto-refresh.
The script exposes `window.CaiboCheckout` once. Guard against duplicate `
```
Replace `REQUEST_ID` and `CHECKOUT_TOKEN` in the examples below with the values returned by the two server-side calls above.
## Inline Mode
The checkout appears directly within a `
` on your page. Ideal for single-page checkout flows.
```html theme={null}
```
### When to use inline
The whole purchase flow lives on one page; embed the iframe as the next step.
You decide the iframe size and surrounding elements (totals, terms, support links).
## Modal Mode
The checkout opens as a centered modal with backdrop overlay. No container element needed. The modal handles its own UI — backdrop, close button (×), and the **Esc** key — all firing `onCancel`.
```html theme={null}
```
### When to use modal
Trigger payment from a button without disturbing the underlying page.
Subscriptions, top-ups, donations — the modal can be opened and closed at will.
## Behavior Summary
| Aspect | Inline | Modal |
| --------------------- | ------------------------------------ | ---------------------------------------------------------- |
| Container required | Yes — `containerId` | No — overlay attached to `` |
| Backdrop | None | Provided by the SDK |
| Close mechanisms | Programmatic via `destroy()` | Backdrop click, **×** button, **Esc** key (all `onCancel`) |
| Body scroll lock | Not applied | `document.body.style.overflow = 'hidden'` while open |
| Auto-cleanup on event | Yes (`success`, `failure`, `cancel`) | Yes (`success`, `failure`, `cancel`) |
## Next Steps
* [Mint a Checkout Session Token](/ipg/iframe-checkout/checkout-session-token) — server-side endpoint reference, scope rules, and error handling.
* [SDK API Reference](/ipg/iframe-checkout/sdk-api-reference) — every option, event, and payload field.
* [Framework Examples](/ipg/iframe-checkout/framework-examples) — React, Angular, and Vue 3 snippets.
# SDK API Reference
Source: https://docs.caibo.digital/ipg/iframe-checkout/sdk-api-reference
Complete reference for the Caibo embedded checkout SDK: CaiboCheckout.init() options, CaiboCheckout.destroy(), and event payloads.
# Overview
This page documents every method, option, and event payload exposed by the embedded checkout SDK.
## `CaiboCheckout.init(options)`
Initializes the checkout iframe and binds event listeners.
### Options
| Option | Type | Required | Default | Description |
| ------------- | ---------- | --------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `mode` | `string` | — | `'inline'` | Display mode: `'inline'` or `'modal'`. |
| `paymentUrl` | `string` | **Required** | — | Full checkout URL: `.../main?requestId=…&token=…` where `token` is a [checkout session token](/ipg/iframe-checkout/checkout-session-token). |
| `containerId` | `string` | **Inline only** | — | ID of the `
` to mount the iframe into. |
| `width` | `string` | — | `'480px'` | Modal width (modal) or iframe width (inline). |
| `height` | `string` | — | `'700px'` | CSS height of the iframe. |
| `onSuccess` | `function` | — | — | Called when payment completes successfully. |
| `onFailure` | `function` | — | — | Called when payment fails or is declined. |
| `onCancel` | `function` | — | — | Called when user cancels or closes the modal. |
| `onPending` | `function` | — | — | Called for async payment flows (e.g. waiting for bank confirmation). |
| `onReady` | `function` | — | — | Called when the checkout page has loaded inside the iframe. |
`containerId` is required only for `mode: 'inline'`. In `'modal'` mode the SDK creates its own overlay attached to `document.body`.
`paymentUrl` must carry a short-lived `token`, not your `apiKey`. The merchant `apiKey` is a long-lived secret and must stay on your server. Mint a token with [`POST /payment-requests/{id}/checkout-session`](/ipg/iframe-checkout/checkout-session-token) and pass the response's `token` as the `token` query parameter.
## `CaiboCheckout.destroy()`
Removes the iframe (inline) or the overlay (modal), cleans up all event listeners, and restores `document.body` scroll. Called **automatically** on `success`, `failure`, and `cancel`. Call it manually only to close programmatically (for example, from a custom abort button).
```js theme={null}
CaiboCheckout.destroy();
```
## Event Payload
All callbacks receive a single `data` object. The shape depends on the event:
| Event | Payload | Description |
| ----------------- | ------------------------------- | ------------------------------------ |
| `payment.success` | `{ url, requestId, paymentId }` | Redirect URL, request & payment IDs. |
| `payment.failure` | `{ url, requestId, paymentId }` | Failure URL with identifiers. |
| `payment.pending` | `{ url, requestId }` | Waiting URL for async flows. |
| `payment.cancel` | `{}` | User-initiated cancellation. |
| `payment.ready` | `{}` | Checkout page loaded. |
### Example Payloads
```js theme={null}
// payment.success
{ url: 'https://merchant.com/success', requestId: '12345', paymentId: '67890' }
// payment.failure
{ url: 'https://merchant.com/failure', requestId: '12345', paymentId: '67890' }
// payment.pending
{ url: 'https://merchant.com/waiting', requestId: '12345' }
// payment.cancel (user-initiated)
{}
```
## Lifecycle Summary
Call `CaiboCheckout.init(options)` to render the iframe and start listening for `postMessage` events.
Fired once the checkout page has rendered inside the iframe.
Exactly one of `onSuccess`, `onFailure`, `onPending`, or `onCancel` is fired.
The SDK removes the iframe/overlay and cleans up listeners. Body scroll is restored.
## Next Steps
* [Framework Examples](/ipg/iframe-checkout/framework-examples) — React, Angular, Vue 3.
* [Browser Support & Notes](/ipg/iframe-checkout/browser-support) — compatibility matrix and security notes.
# Get Payment Request
Source: https://docs.caibo.digital/ipg/payment-requests/get-payment-request
api GET /payment-requests/{id}
Retrieve detailed information about a specific payment request using its ID
# Overview
Retrieve comprehensive details about a specific payment request, including its current status, customer information, and transaction data.
## API Endpoint
```
GET /payment-requests/{id}
```
## Authentication
* **HTTP Header**: `X-API-Key` with your API key obtained from the dashboard
* **Content Type**: `application/json`
## Path Parameters
| Parameter | Description | Type | Required |
| --------- | -------------------------- | --------------- | -------- |
| `id` | Payment request identifier | integer (int64) | YES |
## Response
Returns complete payment request information including:
### Payment Request Details
* **ID**: Unique payment request identifier
* **Status**: Current payment request status
* **Amount**: Transaction amount and currency
* **Reference**: Merchant reference ID
* **Created Date**: When the payment request was created
* **Updated Date**: Last modification timestamp
### Customer Information
* **Customer ID**: Associated customer identifier
* **Name**: Customer full name
* **Email**: Customer email address
* **Phone**: Customer phone number
* **Address**: Billing/shipping address details
### Payment Configuration
* **Payment Methods**: Available payment options
* **Callback URLs**: Success, failure, and notification URLs
* **Expiration**: Payment request expiration time
* **Currency**: Transaction currency code
## Example Request
```bash theme={null}
curl -X GET \
"https://apay.caibo.digital/payment-requests/12345" \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json"
```
## Example Response
```json theme={null}
{
"id": 12345,
"status": "pending",
"amount": 100.50,
"currency": "USD",
"referenceId": "ORDER-12345",
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-15T10:30:00Z",
"expiresAt": "2024-01-15T11:30:00Z",
"customer": {
"id": 67890,
"name": "John Doe",
"email": "john.doe@example.com",
"phone": "+1234567890",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"postalCode": "10001",
"country": "US"
}
},
"paymentMethods": ["credit_card", "apple_pay", "google_pay"],
"urls": {
"success": "https://yoursite.com/success",
"failure": "https://yoursite.com/failure",
"notify": "https://yoursite.com/webhook"
},
"metadata": {
"orderId": "ORD-12345",
"productName": "Premium Subscription"
}
}
```
## Response Status Codes
| Code | Description |
| ----- | --------------------------------------------- |
| `200` | OK - Payment request found and returned |
| `400` | Bad Request - Invalid request format |
| `401` | Unauthorized - Invalid API key |
| `404` | Not Found - Payment request not found |
| `500` | Internal Server Error - Server error occurred |
## Error Response Format
```json theme={null}
{
"error": {
"code": "PAYMENT_REQUEST_NOT_FOUND",
"message": "Payment request with ID 12345 not found",
"details": {
"requestId": "req_abc123",
"timestamp": "2024-01-15T10:30:00Z"
}
}
}
```
## Use Cases
### Order Management
* **Order Tracking**: Link payment requests to order management systems
* **Status Monitoring**: Track payment progress in real-time
* **Customer Support**: Provide payment details for support inquiries
### Integration Scenarios
* **E-commerce Platforms**: Retrieve payment details for order fulfillment
* **Mobile Apps**: Display payment status to customers
* **Admin Dashboards**: Monitor payment request details
* **Reporting Systems**: Generate payment reports and analytics
## Implementation Example
### JavaScript/Node.js
```javascript theme={null}
async function getPaymentRequest(paymentId, apiKey) {
try {
const response = await fetch(
`https://apay.caibo.digital/payment-requests/${paymentId}`,
{
method: 'GET',
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json'
}
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const paymentRequest = await response.json();
return paymentRequest;
} catch (error) {
console.error('Error fetching payment request:', error);
throw error;
}
}
// Usage
const paymentDetails = await getPaymentRequest(12345, 'your-api-key');
console.log('Payment Status:', paymentDetails.status);
console.log('Amount:', paymentDetails.amount, paymentDetails.currency);
```
### PHP
```php theme={null}
getMessage();
}
?>
```
## Best Practices
### Security
* **API Key Protection**: Keep API keys secure and rotate regularly
* **HTTPS Only**: Always use HTTPS for API communications
* **Rate Limiting**: Implement appropriate rate limiting
* **Input Validation**: Validate payment request IDs before making requests
### Performance
* **Caching**: Cache payment request details when appropriate
* **Error Handling**: Implement robust error handling and retry logic
* **Monitoring**: Monitor API response times and success rates
* **Pagination**: Use pagination for bulk payment request retrieval
### Integration
* **Webhook Integration**: Use webhooks for real-time status updates instead of constant polling
* **Status Mapping**: Map payment request statuses to your system's workflow
* **Logging**: Log all API interactions for debugging and audit purposes
* **Testing**: Test with various payment request states and edge cases
## Related Endpoints
* **[Create Payment Request](/ipg/payment-request)**: Create new payment requests
* **[Payment Status Check](/ipg/payment-status-check)**: Check payment status
* **[Handle Payment Request](/ipg/handle-payment-request)**: Handle payment with specific method
* **[Release Payment Request](/ipg/release-payment-request)**: Release payment request
# Handle Payment Request
Source: https://docs.caibo.digital/ipg/payment-requests/handle-payment-request
api GET /payment-requests/handle/{id}/{paymentMethod}
Process a payment request using a specific payment method
# Overview
Process a payment request using a specific payment method. This endpoint allows you to handle payment requests with different payment methods like credit cards, digital wallets, or alternative payment options.
## API Endpoint
```
GET /payment-requests/handle/{id}/{paymentMethod}
```
## Authentication
* **HTTP Header**: `X-API-Key` with your API key obtained from the dashboard
* **Content Type**: `application/json`
## Path Parameters
| Parameter | Description | Type | Required |
| --------------- | ------------------------------------ | ------------------ | -------- |
| `id` | Payment request identifier | integer (int64) | YES |
| `paymentMethod` | Payment method to use for processing | PaymentMethod enum | YES |
## Payment Methods
The following payment methods are supported:
| Method | Description | Use Case |
| ---------------- | -------------------------- | ------------------------ |
| `CREDIT_CARD` | Credit/debit card payments | Standard card processing |
| `APPLE_PAY` | Apple Pay digital wallet | iOS/Safari payments |
| `GOOGLE_PAY` | Google Pay digital wallet | Android/Chrome payments |
| `UPI` | Unified Payments Interface | Indian market payments |
| `BANK_TRANSFER` | Direct bank transfers | ACH/wire transfers |
| `CRYPTOCURRENCY` | Digital currency payments | Bitcoin, Ethereum, etc. |
| `PAYPAL` | PayPal wallet payments | PayPal account holders |
## Response
Returns payment handling result including:
### Processing Information
* **Status**: Payment processing status
* **Transaction ID**: Generated transaction identifier
* **Redirect URL**: URL for customer to complete payment (if required)
* **Processing Time**: Estimated processing duration
### Payment Details
* **Method Used**: Confirmed payment method
* **Amount**: Transaction amount and currency
* **Fees**: Processing fees (if applicable)
* **Exchange Rate**: Currency conversion rate (if applicable)
## Example Request
```bash theme={null}
curl -X GET \
"https://apay.caibo.digital/payment-requests/handle/12345/CREDIT_CARD" \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json"
```
## Example Response
```json theme={null}
{
"status": "processing",
"transactionId": "txn_abc123def456",
"paymentMethod": "CREDIT_CARD",
"redirectUrl": "https://secure.caibo.io/payment/complete/txn_abc123def456",
"estimatedProcessingTime": "2-5 minutes",
"amount": {
"value": 100.50,
"currency": "USD"
},
"fees": {
"processingFee": 2.50,
"currency": "USD"
},
"expiresAt": "2024-01-15T11:30:00Z",
"nextSteps": {
"action": "redirect_customer",
"description": "Redirect customer to complete 3D Secure authentication",
"timeout": 900
}
}
```
## Response Status Codes
| Code | Description |
| ----- | --------------------------------------------------------------------- |
| `200` | OK - Payment handling initiated successfully |
| `400` | Bad Request - Invalid payment method or request |
| `404` | Not Found - Payment request not found |
| `422` | Unprocessable Content - Payment method not supported for this request |
| `500` | Internal Server Error - Processing error occurred |
## Error Response Examples
### Invalid Payment Method
```json theme={null}
{
"error": {
"code": "INVALID_PAYMENT_METHOD",
"message": "Payment method 'INVALID_METHOD' is not supported",
"supportedMethods": ["CREDIT_CARD", "APPLE_PAY", "GOOGLE_PAY", "UPI"]
}
}
```
### Payment Request Not Found
```json theme={null}
{
"error": {
"code": "PAYMENT_REQUEST_NOT_FOUND",
"message": "Payment request with ID 12345 not found or expired"
}
}
```
### Unprocessable Payment Method
```json theme={null}
{
"error": {
"code": "PAYMENT_METHOD_NOT_AVAILABLE",
"message": "APPLE_PAY is not available for this payment request",
"reason": "Customer device does not support Apple Pay"
}
}
```
## Payment Method Specific Handling
### Credit Card Processing
```bash theme={null}
GET /payment-requests/handle/12345/CREDIT_CARD
```
* Initiates 3D Secure authentication if required
* Returns redirect URL for card verification
* Processes payment immediately for non-3DS cards
### Digital Wallet Processing
```bash theme={null}
GET /payment-requests/handle/12345/APPLE_PAY
```
* Validates wallet availability on customer device
* Initiates biometric authentication flow
* Returns wallet-specific payment session
### UPI Processing
```bash theme={null}
GET /payment-requests/handle/12345/UPI
```
* Validates UPI ID format and availability
* Generates UPI payment link
* Supports QR code generation for mobile apps
## Implementation Examples
### JavaScript/Node.js
```javascript theme={null}
async function handlePaymentRequest(paymentId, paymentMethod, apiKey) {
try {
const response = await fetch(
`https://apay.caibo.digital/payment-requests/handle/${paymentId}/${paymentMethod}`,
{
method: 'GET',
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json'
}
}
);
if (!response.ok) {
const error = await response.json();
throw new Error(`Payment handling failed: ${error.message}`);
}
const result = await response.json();
// Handle different response types
if (result.redirectUrl) {
// Redirect customer to complete payment
window.location.href = result.redirectUrl;
} else if (result.status === 'completed') {
// Payment completed immediately
console.log('Payment completed:', result.transactionId);
}
return result;
} catch (error) {
console.error('Error handling payment:', error);
throw error;
}
}
// Usage examples
await handlePaymentRequest(12345, 'CREDIT_CARD', 'your-api-key');
await handlePaymentRequest(12345, 'APPLE_PAY', 'your-api-key');
await handlePaymentRequest(12345, 'UPI', 'your-api-key');
```
### Payment Method Selection
```javascript theme={null}
function selectPaymentMethod(availableMethods, customerPreference) {
const methodPriority = {
'APPLE_PAY': 1,
'GOOGLE_PAY': 2,
'CREDIT_CARD': 3,
'UPI': 4,
'BANK_TRANSFER': 5
};
// Filter available methods by customer device/preference
const supportedMethods = availableMethods.filter(method => {
switch (method) {
case 'APPLE_PAY':
return window.ApplePaySession && ApplePaySession.canMakePayments();
case 'GOOGLE_PAY':
return window.google && window.google.payments;
case 'UPI':
return customerPreference.country === 'IN';
default:
return true;
}
});
// Sort by priority and return best option
return supportedMethods.sort((a, b) =>
methodPriority[a] - methodPriority[b]
)[0];
}
```
## Integration Patterns
### Progressive Enhancement
1. **Start with Basic**: Begin with credit card as fallback
2. **Detect Capabilities**: Check for wallet/UPI support
3. **Offer Options**: Present available payment methods
4. **Handle Gracefully**: Fall back if preferred method fails
### Mobile Optimization
* **Wallet Priority**: Prioritize digital wallets on mobile
* **UPI for India**: Offer UPI as primary option in Indian market
* **Touch/Face ID**: Leverage biometric authentication
* **App Deep Links**: Support payment app integration
## Best Practices
### Payment Method Selection
* **Device Detection**: Choose methods based on customer device
* **Geographic Optimization**: Offer region-appropriate methods
* **Fallback Strategy**: Always provide alternative payment options
* **User Preference**: Remember customer's preferred methods
### Error Handling
* **Graceful Degradation**: Fall back to alternative methods
* **Clear Messaging**: Provide helpful error messages
* **Retry Logic**: Implement appropriate retry mechanisms
* **Support Integration**: Link to customer support for complex issues
### Security
* **Method Validation**: Verify payment method availability before processing
* **Timeout Handling**: Implement appropriate timeouts for each method
* **Fraud Detection**: Monitor for suspicious payment method patterns
* **Compliance**: Ensure compliance with payment method regulations
## Related Endpoints
* **[Get Payment Request](/ipg/get-payment-request)**: Retrieve payment request details
* **[Payment Status Check](/ipg/payment-status-check)**: Check payment status
* **[Release Payment Request](/ipg/release-payment-request)**: Release payment request
* **[Create Payment Request](/ipg/payment-request)**: Create new payment requests
# Payment Request
Source: https://docs.caibo.digital/ipg/payment-requests/payment-request
api POST /payment-requests
Create payment requests using the Caibo IPG API with comprehensive parameter support and flexible payment options.
# Overview
The Payment Request API allows you to create payment requests that customers can complete using various payment methods. This is the standard integration method for most merchants.
## Create Payment Request
Use this endpoint to create a new payment request with specified amount, currency, and callback URLs.
## Key Features
* **Multiple Payment Methods**: Support for credit cards, digital wallets, and alternative payment methods
* **Flexible Callbacks**: Configure success, failure, and notification URLs
* **Reference Tracking**: Include your own reference ID for order tracking
* **Multi-Currency**: Support for various currencies with automatic conversion
## Request Parameters
The payment request requires:
* **amount**: Payment amount (required)
* **unit**: Currency code (required)
* **referenceId**: Your internal order/transaction ID (optional)
* **notifyUrl**: Webhook URL for payment notifications (optional)
* **successUrl**: Redirect URL for successful payments (optional)
* **failureUrl**: Redirect URL for failed payments (optional)
## Response
Upon successful creation, you'll receive:
* Payment request ID
* Payment link for customer redirect
* Status and tracking information
## Next Steps
After creating a payment request:
1. Redirect customer to the payment link
2. Handle webhook notifications for status updates
3. Process success/failure redirects
4. Query payment status as needed
# Payment Status
Source: https://docs.caibo.digital/ipg/payment-requests/payment-status
api GET /payment-requests/status/{id}
Check payment request status and handle payment notifications
# Overview
Monitor and track payment requests using the status endpoint and handle payment notifications.
## Get Payment Request Status
Retrieve the current status of a payment request using its identifier.
### API Endpoint
```
GET https://apay.caibo.digital/payment-requests/status/{id}
```
### Authentication
* **HTTP Header**: `X-API-Key` with your API key obtained from the dashboard
* **Content Type**: `application/json`
### Request Parameters
| Parameter | Description | Required |
| --------- | --------------------------------------------------------- | -------- |
| `{id}` | Payment request identifier from payment creation response | YES |
### Response Fields
| Field | Description | Type |
| ------------------------ | ------------------------------------------------------------------------------------------------- | -------------- |
| `id` | Payment request identifier | string/integer |
| `recipientName` | Payment recipient name | string |
| `paymentRequestStatusId` | Payment request status: 1 – paid 2 – unpaid 3 – cancelled | integer |
| `transactionId` | Created transaction internal identifier | string/integer |
| `transactionNumber` | Created transaction public identifier | string |
| `transactionStatusId` | Created transaction status: 0 – waiting 1 – approved 2 – declined 3 – pending | integer |
| `link` | Payment request link to customer-facing web page | string |
| `unit` | Payment currency | string |
| `amount` | Payment amount | number |
| `referenceId` | Custom reference details | string |
| `notes` | Payment notes | string |
| `client` | Payment sender customer object | object |
| `notifyUrl` | Webhook URL for payment status notifications | string |
| `successUrl` | Redirect URL on successful payment | string |
| `failureUrl` | Redirect URL on failed payment | string |
| `lastLog` | Last payment attempt status and message | object |
### Last Log Object
| Field | Description | Type |
| --------------------- | -------------------------------------------------------------------------------------------------- | ------- |
| `transactionStatusId` | Last payment attempt status: 0 – waiting 1 – approved 2 – declined 3 – pending | integer |
| `message` | Last payment attempt message | string |
| `code` | Last payment attempt code | string |
### Example Request
```bash theme={null}
curl -X GET \
"https://apay.caibo.digital/payment-requests/status/16772761082427695" \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json"
```
## Payment Through SFTP
Process batch payments using SFTP file uploads for high-volume transactions.
### SFTP Configuration
* **Credentials**: Obtain SFTP address and credentials from the dashboard profile page
* **Multiple Providers**: Different SFTP addresses may be available for different payment providers
* **File Format**: Semicolon-delimited CSV without header row
### CSV File Format
Each row represents a separate payment with the following fields in order:
| Order | Field | Description | Required |
| ----- | ---------------- | --------------------------------------------------------- | -------- |
| 1 | Card holder name | Debit/credit card holder name | YES |
| 2 | Card number | Debit/credit card number | YES |
| 3 | Card expiration | Card expiration date (MM/YY format) | YES |
| 4 | Card CVV | Debit/credit card CVV code | YES |
| 5 | Email | Payer email address | YES |
| 6 | Phone | Payer phone number | YES |
| 7 | Address | Payer address | YES |
| 8 | City | Payer city name | YES |
| 9 | State | Payer state name or code (e.g., Florida or FL) | YES |
| 10 | Postal Code | Payer postal code | YES |
| 11 | Country | Payer country 2-letter ISO-3166-1 alpha-2 code (e.g., US) | YES |
| 12 | Amount | Payment amount (e.g., 10.50) | YES |
| 13 | Unit | Payment currency (e.g., USD, EUR, BTC, USDT) | YES |
| 14 | Reference ID | Merchant custom reference ID (free text) | NO |
### CSV Example
```csv theme={null}
Test User;4111111111111111;10/25;123;testu@email.com;972540000000;10 Unknown Street;Far Town;NA;123456;IL;10.50;USD;RI12345
```
**Important**: Field order is critical and must be maintained exactly as specified.
## Payment Notifications
Receive automated notifications about payment status changes via webhooks.
### Notification Setup
* **Configuration**: Set notify URL in dashboard profile page
* **Method**: HTTP POST with `application/x-www-form-urlencoded` content type
* **Requirement**: Notifications only sent if notify URL is configured
### Notification Fields
| Field | Description |
| ------------------------ | ---------------------------------------------- |
| `id` | Payment request identifier |
| `transactionId` | Payment request transaction identifier |
| `transactionStatusId` | Transaction status: 1 – approved, 2 – declined |
| `paymentRequestStatusId` | Payment status: 1 – paid, 2 – unpaid |
| `merchantId` | Merchant identifier (from control panel) |
| `unit` | Payment currency |
| `grossAmount` | Payment gross amount including fees |
| `fee` | Payment fee amount |
| `netAmount` | Net amount deposited to merchant wallet |
| `referenceId` | Custom reference details |
| `notes` | Payment notes |
| `clientId` | Payment sender customer identifier |
| `clientName` | Payment sender customer name |
| `clientEmail` | Payment sender customer email |
| `clientPhone` | Payment sender customer phone |
| `clientMemberId` | Payment sender customer member identifier |
| `message` | Payment failure reason message |
| `code` | Payment failure reason code |
### Example Notification
```
id=16772761082427695&transactionId=265111&transactionStatusId=1&paymentRequestStatusId=1&merchantId=16762420400394816&unit=USD&grossAmount=10&fee=0.5&netAmount=9.5&referenceId=12345¬es=Payment notes&clientId=16772748432912191&clientName=Client Name&clientEmail=client@email.com&clientPhone=1234567890&clientMemberId=12345&message=Stolen Card&code=008
```
## Notification Verification
Verify notification authenticity using HMAC SHA512 signature.
### Signature Verification
1. **Header**: Check `X-Signature` header in notification request
2. **Algorithm**: HMAC SHA512 hash in Base64 format
3. **Key**: Use your API key from the control panel
### Verification Process
```javascript theme={null}
// Pseudo code for signature verification
const crypto = require('crypto');
function verifySignature(payload, signature, apiKey) {
const hash = crypto
.createHmac('sha512', apiKey)
.update(payload)
.digest('base64');
return hash === signature;
}
// Usage
const isValid = verifySignature(requestBody, xSignatureHeader, yourApiKey);
```
## Error Codes
Complete list of error codes and descriptions for troubleshooting.
### Payment Processing Errors (001-020)
| Code | Description |
| ---- | ----------------------------------------------- |
| 001 | Bank system error. Try again later |
| 002 | Invalid or expired card |
| 003 | Card is blocked or restricted |
| 004 | 3DS system decline |
| 005 | Insufficient funds |
| 006 | Security code (CVV/PIN) incorrect |
| 007 | Transaction blocked due to risk control |
| 008 | Unsupported card type |
| 009 | Invalid email address format |
| 010 | Invalid postal/zip code |
| 011 | Invalid credentials or encryption error |
| 012 | Transaction was cancelled |
| 013 | Authentication timed out |
| 014 | Declined: Origin domain is blocked |
| 015 | Declined: Callback URL is not allowed |
| 016 | Declined: Email is blocked due high CHB history |
| 017 | Declined: Card is blocked due high CHB history |
| 018 | Declined: Transaction exceeds max amount |
| 019 | Declined: Transaction less than min amount |
| 020 | Declined: Currency is not allowed |
### Limit and Validation Errors (021-048)
| Code | Description |
| ---- | ------------------------------------------------------ |
| 021 | Declined: Number of transactions exceeded for today |
| 022 | Declined: Number of transactions exceeded this month |
| 023 | Declined: Total transaction amount exceeded for today |
| 024 | Declined: Total transaction amount exceeded this month |
| 025 | Invalid name |
| 026 | Invalid total amount |
| 027 | Invalid currency |
| 028 | Invalid reference |
| 029 | Invalid notify URL |
| 030 | Invalid success URL |
| 031 | Invalid failure URL |
| 032 | Invalid origin domain |
| 033 | Invalid phone number |
| 034 | Invalid address |
| 035 | Invalid city |
| 036 | Invalid state |
| 037 | Invalid country |
| 038 | Invalid UPI |
| 039 | Invalid capture delay hours |
| 040 | Invalid card number |
| 041 | Invalid card expiration |
| 042 | Invalid card CVV |
| 043 | Entity not found |
| 044 | Invalid customer |
| 045 | Invalid payment method |
| 046 | Invalid payment provider |
| 047 | Declined: Country is not allowed |
| 048 | Invalid token |
### System Errors (998-999)
| Code | Description |
| ---- | --------------------------------------------------- |
| 998 | System internal error. Contact system administrator |
| 999 | Transaction declined. Contact your card issuer |
## Best Practices
### Status Checking
* **Polling**: Check status periodically, not continuously
* **Rate Limiting**: Respect API rate limits
* **Error Handling**: Handle network timeouts and API errors gracefully
### SFTP Batch Processing
* **File Validation**: Validate CSV format before upload
* **Error Monitoring**: Monitor notification responses for batch failures
* **Batch Size**: Consider optimal batch sizes for your volume
### Notification Handling
* **Signature Verification**: Always verify notification signatures
* **Idempotency**: Handle duplicate notifications gracefully
* **Response Time**: Respond to notifications quickly (\< 30 seconds)
* **Error Handling**: Return appropriate HTTP status codes
### Security
* **API Key Protection**: Keep API keys secure and rotate regularly
* **HTTPS Only**: Use HTTPS for all API communications
* **Signature Verification**: Always verify webhook signatures
* **Error Logging**: Log errors without exposing sensitive data
# Release Payment Request
Source: https://docs.caibo.digital/ipg/payment-requests/release-payment-request
api GET /payment-requests/release/{id}
Release or cancel a payment request that is no longer needed
# Overview
Release or cancel a payment request that is no longer needed. This endpoint allows you to free up resources and prevent further processing of payment requests that should not be completed.
## API Endpoint
```
GET /payment-requests/release/{id}
```
## Authentication
* **HTTP Header**: `X-API-Key` with your API key obtained from the dashboard
* **Content Type**: `application/json`
## Path Parameters
| Parameter | Description | Type | Required |
| --------- | ------------------------------------- | --------------- | -------- |
| `id` | Payment request identifier to release | integer (int64) | YES |
## Use Cases
### Order Cancellation
* **Customer Cancellation**: Customer cancels order before payment
* **Inventory Issues**: Product out of stock after payment request created
* **Pricing Errors**: Incorrect pricing requires payment request cancellation
* **Duplicate Orders**: Remove duplicate payment requests
### System Management
* **Expired Requests**: Clean up expired payment requests
* **Failed Validation**: Release requests that fail business validation
* **Maintenance**: System maintenance requiring payment request cleanup
* **Resource Management**: Free up system resources
## Response
Returns release confirmation including:
### Release Information
* **Status**: Release operation status
* **Released At**: Timestamp when request was released
* **Reason**: Release reason (if provided)
* **Refund Status**: Refund processing status (if payment was captured)
### Impact Assessment
* **Transactions Affected**: List of related transactions
* **Refunds Initiated**: Automatic refunds triggered
* **Notifications Sent**: Customer notifications dispatched
## Example Request
```bash theme={null}
curl -X GET \
"https://apay.caibo.digital/payment-requests/release/12345" \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json"
```
## Example Response
```json theme={null}
{
"status": "released",
"paymentRequestId": 12345,
"releasedAt": "2024-01-15T10:45:00Z",
"previousStatus": "pending",
"reason": "Customer cancellation",
"impact": {
"transactionsAffected": [],
"refundsInitiated": [],
"notificationsSent": [
{
"type": "customer_notification",
"recipient": "customer@example.com",
"status": "sent"
},
{
"type": "merchant_notification",
"recipient": "merchant@example.com",
"status": "sent"
}
]
},
"metadata": {
"originalAmount": 100.50,
"currency": "USD",
"createdAt": "2024-01-15T10:30:00Z"
}
}
```
## Response Status Codes
| Code | Description |
| ----- | ----------------------------------------------------------------- |
| `200` | OK - Payment request released successfully |
| `400` | Bad Request - Invalid request format |
| `404` | Not Found - Payment request not found |
| `409` | Conflict - Payment request cannot be released (already processed) |
| `500` | Internal Server Error - Release operation failed |
## Error Response Examples
### Payment Request Not Found
```json theme={null}
{
"error": {
"code": "PAYMENT_REQUEST_NOT_FOUND",
"message": "Payment request with ID 12345 not found",
"details": {
"requestId": "req_abc123",
"timestamp": "2024-01-15T10:45:00Z"
}
}
}
```
### Cannot Release Processed Payment
```json theme={null}
{
"error": {
"code": "PAYMENT_ALREADY_PROCESSED",
"message": "Cannot release payment request that has already been processed",
"details": {
"currentStatus": "completed",
"transactionId": "txn_def456",
"processedAt": "2024-01-15T10:35:00Z"
}
}
}
```
### Release Operation Failed
```json theme={null}
{
"error": {
"code": "RELEASE_OPERATION_FAILED",
"message": "Failed to release payment request due to system error",
"details": {
"retryAfter": 300,
"supportReference": "SUP-789123"
}
}
}
```
## Release States and Conditions
### Releasable States
* **Pending**: Payment request created but not processed
* **Waiting**: Awaiting customer action
* **Expired**: Payment request has expired
* **Failed**: Payment processing failed
### Non-Releasable States
* **Processing**: Payment currently being processed
* **Completed**: Payment successfully completed
* **Refunded**: Payment already refunded
* **Cancelled**: Payment request already cancelled
## Implementation Examples
### JavaScript/Node.js
```javascript theme={null}
async function releasePaymentRequest(paymentId, apiKey, reason = null) {
try {
const response = await fetch(
`https://apay.caibo.digital/payment-requests/release/${paymentId}`,
{
method: 'GET',
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json'
}
}
);
if (!response.ok) {
const error = await response.json();
throw new Error(`Release failed: ${error.message}`);
}
const result = await response.json();
// Log release confirmation
console.log(`Payment request ${paymentId} released successfully`);
console.log('Release details:', result);
// Handle notifications
if (result.impact.notificationsSent.length > 0) {
console.log('Notifications sent:', result.impact.notificationsSent);
}
return result;
} catch (error) {
console.error('Error releasing payment request:', error);
throw error;
}
}
// Usage examples
await releasePaymentRequest(12345, 'your-api-key');
```
### Batch Release Operations
```javascript theme={null}
async function batchReleasePaymentRequests(paymentIds, apiKey) {
const results = [];
const errors = [];
for (const paymentId of paymentIds) {
try {
const result = await releasePaymentRequest(paymentId, apiKey);
results.push({ paymentId, status: 'released', result });
} catch (error) {
errors.push({ paymentId, status: 'failed', error: error.message });
}
}
return {
successful: results,
failed: errors,
summary: {
total: paymentIds.length,
released: results.length,
failed: errors.length
}
};
}
// Usage
const paymentIds = [12345, 12346, 12347];
const batchResult = await batchReleasePaymentRequests(paymentIds, 'your-api-key');
console.log('Batch release summary:', batchResult.summary);
```
### PHP Implementation
```php theme={null}
getMessage();
}
?>
```
## Integration Patterns
### Order Management Integration
```javascript theme={null}
class OrderManager {
async cancelOrder(orderId, reason) {
try {
// Get payment request ID from order
const order = await this.getOrder(orderId);
if (order.paymentRequestId) {
// Release payment request
await releasePaymentRequest(order.paymentRequestId, this.apiKey);
}
// Update order status
await this.updateOrderStatus(orderId, 'cancelled', reason);
// Send customer notification
await this.notifyCustomer(order.customerId, 'order_cancelled', {
orderId,
reason,
refundInfo: 'Refund will be processed within 3-5 business days'
});
} catch (error) {
console.error('Order cancellation failed:', error);
throw error;
}
}
}
```
### Automated Cleanup
```javascript theme={null}
async function cleanupExpiredPaymentRequests(apiKey) {
try {
// Get expired payment requests (implement based on your system)
const expiredRequests = await getExpiredPaymentRequests();
const results = [];
for (const request of expiredRequests) {
try {
await releasePaymentRequest(request.id, apiKey);
results.push({ id: request.id, status: 'released' });
} catch (error) {
results.push({ id: request.id, status: 'failed', error: error.message });
}
}
// Log cleanup results
console.log('Cleanup completed:', {
total: expiredRequests.length,
released: results.filter(r => r.status === 'released').length,
failed: results.filter(r => r.status === 'failed').length
});
return results;
} catch (error) {
console.error('Cleanup operation failed:', error);
throw error;
}
}
// Schedule cleanup (example with cron)
// 0 2 * * * node cleanup-expired-payments.js
```
## Best Practices
### When to Release
* **Order Cancellation**: Always release when orders are cancelled
* **Inventory Issues**: Release immediately when products become unavailable
* **Expired Requests**: Regularly clean up expired payment requests
* **System Maintenance**: Release pending requests before maintenance
### Error Handling
* **Retry Logic**: Implement retry for transient failures
* **Logging**: Log all release operations for audit trails
* **Monitoring**: Monitor release success rates
* **Alerting**: Alert on high failure rates
### Customer Communication
* **Immediate Notification**: Notify customers of cancellations immediately
* **Clear Messaging**: Explain why payment request was cancelled
* **Refund Timeline**: Provide clear refund expectations
* **Support Contact**: Offer support contact for questions
### System Integration
* **Order Management**: Integrate with order management systems
* **Inventory Systems**: Connect to inventory management
* **Customer Service**: Provide tools for support teams
* **Reporting**: Include release metrics in reporting
## Related Endpoints
* **[Get Payment Request](/ipg/get-payment-request)**: Retrieve payment request details
* **[Handle Payment Request](/ipg/handle-payment-request)**: Process payment with specific method
* **[Payment Status Check](/ipg/payment-status-check)**: Check payment status
* **[Create Payment Request](/ipg/payment-request)**: Create new payment requests