Understanding the structure of Notch Pay API responses is essential for properly integrating with our API. This guide explains the standard response format, common fields, and how to interpret different types of responses.

Standard Response Format

All Notch Pay API responses follow a consistent JSON format:

{
  "code": 200,
  "status": "OK",
  "message": "Descriptive message about the response",
  "data": {
    / Response data specific to the endpoint
  }
}

Response Properties

PropertyTypeDescription
codenumberHTTP status code indicating the result of the request
statusstringText representation of the HTTP status code
messagestringHuman-readable description of the response
dataobject/arrayThe main response data (varies by endpoint)

Success Responses

Single Resource Response

When retrieving a single resource (like a payment or customer), the response typically looks like this:

{
  "code": 200,
  "status": "OK",
  "message": "Payment retrieved",
  "data": {
    "id": "pay_123456789",
    "reference": "order_123",
    "amount": 5000,
    "currency": "XAF",
    "status": "complete",
    "customer": "cus_123456789",
    "created_at": "2023-01-01T12:00:00Z"
  }
}

Collection Response

When retrieving a collection of resources (like a list of payments), the response includes pagination information:

{
  "code": 200,
  "status": "OK",
  "message": "Payments retrieved",
  "totals": 50,
  "last_page": 2,
  "current_page": 1,
  "selected": 30,
  "items": [
    {
      "id": "pay_123456789",
      "reference": "order_123",
      "amount": 5000,
      "currency": "XAF",
      "status": "complete"
    },
    / More items...
  ]
}

Pagination Properties

PropertyTypeDescription
totalsnumberTotal number of items across all pages
last_pagenumberNumber of the last page
current_pagenumberNumber of the current page
selectednumberNumber of items on the current page
itemsarrayArray of items on the current page

Creation Response

When creating a new resource, the response typically includes the created resource and a 201 status code:

{
  "code": 201,
  "status": "Created",
  "message": "Payment created",
  "data": {
    "id": "pay_123456789",
    "reference": "order_123",
    "amount": 5000,
    "currency": "XAF",
    "status": "pending",
    "created_at": "2023-01-01T12:00:00Z",
    "authorization_url": "https://pay.notchpay.co/pay_123456789"
  }
}

Update Response

When updating a resource, the response typically includes the updated resource:

{
  "code": 200,
  "status": "OK",
  "message": "Customer updated",
  "data": {
    "id": "cus_123456789",
    "name": "John Doe",
    "email": "john@example.com",
    "phone": "+237600000000",
    "updated_at": "2023-01-01T12:00:00Z"
  }
}

Deletion Response

When deleting a resource, the response typically confirms the deletion:

{
  "code": 200,
  "status": "OK",
  "message": "Customer deleted"
}

Error Responses

When an error occurs, the response includes information about what went wrong:

{
  "code": 400,
  "status": "Bad Request",
  "message": "Error message describing what went wrong",
  "errors": {
    "field_name": ["Error description for this field"]
  }
}

For more information about error responses, see the Error Handling guide.

Response Formats for Specific Endpoints

Payments API

Create Payment

{
  "code": 201,
  "status": "Created",
  "message": "Payment initialized",
  "data": {
    "id": "pay_123456789",
    "reference": "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"
  }
}

Retrieve Payment

{
  "code": 200,
  "status": "OK",
  "message": "Payment retrieved",
  "data": {
    "id": "pay_123456789",
    "reference": "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"
  }
}

Transfers API

Create Transfer

{
  "code": 201,
  "status": "Created",
  "message": "Transfer initiated",
  "data": {
    "id": "trf_123456789",
    "reference": "salary_jan_2023",
    "amount": 5000,
    "currency": "XAF",
    "status": "pending",
    "beneficiary": "ben_123456789",
    "channel": "cm.mtn",
    "description": "Salary payment",
    "created_at": "2023-01-01T12:00:00Z"
  }
}

Customers API

Create Customer

{
  "code": 201,
  "status": "Created",
  "message": "Customer created",
  "data": {
    "id": "cus_123456789",
    "name": "John Doe",
    "email": "john@example.com",
    "phone": "+237600000000",
    "created_at": "2023-01-01T12:00:00Z"
  }
}

Response Fields

Common Fields

These fields appear in most resource objects:

FieldTypeDescription
idstringUnique identifier for the resource
created_atstringISO 8601 timestamp when the resource was created
updated_atstringISO 8601 timestamp when the resource was last updated

Timestamps

All timestamps in Notch Pay API responses are in ISO 8601 format with UTC timezone:

YYYY-MM-DDTHH:MM:SSZ

Example: 2023-01-01T12:00:00Z

Handling Responses in Different Programming Languages

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: {
      email: 'customer@example.com'
    }
  })
})
.then(response => response.json())
.then(data => {
  if (data.code >= 200 && data.code < 300) {
    / Success
    console.log('Success:', data.message);
    console.log('Payment ID:', data.data.id);
    console.log('Authorization URL:', data.data.authorization_url);
  } else {
    / Error
    console.error('Error:', data.message);
    if (data.errors) {
      console.error('Validation errors:', data.errors);
    }
  }
})
.catch(error => {
  console.error('Request failed:', error);
});

PHP

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.notchpay.co/payments');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'amount' => 5000,
    'currency' => 'XAF',
    'customer' => [
        'email' => 'customer@example.com'
    ]
]));

$headers = [
    'Authorization: YOUR_PUBLIC_KEY',
    'Content-Type: application/json'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

if ($data['code'] >= 200 && $data['code'] < 300) {
    / Success
    echo "Success: " . $data['message'] . "\n";
    echo "Payment ID: " . $data['data']['id'] . "\n";
    echo "Authorization URL: " . $data['data']['authorization_url'] . "\n";
} else {
    / Error
    echo "Error: " . $data['message'] . "\n";
    if (isset($data['errors'])) {
        echo "Validation errors:\n";
        foreach ($data['errors'] as $field => $errors) {
            echo "- $field: " . implode(', ', $errors) . "\n";
        }
    }
}

Python

import requests
import json

url = "https://api.notchpay.co/payments"
payload = {
    "amount": 5000,
    "currency": "XAF",
    "customer": {
        "email": "customer@example.com"
    }
}
headers = {
    "Authorization": "YOUR_PUBLIC_KEY",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()

if 200 <= data['code'] < 300:
    # Success
    print("Success:", data['message'])
    print("Payment ID:", data['data']['id'])
    print("Authorization URL:", data['data']['authorization_url'])
else:
    # Error
    print("Error:", data['message'])
    if 'errors' in data:
        print("Validation errors:")
        for field, errors in data['errors'].items():
            print(f"- {field}: {', '.join(errors)}")

Best Practices

  1. Check the Status Code: Always check the code field to determine if the request was successful.

  2. Handle Pagination: When working with collection endpoints, implement pagination to retrieve all results.

/ Example of handling pagination in JavaScript
async function getAllPayments() {
  let page = 1;
  let allPayments = [];
  let hasMorePages = true;
  
  while (hasMorePages) {
    const response = await fetch(`https://api.notchpay.co/payments?page=${page}`, {
      headers: {
        'Authorization': 'YOUR_PUBLIC_KEY'
      }
    });
    
    const data = await response.json();
    
    if (data.code === 200) {
      allPayments = allPayments.concat(data.items);
      
      if (data.current_page < data.last_page) {
        page++;
      } else {
        hasMorePages = false;
      }
    } else {
      throw new Error(data.message);
    }
  }
  
  return allPayments;
}
  1. Parse Timestamps: Convert timestamp strings to Date objects for easier manipulation.
const createdAt = new Date(payment.created_at);
console.log('Payment created on:', createdAt.toLocaleDateString());
  1. Handle Empty Collections: When retrieving collections, check if the items array is empty.
if (data.items.length === 0) {
  console.log('No payments found.');
} else {
  console.log(`Found ${data.totals} payments.`);
}
  1. Extract Relevant Data: Only extract the data you need from the response to simplify your code.
const { id, amount, currency, status } = data.data;
console.log(`Payment ${id}: ${amount} ${currency} (${status})`);

Next Steps