Documentation

Everything you need to integrate, use, and get the most out of MOMO LENS.

Third-Party Integration

API Keys for Third-Party Integrations

Secure, long-lived authentication for server-to-server integrations, webhooks, and third-party applications. API keys provide programmatic access without requiring user authentication.

When to Use API Keys

Use API Keys For

  • • Server-to-server integrations
  • • Third-party applications
  • • Automated systems and scripts
  • • Webhook endpoints (future)
  • • Long-lived integrations
  • • Background jobs and scheduled tasks

Use JWT Tokens For

  • • Mobile applications (Android/iOS)
  • • Web applications with user sessions
  • • User-initiated actions
  • • Short-lived sessions (24 hours)
  • • Interactive applications

Getting Started

1

Create an API Key

First, you need to authenticate with your MOMO LENS account using JWT to create an API key. This is a one-time setup process.

POST /api/v1/api-keys
Authorization: Bearer <your-jwt-token>
Content-Type: application/json

{
  "name": "Production Integration Key",
  "expiresAt": "2025-12-31T23:59:59Z",
  "allowedOrigins": ["https://your-app.com"],
  "rateLimit": 1000
}

Important: Store Your Key Securely

The full API key is only returned once during creation. Make sure to store it securely immediately - you won't be able to retrieve it again!

2

Use Your API Key

Once you have your API key, you can use it to authenticate API requests. API keys can be sent in two ways:

Option 1: X-API-Key Header (Recommended)

curl -X GET https://momolens-production.up.railway.app/api/v1/merchants/{merchantId}/sales-records \
  -H "X-API-Key: ml_live_abc12345def67890..."

Option 2: Authorization Bearer Header

curl -X GET https://momolens-production.up.railway.app/api/v1/merchants/{merchantId}/sales-records \
  -H "Authorization: Bearer ml_live_abc12345def67890..."
3

Make API Calls

Your API key works just like a JWT token - you can use it to access all the same endpoints. The API key automatically identifies your merchant account.

# Example: Fetch sales records
curl -X GET \
  https://momolens-production.up.railway.app/api/v1/merchants/{merchantId}/sales-records \
  -H "X-API-Key: ml_live_abc12345def67890..." \
  -H "Content-Type: application/json"

# Example: Create a transaction
curl -X POST \
  https://momolens-production.up.railway.app/api/v1/transactions \
  -H "X-API-Key: ml_live_abc12345def67890..." \
  -H "Content-Type: application/json" \
  -d '{
    "amount": 100.00,
    "currency": "ZMW",
    "provider": "MTN_MOMO"
  }'

Managing Your API Keys

List All Keys

GET /api/v1/api-keys
Authorization: Bearer <jwt-token>

Returns all API keys for your merchant account. The full key is never returned - only the prefix for identification.

Update a Key

PUT /api/v1/api-keys/:id
Authorization: Bearer <jwt-token>
Content-Type: application/json

{
  "name": "Updated Name",
  "status": "INACTIVE",
  "allowedOrigins": ["https://new-domain.com"]
}

Update key name, status, allowed origins, rate limits, or expiration date.

Revoke a Key

DELETE /api/v1/api-keys/:id
Authorization: Bearer <jwt-token>

Immediately revokes an API key. The key will stop working for all future requests.

Key Status

ACTIVE - Key is active and can be used
INACTIVE - Key is temporarily disabled
REVOKED - Key has been revoked
EXPIRED - Key has passed its expiration date

Security Features

Key Hashing

API keys are hashed using SHA-256 before storage. Plain text keys are never stored in the database.

Status Management

Keys can be activated, deactivated, or revoked at any time. Expired keys are automatically disabled.

CORS Origins

Restrict which domains can use your API key. Perfect for web applications with specific domains.

Rate Limiting

Set custom rate limits per API key to prevent abuse and control usage.

Expiration Dates

Set expiration dates for keys. Keys automatically expire and stop working after the date.

Last Used Tracking

Monitor when keys were last used to identify unused or potentially compromised keys.

CORS Configuration

When using API keys from web applications, you can restrict which origins (domains) are allowed to use the key.

No Restrictions (Default)

{
  "name": "Unrestricted Key",
  "allowedOrigins": []
}

If allowedOrigins is empty, the key can be used from any origin (subject to global CORS settings).

Restricted to Specific Domains

{
  "name": "Production Web App Key",
  "allowedOrigins": [
    "https://app.example.com",
    "https://www.example.com"
  ]
}

Only requests from the specified origins will be allowed. All other origins will be rejected by CORS.

Code Examples

JavaScript/TypeScript

const API_KEY = process.env.MOMO_LENS_API_KEY;
const BASE_URL = 'https://momolens-production.up.railway.app/api/v1';

async function fetchSalesRecords(merchantId) {
  const response = await fetch(
    `${BASE_URL}/merchants/${merchantId}/sales-records`,
    {
      headers: {
        'X-API-Key': API_KEY,
        'Content-Type': 'application/json',
      },
    }
  );
  
  if (!response.ok) {
    throw new Error(`API Error: ${response.statusText}`);
  }
  
  return response.json();
}

Python

import os
import requests

API_KEY = os.getenv('MOMO_LENS_API_KEY')
BASE_URL = 'https://momolens-production.up.railway.app/api/v1'

def fetch_sales_records(merchant_id):
    response = requests.get(
        f'{BASE_URL}/merchants/{merchant_id}/sales-records',
        headers={
            'X-API-Key': API_KEY,
            'Content-Type': 'application/json',
        }
    )
    response.raise_for_status()
    return response.json()

PHP

<?php
$apiKey = getenv('MOMO_LENS_API_KEY');
$baseUrl = 'https://momolens-production.up.railway.app/api/v1';

function fetchSalesRecords($merchantId) {
    global $apiKey, $baseUrl;
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "$baseUrl/merchants/$merchantId/sales-records");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "X-API-Key: $apiKey",
        "Content-Type: application/json"
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}
?>

Security Best Practices

Never Commit Keys to Version Control

Always use environment variables or secure key management systems. Never hardcode API keys in your source code.

Store Keys Securely

Use environment variables, secret managers (AWS Secrets Manager, HashiCorp Vault), or secure configuration files.

Rotate Keys Regularly

Regularly rotate API keys, especially if you suspect they may have been compromised. Create new keys and revoke old ones.

Set Expiration Dates

Always set expiration dates for production keys. This ensures keys don't remain active indefinitely.

Restrict Origins

Use allowedOrigins to restrict which domains can use your API key. This prevents unauthorized usage.

Monitor Usage

Regularly check the lastUsedAt timestamp to identify unused keys or detect suspicious activity.

Use Different Keys for Different Environments

Use separate API keys for development, staging, and production environments.

Revoke Compromised Keys Immediately

If you suspect a key has been compromised, revoke it immediately and create a new one.

Rate Limiting

Each API key can have a custom rate limit (requests per minute). If not set, the global rate limit applies.

{
  "name": "High Volume Integration",
  "rateLimit": 1000  // 1000 requests per minute
}

Default Rate Limit: If no custom rate limit is set, the global rate limit of 100 requests per 15 minutes applies.

Troubleshooting

"Invalid API key" Error

  • Verify the API key is correct (no extra spaces or characters)
  • Check that the key status is ACTIVE
  • Ensure the key hasn't expired
  • Verify the merchant account is active

CORS Errors

  • Check that your origin is in the allowedOrigins list
  • Verify the origin matches exactly (including protocol and port)
  • If allowedOrigins is empty, check global CORS settings

Rate Limit Exceeded

  • Check your API key's rateLimit setting
  • Implement exponential backoff in your application
  • Consider requesting a higher rate limit if needed