Codian Logo
CODIAN API DOCUMENTATION
Codian → APIs → Payments | Chatbots | Emails | SMS | Airtime

Overview

The Codian API suite enables developers to integrate payments, chatbots, emails, SMS, and airtime services into their applications. All APIs use JSON payloads and are compatible with any programming language that supports HTTP requests, such as Python, JavaScript, PHP, Ruby, or Go.

API Services

  • Payments API: Facilitates M-Pesa payments through managed or custom integration methods.
  • Chatbots API: Enables the creation of conversational bots for user engagement and task automation.
  • Emails API: Supports sending transactional or bulk emails with customizable templates.
  • SMS API: Allows sending SMS notifications or campaigns.
  • Airtime API: Facilitates mobile airtime top-ups across supported networks.

Getting Started

Create a Codian Account

To begin, create a developer account at codian.co.ke/accounts/signup.php. After signing up, log in to your dashboard to create an app and obtain your client_id and client_secret.

Dashboard Manuals

Refer to the following manuals for navigating Codian’s dashboards:

Prerequisites

  • A Codian developer account with API credentials (Client ID & Secret).
  • An HTTPS-enabled website for production (localhost is acceptable for testing).
  • A webhook endpoint configured in the Codian dashboard to receive real-time updates (must return HTTP 200).
  • Basic knowledge of HTTP requests (POST, JSON, etc.) in your preferred programming language.

Step 1: Obtain Credentials

Log in to your Codian dashboard, create an app, and retrieve your client_id and client_secret.

Client ID: codian_prd_XXXXXXXXXX
Client Secret: codian_sk_prd_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Step 2: Secure Credentials

Store your credentials securely:

  • Hardcoded: Suitable for quick development testing but not recommended for production.
  • Environment Variables: Recommended for secure storage in production environments.

Payments API: Managed Integration

Payment Integration Methods

Codian offers two methods for integrating payments:

  • Managed Integration: Codian handles the payment flow, including forms, STK Push, and redirects. Ideal for quick and low-code setups.
  • Custom Integration: Developers build their own payment forms and handle callbacks, offering full control over the user experience.

Codian supports both online and offline payment methods. Online payments are processed via M-Pesa STK Push, while offline payments can be made with Codian Concepts Paybill number 3554651 then using a 6 Digit Unique Account Number provided by Codian, in your dashboard. Transaction updates for both methods are sent to your webhook endpoint, ensuring flexibility across devices and payment scenarios. In both methods, the funds collect to your wallet

Overview

The Managed Integration simplifies the payment process by handling the entire flow, including form rendering and redirects. Developers provide a JSON payload with transaction details and redirect URLs.

Endpoint URLs

  • Sandbox: https://codian.co.ke/session/checkout/process.php
  • Production: https://codian.co.ke/session/checkout/process.php

Payload Structure

Send a JSON payload to the appropriate endpoint. The payload is compatible with any language supporting HTTP POST requests.

Field Type Description Example
client_id string Your Codian Client ID codian_prd_0wGSy66bZu
client_secret string Your Codian Client Secret codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD
amount number Amount in KES (min 1) 100.00
transaction_desc text Transaction description Order #123
success_url string Redirect URL on success https://yourapp.com/success
failure_url string Redirect URL on failure https://yourapp.com/failure
amount_readonly boolean (0/1) Make amount field read-only (optional) 1
transaction_desc_readonly boolean (0/1) Make description read-only (optional) 0
{
    "client_id": "codian_prd_0wGSy66bZu",
    "client_secret": "codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD",
    "amount": 100.00,
    "transaction_desc": "Order #123",
    "success_url": "https://yourapp.com/success",
    "failure_url": "https://yourapp.com/failure",
    "amount_readonly": 1,
    "transaction_desc_readonly": 0
}

Integration Example

Send the payload to initiate a payment. Codian handles the payment form and redirects.

const payload = {
    client_id: 'codian_prd_0wGSy66bZu',
    client_secret: 'codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD',
    amount: 100.00,
    transaction_desc: 'Order #123',
    success_url: 'https://yourapp.com/success',
    failure_url: 'https://yourapp.com/failure',
    amount_readonly: 1
};

fetch('https://codian.co.ke/session/checkout/process.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
})
.then(response => response.json())
.then(data => {
    if (data.success) {
        window.location.href = data.redirect_url;
    } else {
        console.error('Error:', data.error);
    }
})
.catch(error => console.error('Error:', error));
Note: Customize the checkout page template in your Codian dashboard.

Payments API: Custom Integration

Overview

The Custom Integration allows developers to create their own payment forms and handle callbacks. Initiate M-Pesa STK Push and receive transaction updates via a webhook configured in the Codian dashboard.

Endpoint URLs

  • Sandbox: https://sandbox.codian.co.ke/v1/payments/c2b/initiate.php
  • Production: https://api.codian.co.ke/v1/payments/c2b/initiate.php

Payload Structure

Send a JSON payload to the appropriate endpoint.

Field Type Description Example
client_id string Your Codian Client ID codian_prd_0wGSy66bZu
client_secret string Your Codian Client Secret codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD
amount number Amount in KES (min 1) 100.00
phone string M-Pesa registered phone (e.g., 2547XXXXXXXX) 254794335725
{
    "client_id": "codian_prd_0wGSy66bZu",
    "client_secret": "codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD",
    "amount": 100.00,
    "phone": "254794335725"
}

Integration Example

Build a custom form and send the payload to initiate an STK Push.

<?php
$payload = [
    "client_id" => "codian_prd_0wGSy66bZu",
    "client_secret" => "codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD",
    "amount" => 100.00,
    "phone" => "254794335725"
];

$ch = curl_init('https://api.codian.co.ke/v1/payments/c2b/initiate.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($response && $http_code === 200) {
    $data = json_decode($response, true);
    if ($data['success']) {
        echo "STK Push initiated, waiting for user PIN...";
    } else {
        echo "Error: " . $data['error'];
    }
} else {
    echo "Request failed: HTTP $http_code";
}
?>
Note: The user receives an M-Pesa STK Push prompt. Transaction updates are sent to the webhook endpoint configured in the Codian dashboard.

Payments API: Webhooks

Webhook Setup

Configure your webhook endpoint in the Codian dashboard under the Webhooks tab. Specify the URL (e.g., https://yourapp.com/callback) and select events such as completed, failed, or timeout. The endpoint must return HTTP 200 to confirm receipt.

Note: Test your webhook in the sandbox environment to verify payload handling.

Webhook Payloads

Codian sends two types of callbacks: STK Push and C2B Confirmation. Both are JSON payloads.

STK Push Callback

Sent when the M-Pesa STK Push is processed.

{
    "Body": {
        "stkCallback": {
            "MerchantRequestID": "52fa-4e92-bebd-51f12cb786f3256",
            "CheckoutRequestID": "ws_CO_18102025233012373794335725",
            "ResultCode": 0,
            "ResultDesc": "The service request is processed successfully.",
            "CallbackMetadata": {
                "Amount": 1,
                "MpesaReceiptNumber": "TJIKQ7V33N",
                "TransactionDate": "2025-10-18 23:30:26",
                "PhoneNumber": 254794335725
            }
        }
    }
}

C2B Confirmation Callback

Sent to confirm transaction details after payment.

{
    "TransactionType": "Pay Bill",
    "TransID": "TJIKQ7V33N",
    "TransTime": "20251018233026",
    "TransAmount": "1.00",
    "BusinessShortCode": "3554651",
    "BillRefNumber": "TESTEEN EXAMS",
    "InvoiceNumber": "",
    "ThirdPartyTransID": "",
    "MSISDN": "4f263387a4a6de604e6c4500530b07e22cc76a1dfbb7b8ae62a96a3d5ad55784",
    "FirstName": "peter"
}
Note: Use MpesaReceiptNumber or TransID to correlate callbacks.

Payments API: Callbacks

Handling Callbacks

Process STK Push and C2B Confirmation payloads at your webhook endpoint. This PHP example logs callbacks for auditing.

<?php
header('Content-Type: application/json');
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

function logToResponseFile($message) {
    $logFile = __DIR__ . '/response.log';
    $timestamp = date('Y-m-d H:i:s');
    $formattedMessage = "[$timestamp] $message" . PHP_EOL;
    
    if (!is_writable($logFile) && !is_writable(dirname($logFile))) {
        error_log("[$timestamp] Failed to write to response.log: File or directory not writable");
        error_log("[$timestamp] Fallback log: $message");
        return false;
    }
    
    $result = file_put_contents($logFile, $formattedMessage, FILE_APPEND | LOCK_EX);
    if ($result === false) {
        error_log("[$timestamp] Failed to write to response.log: Write error");
        error_log("[$timestamp] Fallback log: $message");
    }
    return $result !== false;
}

logToResponseFile("Script reached: callback.php");
$raw_data = file_get_contents('php://input');
logToResponseFile("Raw input received: " . ($raw_data ?: 'Empty'));

$callback_data = json_decode($raw_data, true);
if ($callback_data === null) {
    $errorMsg = 'Invalid or malformed JSON data: ' . json_last_error_msg();
    logToResponseFile($errorMsg);
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $errorMsg]);
    exit;
}

if (empty($callback_data)) {
    $errorMsg = 'Empty callback data';
    logToResponseFile($errorMsg);
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $errorMsg]);
    exit;
}

$callback_type = 'Unknown';
$identifier = 'N/A';
if (isset($callback_data['Body']['stkCallback']['CheckoutRequestID'])) {
    $callback_type = 'STK Push';
    $identifier = $callback_data['Body']['stkCallback']['CheckoutRequestID'];
} elseif (isset($callback_data['TransID']) && isset($callback_data['BillRefNumber'])) {
    $callback_type = 'C2B Confirmation';
    $identifier = $callback_data['TransID'];
}

logToResponseFile("Callback Type: $callback_type, Identifier: $identifier, Payload: " . json_encode($callback_data, JSON_UNESCAPED_SLASHES));

if ($callback_type === 'C2B Confirmation') {
    echo json_encode(['ResultCode' => '0', 'ResultDesc' => 'Success']);
} else {
    echo json_encode(['success' => true, 'message' => 'Callback processed successfully']);
}
?>
Note: Use CheckoutRequestID or TransID to track transactions and update your application state.

Chatbots API: Overview

The Chatbots API enables developers to build conversational bots for user engagement and task automation. JSON payloads facilitate integration with any platform.

Chatbots API: Integration

Payload Structure

Send a JSON payload to https://codian.co.ke/api/chatbots/send.

Field Type Description Example
client_id string Your Codian Client ID codian_prd_0wGSy66bZu
client_secret string Your Codian Client Secret codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD
user_id string Unique user identifier user_123
message text User’s message to the bot Hi, what’s my order status?
{
    "client_id": "codian_prd_0wGSy66bZu",
    "client_secret": "codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD",
    "user_id": "user_123",
    "message": "Hi, what’s my order status?"
}

Integration Example

Send a message to the bot and receive responses via a webhook.

fetch('https://codian.co.ke/api/chatbots/send', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
        client_id: 'codian_prd_0wGSy66bZu',
        client_secret: 'codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD',
        user_id: 'user_123',
        message: 'Hi, what’s my order status?'
    })
})
.then(response => response.json())
.then(data => {
    if (data.success) {
        console.log('Message sent, awaiting bot response...');
    } else {
        console.error('Error:', data.error);
    }
})
.catch(error => console.error('Error:', error));

Chatbots API: Webhooks

Webhook Payload

Receive bot responses via your webhook endpoint configured in the Codian dashboard.

{
    "user_id": "user_123",
    "message_id": "msg_456",
    "response": "Your order #123 is shipped!",
    "timestamp": "2025-10-19 10:03:00"
}
Note: Use message_id to track conversation threads.

Emails API: Overview

The Emails API supports sending transactional or bulk emails with customizable templates. JSON payloads enable seamless integration.

Emails API: Integration

Payload Structure

Send a JSON payload to https://codian.co.ke/api/emails/send.

Field Type Description Example
client_id string Your Codian Client ID codian_prd_0wGSy66bZu
client_secret string Your Codian Client Secret codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD
recipient string Recipient email address user@example.com
subject text Email subject Your Order Confirmation
body text Email content (HTML or plain) <p>Thanks for your order!</p>
{
    "client_id": "codian_prd_0wGSy66bZu",
    "client_secret": "codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD",
    "recipient": "user@example.com",
    "subject": "Your Order Confirmation",
    "body": "<p>Thanks for your order!</p>"
}

Integration Example

Send an email using this JavaScript example.

fetch('https://codian.co.ke/api/emails/send', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
        client_id: 'codian_prd_0wGSy66bZu',
        client_secret: 'codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD',
        recipient: 'user@example.com',
        subject: 'Your Order Confirmation',
        body: '<p>Thanks for your order!</p>'
    })
})
.then(response => response.json())
.then(data => {
    if (data.success) {
        console.log('Email sent!');
    } else {
        console.error('Error:', data.error);
    }
})
.catch(error => console.error('Error:', error));

Emails API: Webhooks

Webhook Payload

Receive email delivery status via your webhook endpoint.

{
    "email_id": "email_789",
    "recipient": "user@example.com",
    "status": "delivered",
    "timestamp": "2025-10-19 10:03:00"
}

SMS API: Overview

The SMS API enables sending notifications or campaigns to users via SMS. JSON payloads ensure compatibility with any platform.

SMS API: Integration

Payload Structure

Send a JSON payload to https://codian.co.ke/api/sms/send.

Field Type Description Example
client_id string Your Codian Client ID codian_prd_0wGSy66bZu
client_secret string Your Codian Client Secret codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD
phone_number string Recipient phone (e.g., 2547XXXXXXXX) 254794335725
message text SMS content (max 160 chars) Your order #123 is shipped!
{
    "client_id": "codian_prd_0wGSy66bZu",
    "client_secret": "codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD",
    "phone_number": "254794335725",
    "message": "Your order #123 is shipped!"
}

Integration Example

Send an SMS using this Python example.

import requests

payload = {
    "client_id": "codian_prd_0wGSy66bZu",
    "client_secret": "codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD",
    "phone_number": "254794335725",
    "message": "Your order #123 is shipped!"
}

response = requests.post("https://codian.co.ke/api/sms/send", json=payload)
if response.status_code == 200:
    data = response.json()
    if data["success"]:
        print("SMS sent!")
    else:
        print("Error:", data["error"])
else:
    print("Request failed:", response.status_code)

SMS API: Webhooks

Webhook Payload

Receive SMS delivery status via your webhook endpoint.

{
    "sms_id": "sms_101",
    "phone_number": "254794335725",
    "status": "delivered",
    "timestamp": "2025-10-19 10:03:00"
}

Airtime API: Overview

The Airtime API enables mobile airtime top-ups for users across supported networks. JSON payloads ensure seamless integration.

Airtime API: Integration

Payload Structure

Send a JSON payload to https://codian.co.ke/api/airtime/send.

Field Type Description Example
client_id string Your Codian Client ID codian_prd_0wGSy66bZu
client_secret string Your Codian Client Secret codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD
phone_number string Recipient phone (e.g., 2547XXXXXXXX) 254794335725
amount number Airtime amount in KES 50.00
{
    "client_id": "codian_prd_0wGSy66bZu",
    "client_secret": "codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD",
    "phone_number": "254794335725",
    "amount": 50.00
}

Integration Example

Top up airtime using this JavaScript example.

fetch('https://codian.co.ke/api/airtime/send', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
        client_id: 'codian_prd_0wGSy66bZu',
        client_secret: 'codian_sk_prd_21FjoE6JA6uNfSfrfvRtJ8MtRlxWiD',
        phone_number: '254794335725',
        amount: 50.00
    })
})
.then(response => response.json())
.then(data => {
    if (data.success) {
        console.log('Airtime top-up sent!');
    } else {
        console.error('Error:', data.error);
    }
})
.catch(error => console.error('Error:', error));

Airtime API: Webhooks

Webhook Payload

Receive airtime top-up status via your webhook endpoint.

{
    "airtime_id": "airtime_202",
    "phone_number": "254794335725",
    "amount": 50.00,
    "status": "completed",
    "timestamp": "2025-10-19 10:03:00"
}

Common Errors

Error Codes & Solutions

Below are common errors and their solutions.

Error Code Description Solution
401 Unauthorized Invalid client_id or client_secret. Verify credentials in your Codian dashboard. Ensure no spaces or typos. Use environment variables to avoid hardcoding errors.
400 Bad Request Missing or invalid payload fields. Check payload against the API’s required fields (e.g., amount ≥ 1, valid phone_number). Log the request body for debugging.
Timeout Payment or API request timed out. Ensure user has funds (for payments) or network is stable. Implement retry logic with exponential backoff.
503 Service Unavailable Codian server is temporarily down or under maintenance. Check Codian status page for updates. Retry after some time.

Contact Support

Support Channels

For assistance, contact our support team via:

Include your client_id, error details, and logs for faster resolution.