Skip to content

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/v1 as base URL
  • Production: Use https://api.fluid-network.com/api/v1 as 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/json header
  • 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:

  1. Initiate Transaction: Call the debit initiation endpoint with transaction details
  2. Store Transaction ID: Save the returned transaction_id for status tracking
  3. Poll for Status (optional): Query transaction status periodically if webhook not received
  4. 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, or cancelled
  • Always rely on webhooks as primary status update mechanism

3.2 Test Different Scenarios

Use sandbox test phone numbers to simulate different outcomes:

Phone NumberBehaviorUse Case
+233241234567Auto-success after 5 secondsHappy path testing
+233241111111Auto-fail (insufficient funds)Error handling
+233242222222Auto-fail (invalid account)Validation errors
+233243333333Timeout (no response)Timeout handling
+233244444444Requires manual approvalPending 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-Signature header
  • 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:

  1. Verify Signature: Validate request authenticity using webhook secret
  2. Check Idempotency: Prevent duplicate processing using event_id
  3. Store Event: Log webhook event for audit trail
  4. Handle Event Type: Process based on event type (transaction.completed, transaction.failed, etc.)
  5. Update Database: Update transaction status in your system
  6. Trigger Actions: Send emails, fulfill orders, etc.

Event Handlers:

  • transaction.completed: Payment successful - fulfill order, credit account, send confirmation
  • transaction.failed: Payment failed - update status, notify customer, log for review
  • transaction.pending: Payment awaiting approval - update UI, set timeout for fallback polling

Signature Verification Process:

  1. Extract raw request body (before parsing)
  2. Extract signature from X-Fluid-Signature header
  3. Compute HMAC-SHA256 using webhook secret and raw body
  4. Compare computed signature with provided signature using constant-time comparison

4.2 Expose Webhook Endpoint

For local testing, use a tunneling service:

bash
# 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:

bash
# 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 logs

Stage 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_reference for each transaction
    • ✅ Implement deduplication for webhook events
    • ✅ Handle retry scenarios gracefully
  • 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:

bash
# 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 works

5.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:

MetricTargetAlert 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:

  1. Create Order: Save order in your database with pending_payment status
  2. Initiate Transaction: Call FLUID debit endpoint with order details
  3. Store Transaction ID: Link FLUID transaction ID to your order record
  4. Update Status: Change order status to awaiting_payment
  5. 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_reference for 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:

  1. Schedule Recurring Charge: Use cron job or scheduled task to charge subscriptions
  2. Check Existing Charge: Prevent duplicate charges by checking if current period already charged
  3. Generate Idempotency Key: Use subscription ID + billing period as partner_reference
  4. Initiate Charge: Call FLUID debit endpoint
  5. 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:

  1. Validate Transfer: Check sender balance, verify recipient exists, validate amount
  2. Create Transfer Record: Store transfer in database with initiated status
  3. Charge Sender: Initiate FLUID debit transaction from sender's phone
  4. Link Transaction: Store FLUID transaction ID with transfer record
  5. 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:

  1. Verify webhook URL is publicly accessible (use webhook.site to test)
  2. Check webhook endpoint returns 2xx status within 5 seconds
  3. Verify SSL certificate is valid
  4. Check firewall/security group rules
  5. Review webhook delivery logs in FLUID dashboard

Issue: Signature Verification Fails

Symptoms: Invalid signature errors on webhook endpoint

Solutions:

  1. Verify you're using raw request body (not parsed JSON)
  2. Check you're using correct webhook secret for environment
  3. Ensure no middleware is modifying request body
  4. Verify HMAC algorithm is SHA-256
  5. Use constant-time comparison for signatures

Issue: High Transaction Failure Rate

Symptoms: Many transactions failing with same error

Solutions:

  1. Check error codes and messages in failed transactions
  2. Verify phone numbers are in correct format (+233...)
  3. Test with sandbox phone numbers first
  4. Ensure amounts are in smallest currency unit (pesewas)
  5. Contact FLUID support if error persists

Issue: Slow Transaction Processing

Symptoms: Transactions taking longer than expected

Solutions:

  1. Check your network latency to FLUID API
  2. Verify you're not hitting rate limits
  3. Reduce polling frequency (rely on webhooks)
  4. Implement connection pooling
  5. Use async/parallel processing where possible

Next Steps

Now that you've completed the integration:

  1. Read the API Reference - Deep dive into all available endpoints
  2. Implement Error Handling - Learn about all error codes and how to handle them
  3. Configure Rate Limiting - Optimize your API usage
  4. Set Up Idempotency - Prevent duplicate transactions
  5. Join the Community - Connect with other developers

Resources

Support

Need help with your integration?