Corridorly Best Practices
Essential guidelines for building robust, secure, and production-ready integrations with Corridorly. Follow these practices to optimise performance, security, and reliability.
Overview
This guide consolidates best practices from across the Corridorly platform. Whether you're implementing the smart router, handling webhooks, or preparing for production, these guidelines will help you build a robust integration.
Security First
Protect API keys, verify webhooks, use HTTPS, and follow least privilege access
Optimised Performance
Minimise payload sizes, implement caching, and monitor execution times
Production Ready
Test thoroughly, monitor actively, and prepare for edge cases
API Usage Best Practices
Follow these patterns when making API requests to ensure reliability and predictability.
Always Use Idempotency KeysCritical
Include a unique idempotency_key in every payment request to prevent duplicate charges if a request is retried.
{
"amount": 9900,
"currency": "GBP",
"idempotency_key": "payment_${timestamp}_${customerId}_${orderId}"
}Use Test Mode During Development
Set testMode: true in metadata to prevent real charges and external API calls.
{
"amount": 9900,
"currency": "GBP",
"metadata": {
"testMode": true, // Prevents real charges
"orderId": "test_order_123"
}
}sk_dev_) when testing, never production keysMinimise Payload Size
Only include necessary data in API requests. Large payloads increase latency and processing time.
- • Sending entire user objects
- • Including unnecessary metadata
- • Duplicating data already stored
- • Send only customer ID
- • Include essential fields only
- • Reference existing records
Set Appropriate HTTP Headers
Always include proper headers for authentication and content type.
Security Best Practices
Security is paramount when handling payment data. Follow these practices to protect your integration and customer data.
Protect API KeysCritical
API keys provide full access to your Corridorly account. Treat them like passwords.
Always Verify Webhook SignaturesCritical
Never trust webhook payloads without HMAC-SHA256 signature verification. This prevents spoofing attacks.
const crypto = require('crypto');
function verifyWebhook(payload, signature, secret) {
const hmac = crypto
.createHmac('sha256', secret)
.update(JSON.stringify(payload))
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(hmac)
);
}
// In webhook handler
const signature = req.headers['x-corridorly-signature'];
if (!verifyWebhook(req.body, signature, webhookSecret)) {
return res.status(401).send('Invalid signature');
}Use HTTPS Everywhere
All webhook endpoints must use HTTPS with valid TLS certificates. Self-signed certificates will fail.
https://api.yourapp.com/webhookshttp://api.yourapp.com/webhooksPrinciple of Least Privilege
Grant team members only the permissions they need. Regularly audit access.
Webhook Implementation
Webhooks enable real-time event processing. Follow these practices for reliable webhook handling.
Respond Quickly (Within 10-15 Seconds)
Return a 200 OK response immediately. Process events asynchronously in background jobs.
app.post('/webhook', (req, res) => {
// Verify signature
verifySignature(req);
// Queue for processing
queue.add(req.body);
// Immediate response
res.status(200).send('OK');
});app.post('/webhook', async (req, res) => {
// Process synchronously (SLOW!)
await updateDatabase(req.body);
await sendEmail(req.body);
await updateCache(req.body);
res.status(200).send('OK');
});Implement Webhook Idempotency
Store processed event IDs to skip duplicates. Webhooks may be sent multiple times.
const processedEvents = new Set(); // or database
app.post('/webhook', async (req, res) => {
const eventId = req.body.id;
// Check if already processed
if (processedEvents.has(eventId)) {
return res.status(200).send('Already processed');
}
// Process event
await queue.add(req.body);
// Mark as processed
processedEvents.add(eventId);
res.status(200).send('OK');
});Monitor Webhook Health
Track delivery success rates and set up alerts for failed deliveries.
- • Delivery success rate
- • Failed delivery logs
- • Average response times
- • Retry attempt counts
- • Success rate drops below 95%
- • 5+ consecutive failures
- • Response time exceeds 8 seconds
- • SSL certificate expiring soon
Payment Routing Optimization
Optimise how the smart router selects payment providers to maximise success rates and minimise costs.
Configure Provider Priorities
Set up multiple payment providers with appropriate priorities for different scenarios.
- • Europe: Stripe, Adyen
- • APAC: Adyen, local providers
- • LATAM: Local providers first
- • US/CA: Stripe primary
- • Domestic: Lower-cost providers
- • Cross-border: Specialists
- • High volume: Negotiate rates
- • Enterprise: Custom routing
Monitor Provider Performance
Review routing decisions and success rates regularly to identify optimisation opportunities.
Plan for Provider Failures
Configure backup providers and understand the automatic fallback behavior.
Error Handling
Robust error handling ensures your integration gracefully handles failures and provides clear feedback.
Implement Client-Side Retry Logic
The Corridorly API does not automatically retry failed requests. Implement exponential backoff for transient errors.
async function makePaymentWithRetry(paymentData, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await corridorly.payments.route(paymentData);
return response; // Success
} catch (error) {
// Retry on transient errors (500, 503, network issues)
if (isRetryable(error) && attempt < maxRetries - 1) {
const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
await sleep(delay);
continue;
}
throw error; // Non-retryable or max attempts reached
}
}
}
function isRetryable(error) {
return error.status >= 500 || error.code === 'NETWORK_ERROR';
}Handle Error Codes Appropriately
Different errors require different handling strategies.
400 Bad Request• Don't retryInvalid request data. Fix the payload and resubmit.
401 Unauthorized• Don't retryInvalid API key. Check authentication credentials.
422 Unprocessable• Don't retryMissing required fields or validation failed. Review error message.
500/503 Server Error✓ Safe to retryTemporary issue. Retry with exponential backoff.
Log Errors Comprehensively
Capture sufficient context to debug issues quickly.
Testing & Development
Thorough testing ensures your integration works reliably before going to production.
Use Test Mode Extensively
Test mode prevents real charges and external API calls. Use it for all development and testing.
- • Simulated payment processing
- • No real provider API calls
- • Predictable test scenarios
- • Safe experimentation
- • Successful payments
- • Declined transactions
- • Network timeouts
- • Provider failures
Test Webhooks Locally
Use tools like ngrok or webhook.site to test webhooks during development.
# 1. Start your local server npm run dev # 2. Expose via ngrok ngrok http 3000 # 3. Use the ngrok URL in Corridorly dashboard https://abc123.ngrok.io/api/webhooks # 4. Test events fire to your local machine
Test Critical User Flows
Create integration tests for your main payment scenarios.
✓Successful payment with optimal routing✓Soft decline recovery (retry with same card)✓Hard decline handling (expired card, etc.)✓Webhook receipt and processing✓Idempotency key behavior✓Multi-currency transactionsProduction Readiness Checklist
Ensure you've completed all critical steps before going live with Corridorly in production.
Security Checklist
Configuration Checklist
Code Quality Checklist
Monitoring Checklist
Monitoring & Observability
Continuous monitoring helps you identify issues quickly and maintain high availability.
Track Key Metrics
Monitor these critical metrics in your dashboard and analytics tools.
- • Success rate (target: ≥95%)
- • Average transaction amount
- • Decline rate by reason
- • Provider distribution
- • Geographic breakdown
- • API response times
- • Webhook delivery success rate
- • Error rates by type
- • Retry attempt frequency
- • Provider health scores
Configure Critical Alerts
Set up alerts for conditions that require immediate attention.
Review Dashboard Regularly
Make dashboard reviews part of your routine operations.
- • Transaction volume
- • Success rates
- • Recent errors
- • Provider performance
- • Geographic trends
- • Webhook health
- • Cost analysis
- • Routing optimization
- • Access review
Ready to Build?
With these best practices in place, you're ready to build a robust, production-ready integration with Corridorly.