Integration Flow
This guide walks you through the complete integration process with FLUID Network's API, from initial setup to production deployment.
Overview
The integration process follows these main stages:
Stage 1: Setup
1.1 Get API Credentials
Contact FLUID Network to receive your API credentials:
- Sandbox API Key: For testing and development
- Production API Key: For live transactions
- Webhook Secret: For verifying webhook signatures
1.2 Configure Your Environment
Set up environment-specific configuration with separate settings for sandbox (testing) and production environments. Store your API credentials in environment variables, never hardcode them in your application code:
- Sandbox: Use
https://sandbox-api.fluid-network.com/api/v1as base URL - Production: Use
https://api.fluid-network.com/api/v1as base URL - Store API keys and webhook secrets in environment variables
- Use your framework's configuration management system
1.3 Install Dependencies
Install an HTTP client library for your programming language to make API requests (e.g., axios for Node.js, requests for Python, Guzzle for PHP, Faraday for Ruby).
Stage 2: Authentication
2.1 Create API Client
Build a reusable API client with authentication. Your client should:
- Set the base URL (sandbox or production)
- Include
Authorization: Bearer {api_key}header on all requests - Set
Content-Type: application/jsonheader - Configure appropriate timeout (recommended: 30 seconds)
- Implement request/response logging for debugging
- Handle errors gracefully with proper error messages
- Provide methods for common operations (initiate debit, get transaction, get balance)
2.2 Verify Authentication
Test your API connection by calling the balance endpoint or any simple GET endpoint. A successful response confirms your authentication is working correctly. If authentication fails, verify:
- API key is correct for your environment (sandbox vs production)
- API key is properly set in Authorization header as
Bearer {api_key} - Base URL matches your environment
- Network connectivity to FLUID API servers
Stage 3: Test Integration
3.1 Initiate Test Transaction
Create your first test transaction in sandbox. The transaction flow includes:
- Initiate Transaction: Call the debit initiation endpoint with transaction details
- Store Transaction ID: Save the returned
transaction_idfor status tracking - Poll for Status (optional): Query transaction status periodically if webhook not received
- Handle Final Status: Process completed, failed, or cancelled states
Test Transaction Details:
- Amount: 5000 (50.00 GHS in smallest currency unit - pesewas)
- Currency: GHS
- Phone: Use sandbox test numbers (see table below)
- Partner Reference: Unique identifier from your system
- Description: Human-readable transaction description
- Callback URL: Your webhook endpoint (use ngrok for local testing)
Status Polling Pattern:
- Maximum 10 attempts recommended
- 3-second intervals between polls
- Stop polling when status is
completed,failed, orcancelled - Always rely on webhooks as primary status update mechanism
3.2 Test Different Scenarios
Use sandbox test phone numbers to simulate different outcomes:
| Phone Number | Behavior | Use Case |
|---|---|---|
+233241234567 | Auto-success after 5 seconds | Happy path testing |
+233241111111 | Auto-fail (insufficient funds) | Error handling |
+233242222222 | Auto-fail (invalid account) | Validation errors |
+233243333333 | Timeout (no response) | Timeout handling |
+233244444444 | Requires manual approval | Pending state testing |
Stage 4: Handle Webhooks
4.1 Set Up Webhook Endpoint
Create an endpoint to receive webhook notifications. Your webhook handler should:
Security Requirements:
- Use raw request body for signature verification (don't parse JSON first)
- Verify HMAC-SHA256 signature from
X-Fluid-Signatureheader - Use timing-safe comparison for signature validation
- Return 401 Unauthorized if signature is invalid
- Require HTTPS in production
Response Requirements:
- Respond with 200 status code within 5 seconds
- Process webhook asynchronously if heavy operations needed
- Return simple success JSON:
{ "received": true }
Processing Logic:
- Verify Signature: Validate request authenticity using webhook secret
- Check Idempotency: Prevent duplicate processing using
event_id - Store Event: Log webhook event for audit trail
- Handle Event Type: Process based on event type (transaction.completed, transaction.failed, etc.)
- Update Database: Update transaction status in your system
- Trigger Actions: Send emails, fulfill orders, etc.
Event Handlers:
transaction.completed: Payment successful - fulfill order, credit account, send confirmationtransaction.failed: Payment failed - update status, notify customer, log for reviewtransaction.pending: Payment awaiting approval - update UI, set timeout for fallback polling
Signature Verification Process:
- Extract raw request body (before parsing)
- Extract signature from
X-Fluid-Signatureheader - Compute HMAC-SHA256 using webhook secret and raw body
- Compare computed signature with provided signature using constant-time comparison
4.2 Expose Webhook Endpoint
For local testing, use a tunneling service:
# Using ngrok
ngrok http 3000
# Your webhook URL will be:
# https://abc123.ngrok.io/webhooks/fluid
# Update this URL in your transaction initiation:
# callback_url: 'https://abc123.ngrok.io/webhooks/fluid'4.3 Test Webhook Delivery
Initiate a test transaction and verify webhook reception:
# Terminal 1: Start your webhook server
node webhook-server.js
# Terminal 2: Start ngrok tunnel
ngrok http 3000
# Terminal 3: Initiate test transaction
node test-transaction.js
# Check Terminal 1 for webhook logsStage 5: Go Live
5.1 Pre-Launch Checklist
Before switching to production:
✅ Security
- ✅ Store API keys in environment variables (never in code)
- ✅ Implement webhook signature verification
- ✅ Use HTTPS for all webhook endpoints
- ✅ Implement rate limiting on your endpoints
- ✅ Set up IP whitelisting if required
✅ Error Handling
- ✅ Handle all error codes appropriately
- ✅ Implement retry logic for transient errors
- ✅ Log all API interactions
- ✅ Set up error monitoring (Sentry, Rollbar, etc.)
✅ Idempotency
- ✅ Use unique
partner_referencefor each transaction - ✅ Implement deduplication for webhook events
- ✅ Handle retry scenarios gracefully
- ✅ Use unique
✅ Testing
- ✅ Test all transaction flows in sandbox
- ✅ Test webhook delivery and processing
- ✅ Test error scenarios
- ✅ Load test your integration
- ✅ Verify database transactions are atomic
✅ Monitoring
- ✅ Set up transaction monitoring dashboard
- ✅ Configure alerting for failed transactions
- ✅ Monitor webhook delivery success rate
- ✅ Track API performance metrics
5.2 Switch to Production
Update your configuration to use production credentials:
# Set production environment variables
export NODE_ENV=production
export FLUID_PRODUCTION_API_KEY=your_production_key
export FLUID_PRODUCTION_WEBHOOK_SECRET=your_webhook_secret
# Deploy your application
# Start with low volume to verify everything works5.3 Gradual Rollout
Implement a gradual rollout strategy to minimize risk when launching in production:
Recommended Rollout Schedule:
- Week 1: 10% of traffic to FLUID Network (validate basic functionality)
- Week 2: 25% of traffic (monitor error rates and performance)
- Week 3: 50% of traffic (compare metrics with baseline)
- Week 4: 100% of traffic (full production rollout)
Feature Flag Implementation: Use consistent hashing to ensure the same user always gets the same experience. This prevents confusion from inconsistent payment methods across sessions.
Key Principles:
- Use deterministic hashing based on user ID for consistency
- Configure rollout percentage via environment variable
- Calculate hash bucket (0-99) and compare with rollout percentage
- Users in lower buckets are enabled first
- Same user always gets same assignment (no random switching)
Stage 6: Monitor & Optimize
6.1 Key Metrics to Track
Monitor these metrics in production:
| Metric | Target | Alert Threshold |
|---|---|---|
| Transaction success rate | > 95% | < 90% |
| Average transaction time | < 30s | > 60s |
| Webhook delivery rate | > 99% | < 95% |
| API error rate | < 1% | > 5% |
| Retry rate | < 5% | > 10% |
6.2 Set Up Monitoring Dashboard
Create a dashboard to visualize key metrics for your FLUID integration. Track these metrics:
Transaction Metrics:
- Total transaction count by status (completed, failed, pending, cancelled)
- Transaction duration histogram with buckets: 5s, 10s, 30s, 60s, 120s
- Success rate percentage
- Failure rate by error code
Webhook Metrics:
- Total webhook count by event type
- Webhook processing time
- Webhook delivery failures
API Metrics:
- API request rate
- API error rate by endpoint
- API response time percentiles (p50, p95, p99)
Implementation Options:
- Prometheus + Grafana for metrics collection and visualization
- Datadog for full-stack monitoring
- New Relic for application performance monitoring
- CloudWatch for AWS deployments
- Custom dashboard using your preferred monitoring tool
6.3 Optimize Performance
Based on monitoring data, optimize your integration:
Reduce Polling
- Use webhooks as primary status update mechanism
- Only poll as fallback if webhook not received within timeout
- Implement exponential backoff for polling
Batch Operations
- Use transaction query endpoint to fetch multiple transactions
- Batch database updates from webhook processing
- Implement job queues for asynchronous processing
Caching
- Cache balance information with appropriate TTL
- Cache transaction status for completed/failed transactions
- Use Redis or similar for distributed caching
Connection Pooling
- Reuse HTTP connections to FLUID API
- Configure appropriate connection pool size
- Set reasonable timeout values
6.4 Continuous Improvement
Regular optimization tasks:
Weekly
- Review error logs and address recurring issues
- Check webhook delivery failures
- Monitor API performance trends
Monthly
- Analyze transaction success rates
- Review and optimize retry logic
- Update documentation for team members
Quarterly
- Conduct security audit
- Review and update monitoring thresholds
- Load test with production-like traffic
Common Integration Patterns
Pattern 1: E-Commerce Checkout
Flow Overview:
- Create Order: Save order in your database with
pending_paymentstatus - Initiate Transaction: Call FLUID debit endpoint with order details
- Store Transaction ID: Link FLUID transaction ID to your order record
- Update Status: Change order status to
awaiting_payment - Return to Customer: Display "Complete payment on your phone" message
Webhook Handling:
- On transaction.completed: Update order to
paid, trigger fulfillment, send confirmation email - On transaction.failed: Update order to
payment_failed, notify customer with retry option
Key Considerations:
- Use order ID as
partner_referencefor easy lookup - Convert order total to smallest currency unit (pesewas)
- Include order number in transaction description
- Handle concurrent webhook/polling status updates with database locks
Pattern 2: Subscription Billing
Flow Overview:
- Schedule Recurring Charge: Use cron job or scheduled task to charge subscriptions
- Check Existing Charge: Prevent duplicate charges by checking if current period already charged
- Generate Idempotency Key: Use subscription ID + billing period as
partner_reference - Initiate Charge: Call FLUID debit endpoint
- Record Attempt: Store charge attempt with transaction ID and period
Webhook Handling:
- On transaction.completed: Mark subscription as active, send receipt
- On transaction.failed: Increment retry count, suspend after max retries, notify customer
Key Considerations:
- Use format like
SUB-{subscription_id}-{period}for partner_reference - Implement retry logic with exponential backoff (retry after 1 day, 3 days, 7 days)
- Send reminder emails before charging
- Handle grace periods for failed payments
- Track dunning management for past-due subscriptions
Pattern 3: Peer-to-Peer Transfers
Flow Overview:
- Validate Transfer: Check sender balance, verify recipient exists, validate amount
- Create Transfer Record: Store transfer in database with
initiatedstatus - Charge Sender: Initiate FLUID debit transaction from sender's phone
- Link Transaction: Store FLUID transaction ID with transfer record
- Wait for Webhook: Don't credit recipient until sender charge completes
Webhook Handling:
- On transaction.completed: Credit recipient balance, update transfer to
completed, notify both users - On transaction.failed: Update transfer to
failed, notify sender with reason, don't credit recipient
Key Considerations:
- Use atomic database transactions to ensure consistency
- Lock sender account during transfer to prevent overdraft
- Use format like
P2P-{transfer_id}for partner_reference - Include recipient name in transaction description for sender clarity
- Implement transfer limits (daily/per-transaction) for fraud prevention
- Consider holding funds during processing to prevent double-spending
Troubleshooting
Issue: Webhooks Not Received
Symptoms: Transactions complete but webhooks not arriving
Solutions:
- Verify webhook URL is publicly accessible (use webhook.site to test)
- Check webhook endpoint returns 2xx status within 5 seconds
- Verify SSL certificate is valid
- Check firewall/security group rules
- Review webhook delivery logs in FLUID dashboard
Issue: Signature Verification Fails
Symptoms: Invalid signature errors on webhook endpoint
Solutions:
- Verify you're using raw request body (not parsed JSON)
- Check you're using correct webhook secret for environment
- Ensure no middleware is modifying request body
- Verify HMAC algorithm is SHA-256
- Use constant-time comparison for signatures
Issue: High Transaction Failure Rate
Symptoms: Many transactions failing with same error
Solutions:
- Check error codes and messages in failed transactions
- Verify phone numbers are in correct format (+233...)
- Test with sandbox phone numbers first
- Ensure amounts are in smallest currency unit (pesewas)
- Contact FLUID support if error persists
Issue: Slow Transaction Processing
Symptoms: Transactions taking longer than expected
Solutions:
- Check your network latency to FLUID API
- Verify you're not hitting rate limits
- Reduce polling frequency (rely on webhooks)
- Implement connection pooling
- Use async/parallel processing where possible
Next Steps
Now that you've completed the integration:
- Read the API Reference - Deep dive into all available endpoints
- Implement Error Handling - Learn about all error codes and how to handle them
- Configure Rate Limiting - Optimize your API usage
- Set Up Idempotency - Prevent duplicate transactions
- Join the Community - Connect with other developers
Resources
- API Reference
- Error Handling Guide
- Rate Limiting Guide
- Idempotency Guide
- Webhook Reference
- Security Best Practices
Support
Need help with your integration?
- Email: developers@fluidnetwork.africa
- Slack: Join our community
- Documentation: https://fluidnetwork.africa/docs