๐ Introduction: The Role of API Documentation
Payment gateway API documentation is the technical blueprint that developers use to integrate a payment gateway into their applications. It provides all the necessary information to connect, authenticate, send requests, handle responses, and process payments programmatically.
Well-written API documentation is critical for a successful integration. It reduces development time, minimizes errors, and enables developers to build robust payment flows with confidence.
Good API documentation can reduce integration time by 50-70% and decrease support tickets by providing clear, self-service answers to common questions.
๐ Key Sections of API Documentation
Comprehensive payment gateway API documentation typically includes:
High-level description of the API, its capabilities, and what it enables developers to build.
How to authenticate API requests โ API keys, OAuth 2.0, JWT tokens, or HMAC signatures.
Detailed descriptions of each API endpoint, including URL, method, parameters, request body, and response format.
Concrete examples of API calls and responses in multiple programming languages (cURL, Python, JavaScript, etc.).
Information about asynchronous callbacks, including event types, payload structure, and security/verification.
List of error codes, status codes, and troubleshooting guidance.
๐ Authentication Methods
Payment gateways typically use one or more of these authentication methods:
| Method | Description | Security Level | Common Use |
|---|---|---|---|
| API Key (Header) | Send API key in the X-API-Key or Authorization header | Medium | Most common for simple integrations |
| API Key (Query) | Send API key as a query parameter (?api_key=xxx) | Low | Legacy or simple public APIs |
| OAuth 2.0 | Standard authorization framework with access tokens | High | Enterprise, third-party integrations |
| JWT (JSON Web Token) | Signed tokens with expiration and claims | High | Stateless authentication, modern APIs |
| HMAC Signature | Cryptographic signature of request payload | High | Webhook verification, secure endpoints |
| Basic Auth | Username and password (Base64 encoded) | Low | Legacy systems, internal APIs |
Always use API keys in headers (not query parameters) and store them securely in environment variables. Never expose API keys in client-side code or version control.
๐ Common API Endpoints
Here are typical endpoints found in payment gateway API documentation:
| Endpoint | Method | Description | Key Parameters |
|---|---|---|---|
/api/v1/payments | POST | Create a new payment request | amount, currency, payment_currency, order_id |
/api/v1/payments/{id} | GET | Get payment details | payment_id |
/api/v1/payments/{id}/status | GET | Check payment status | payment_id |
/api/v1/currencies | GET | List supported currencies | โ |
/api/v1/rates | GET | Get exchange rates | from, to |
/api/v1/invoices | POST | Create a payment invoice | amount, currency, customer_email |
/api/v1/refunds | POST | Process a refund | payment_id, amount |
/api/v1/merchant/balance | GET | Check merchant balance | โ |
Example: Create Payment Request
POST /api/v1/payments
Headers: X-API-Key: your_api_key
Content-Type: application/json
{
"amount": "100.00",
"currency": "USD",
"payment_currency": "USDT",
"order_id": "order_12345",
"callback_url": "https://yoursite.com/webhook/payment"
}
Response (201 Created):
{
"payment_id": "pay_abc123",
"address": "T...",
"amount": "100.00",
"payment_currency": "USDT",
"expires_at": "2025-06-25T12:00:00Z",
"status": "pending"
}
๐ Webhooks: Asynchronous Notifications
Webhooks are asynchronous callbacks that the payment gateway sends to your server when payment events occur. They are critical for automating order fulfillment without polling the API.
| Event Type | Description | When Triggered |
|---|---|---|
payment.created | Payment request created | After POST /payments |
payment.received | Transaction detected on blockchain | When funds are sent (unconfirmed) |
payment.confirmed | Payment confirmed | After required confirmations |
payment.expired | Payment request expired | After expiration time without payment |
payment.underpaid | Amount received is less than expected | When underpayment is detected |
payment.overpaid | Amount received is more than expected | When overpayment is detected |
refund.completed | Refund processed | After refund is completed |
merchant.balance.updated | Merchant balance changed | After settlement |
// Example: Verifying a webhook signature (Node.js)
const crypto = require('crypto');
function verifyWebhook(payload, signature, secret) {
const expected = crypto
.createHmac('sha256', secret)
.update(JSON.stringify(payload))
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expected)
);
}
Always verify webhook signatures, respond with HTTP 200 OK to acknowledge receipt, implement idempotency to handle duplicate events, and monitor webhook delivery for failures.
โ ๏ธ Error Handling
Understanding API error responses is essential for building robust integrations:
| HTTP Status | Meaning | Common Causes | Action |
|---|---|---|---|
| 200 | OK | Request successful | Process response |
| 201 | Created | Resource created | Store resource ID |
| 400 | Bad Request | Invalid parameters, missing fields | Check request payload |
| 401 | Unauthorized | Invalid or missing API key | Verify authentication |
| 403 | Forbidden | Insufficient permissions | Check API key permissions |
| 404 | Not Found | Resource doesn't exist | Verify resource ID |
| 422 | Unprocessable Entity | Validation errors | Fix validation issues |
| 429 | Too Many Requests | Rate limit exceeded | Implement backoff/retry |
| 500 | Internal Server Error | Gateway server issue | Retry with exponential backoff |
| 503 | Service Unavailable | Gateway down or overloaded | Retry after delay |
// Example error response
{
"error": {
"code": "INVALID_AMOUNT",
"message": "Amount must be greater than 0",
"field": "amount",
"status": 400
}
}
๐ฆ SDKs and Libraries
Many payment gateways provide official Software Development Kits (SDKs) in popular programming languages to simplify integration:
For web applications and server-side Node.js integrations.
For Python web frameworks (Django, Flask) and backend services.
For enterprise applications and Android integrations.
For WordPress, Laravel, and PHP-based e-commerce platforms.
SDKs handle authentication, request formatting, and error handling automatically. They significantly reduce integration code and ensure best practices are followed.
๐งช Testing and Sandbox Environment
Most payment gateways provide a sandbox (test) environment for integration testing:
- Sandbox URL โ separate endpoint for test transactions (e.g.,
https://sandbox.gateway.com). - Test API Keys โ separate keys for sandbox environment.
- Test Payment Methods โ simulated payment methods (test card numbers, testnet cryptocurrencies).
- Simulated Events โ ability to trigger webhook events for testing.
Always test thoroughly in sandbox before moving to production. Simulate all payment flows, edge cases, and webhook scenarios.