Notch Pay’s Directe Charge allows you to build a custom payment experience directly into your application. With our RESTful API, you have complete control over the payment flow while still benefiting from Notch Pay’s secure payment processing.

Overview

The API integration gives you:

  • Complete control over the payment flow
  • Seamless integration with your existing systems
  • Support for all payment methods
  • Webhook notifications for payment events
  • Detailed transaction data

When to Use API Integration

  • You need a fully customized payment experience
  • You want to integrate payments into your existing application
  • You need to implement complex payment flows
  • You want to build a custom payment form

Alternatives

  • Collect: For a quick integration with minimal coding
  • Payment Links: For sharing payment links without coding
  • Invoices: For creating and managing invoices

Authentication

All API requests must include your API key in the Authorization header:

Authorization: YOUR_PUBLIC_KEY

You can find your API keys in your Notch Pay Business suite under Settings > API Keys. Make sure to use your test API key for development and your live API key for production.

Basic Payment Flow

The basic payment flow with the Notch Pay API consists of three main steps:

  1. Initialize a Payment: Create a payment with customer and transaction details
  2. Process the Payment: Process the payment with the customer’s chosen payment method
  3. Verify the Payment: Check the payment status to confirm completion

1. Initialize a Payment

To initialize a payment, make a POST request to the /payments endpoint:

// Using fetch in JavaScript
fetch('https://api.notchpay.co/payments', {
  method: 'POST',
  headers: {
    'Authorization': 'YOUR_PUBLIC_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    amount: 5000,
    currency: 'XAF',
    customer: {
      name: 'John Doe',
      email: 'john@example.com',
      phone: '+237600000000'
    },
    description: 'Payment for Order #123',
    reference: 'order_123',
    callback: 'https://your-website.com/callback'
  })
})
.then(response => response.json())
.then(data => {
  console.log(data);
  // Store the payment reference for the next step
  const paymentReference = data.transaction.reference;
})

Response

{
  "status": "Accepted",
  "message": "Payment initialized",
  "code": 201,
  "transaction": {
    "id": "pay_123456789",
    "reference": "trx.123456789abcdefghj",
    "trxref": "order_123",
    "amount": 5000,
    "currency": "XAF",
    "status": "pending",
    "customer": "cus_123456789",
    "created_at": "2023-01-01T12:00:00Z"
  },
  "authorization_url": "https://pay.notchpay.co/pay_123456789"
}

2. Process the Payment

You have two options for processing the payment:

Option 1: Redirect to Checkout

Redirect the customer to the authorization_url from the response:

window.location.href = data.authorization_url;

This will take the customer to the Notch Pay Checkout page where they can select a payment method and complete the payment.

Option 2: Direct API Processing

Process the payment directly through the API with the customer’s chosen payment method:

/ Example for MTN Mobile Money
fetch(`https://api.notchpay.co/payments/${paymentReference}`, {
  method: 'POST',
  headers: {
    'Authorization': 'YOUR_PUBLIC_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    channel: 'cm.mtn',
    data: {
      phone: '+237680000000'
    }
  })
})
.then(response => response.json())
.then(data => {
  console.log(data);
  // Payment is now processing
  // The customer will receive a prompt on their phone
})

Response

{
  "status": "Accepted",
  "message": "Payment processing initiated",
  "code": 202,
  "transaction": {
    "reference": "trx.123456789abcdefghj",
    "trxref": "order_123",
    "status": "processing"
  }
}

3. Verify the Payment

After processing the payment, you should verify its status:

fetch(`https://api.notchpay.co/payments/${paymentReference}`, {
  headers: {
    'Authorization': 'YOUR_PUBLIC_KEY'
  }
})
.then(response => response.json())
.then(data => {
  console.log(data);
  if (data.transaction.status === 'complete') {
    // Payment successful, update your database and show success page
  } else if (data.transaction.status === 'failed') {
    // Payment failed, show error message
  } else {
    // Payment still processing, show pending message
  }
})

Response

{
  "status": "Accepted",
  "message": "Transaction retrieved",
  "code": 202,
  "transaction": {
    "reference": "trx.123456789abcdefghj",
    "trxref": "order_123",
    "amount": 5000,
    "currency": "XAF",
    "status": "complete",
    "customer": "cus_123456789",
    "payment_method": "pm.ndzAfIh555VCPML1",
    "created_at": "2023-01-01T12:00:00Z",
    "completed_at": "2023-01-01T12:05:00Z"
  }
}

Payment Methods

Notch Pay supports various payment methods, each with its own processing requirements:

Mobile Money

For Mobile Money payments, you need to specify the channel and phone number:

{
  "channel": "cm.mtn", // or "cm.orange", etc.
  "data": {
    "account_number": "+237680000000"
  }
}

Digital Wallets

For digital wallet payments, you need to specify the wallet provider:

{
  "channel": "assoh", // or other wallet providers
  "data": {
    "account_number": "+237680000000" // Customer's wallet phone number
  }
}

Handling Callbacks

When a customer completes a payment, they will be redirected to your callback URL with the payment reference:

https://your-website.com/callback?reference=trx.123456789abcdefghj&trxref=order_123&status=canceled

Your callback handler should:

  1. Extract the reference from the URL parameters
  2. Verify the payment status by calling the API
  3. Update your database and show the appropriate page to the customer

Example callback handler in Node.js (Express):

app.get('/callback', async (req, res) => {
  const { reference } = req.query;
  
  try {
    const response = await fetch(`https://api.notchpay.co/payments/${reference}`, {
      headers: {
        'Authorization': process.env.NOTCHPAY_API_KEY
      }
    });
    
    const data = await response.json();
    
    if (data.transaction.status === 'complete') {
      // Payment successful
      // Update your database
      // Show success page
      res.redirect('/success');
    } else if (data.transaction.status === 'failed') {
      // Payment failed
      // Show error page
      res.redirect('/failed');
    } else {
     // Payment still processing
      // Show pending page
      res.redirect('/pending');
    }
  } catch (error) {
    console.error('Error verifying payment:', error);
    res.redirect('/error');
  }
});

Implementing Webhooks

Webhooks provide a more reliable way to receive payment notifications, especially for asynchronous payment methods like Mobile Money.

1. Set Up a Webhook Endpoint

Create an endpoint in your application to receive webhook notifications:

// Example in Node.js (Express)
app.post('/webhooks/notchpay', express.json(), (req, res) => {
  const event = req.body;
  
  // Verify webhook signature (recommended)
  const signature = req.headers['x-notch-signature'];
  if (!verifySignature(event, signature)) {
    return res.status(400).send('Invalid signature');
  }
  
  / Handle different event types
  switch (event.type) {
    case 'payment.complete':
      // Payment was successful
      // Update your database
      break;
    case 'payment.failed':
      // Payment failed
      // Update your database
      break;
    default:
      // Unhandled event type
      console.log(`Unhandled event type: ${event.type}`);
  }
  
  / Acknowledge receipt of the webhook
  res.status(200).send('Webhook received');
});

function verifySignature(payload, signature) {
  // Implement signature verification
  // See the Webhooks documentation for details
  return true; // Placeholder
}

2. Register Your Webhook

Register your webhook endpoint in your Notch Pay dashboard:

  1. Go to Settings > Webhooks
  2. Click “Add Endpoint”
  3. Enter your endpoint URL (e.g., https://your-website.com/webhooks/notchpay)
  4. Select the events you want to receive (e.g., payment.complete, payment.failed)
  5. Click “Save”

Error Handling

The Notch Pay API returns standard HTTP status codes and detailed error messages:

{
  "code": 400,
  "status": "Bad Request",
  "message": "Invalid parameters",
  "errors": {
    "amount": ["Amount is required"],
    "currency": ["Currency is invalid"]
  }
}

Implement proper error handling in your integration:

fetch('https://api.notchpay.co/payments', {
  method: 'POST',
  headers: {
    'Authorization': 'YOUR_PUBLIC_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    // Payment details
  })
})
.then(response => {
  if (!response.ok) {
    return response.json().then(error => {
      throw new Error(error.message || 'An error occurred');
    });
  }
  return response.json();
})
.then(data => {
  // Handle successful response
})
.catch(error => {
  console.error('Error:', error);
  // Show error message to the user
});

Testing

Before going live, thoroughly test your integration in the sandbox environment:

  1. Use your test API key
  2. Use test payment methods to simulate different scenarios
  3. Verify that your callback handling and webhook processing work correctly
  4. Test error scenarios to ensure your application handles them gracefully

Going Live

When you’re ready to go live:

  1. Switch to your live API key
  2. Update your webhook endpoints to production URLs
  3. Make a test payment in production to verify everything works correctly
  4. Monitor your first few live transactions closely

Using Metadata

Metadata allows you to attach custom data to payments, which can be useful for tracking and reconciliation purposes.

Adding Metadata to Payments

When creating a payment, you can include a metadata object with any key-value pairs you want to associate with the payment:

fetch('https://api.notchpay.co/payments', {
  method: 'POST',
  headers: {
    'Authorization': 'YOUR_PUBLIC_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    amount: 5000,
    currency: 'XAF',
    customer: {
      name: 'John Doe',
      email: 'john@example.com'
    },
    description: 'Payment for Order #123',
    reference: 'order_123',
    metadata: {
      order_id: '12345',
      product_ids: ['p-001', 'p-002'],
      customer_id: 'cus_9876',
      shipping_method: 'express',
      source: 'mobile_app'
    }
  })
})

Retrieving Metadata

When you retrieve a payment, the metadata will be included in the response:

fetch('https://api.notchpay.co/payments/order_123', {
  headers: {
    'Authorization': 'YOUR_PUBLIC_KEY'
  }
})
.then(response => response.json())
.then(data => {
  const metadata = data.transaction.metadata;
  console.log(metadata.order_id); // '12345'
  console.log(metadata.product_ids); // ['p-001', 'p-002']
})

Metadata Best Practices

  1. Keep it Relevant: Only include data that’s useful for your business processes
  2. Avoid Sensitive Data: Never store sensitive customer information in metadata
  3. Size Limitations: Keep metadata concise as there may be size limitations
  4. Consistent Structure: Use a consistent structure for your metadata across transactions
  5. Searchable Keys: Use keys that make sense for searching and filtering transactions later

Best Practices

  1. Secure Your API Key: Never expose your API key in client-side code
  2. Validate Input: Validate all input parameters before sending them to the API
  3. Handle Errors Gracefully: Implement proper error handling for a better user experience
  4. Use Webhooks: Set up webhooks for reliable payment notifications
  5. Log Transactions: Keep detailed logs of all transactions for troubleshooting
  6. Utilize Metadata: Use metadata to link payments to your internal systems

API Reference

For detailed API documentation, see the Payments API Reference.