SonicPesa

Code Examples

Integration examples in all major programming languages

← Back to Documentation

Create Order - Code Examples

Examples showing how to create a payment order in different programming languages.

<?php
// SonicPesa API - Create Order (PHP)

$apiKey = 'YOUR_API_KEY';
$apiUrl = 'https://api.sonicpesa.com/api/v1/payment/create_order';

$data = [
    'buyer_email' => 'customer@example.com',
    'buyer_name' => 'John Doe',
    'buyer_phone' => '255682812345',
    'amount' => 10000,
    'currency' => 'TZS'
];

$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'X-API-KEY: ' . $apiKey
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode === 200) {
    $result = json_decode($response, true);
    echo "Order ID: " . $result['data']['order_id'] . "\n";
    echo "Status: " . $result['data']['payment_status'] . "\n";
} else {
    echo "Error: " . $response . "\n";
}
?>
# SonicPesa API - Create Order (Python)
import requests
import json

api_key = 'YOUR_API_KEY'
api_url = 'https://api.sonicpesa.com/api/v1/payment/create_order'

headers = {
    'Content-Type': 'application/json',
    'X-API-KEY': api_key
}

data = {
    'buyer_email': 'customer@example.com',
    'buyer_name': 'John Doe',
    'buyer_phone': '255682812345',
    'amount': 10000,
    'currency': 'TZS'
}

response = requests.post(api_url, headers=headers, json=data)

if response.status_code == 200:
    result = response.json()
    print(f"Order ID: {result['data']['order_id']}")
    print(f"Status: {result['data']['payment_status']}")
else:
    print(f"Error: {response.text}")
// SonicPesa API - Create Order (JavaScript/Node.js)
const axios = require('axios');

const apiKey = 'YOUR_API_KEY';
const apiUrl = 'https://api.sonicpesa.com/api/v1/payment/create_order';

const data = {
    buyer_email: 'customer@example.com',
    buyer_name: 'John Doe',
    buyer_phone: '255682812345',
    amount: 10000,
    currency: 'TZS'
};

const config = {
    headers: {
        'Content-Type': 'application/json',
        'X-API-KEY': apiKey
    }
};

axios.post(apiUrl, data, config)
    .then(response => {
        console.log('Order ID:', response.data.data.order_id);
        console.log('Status:', response.data.data.payment_status);
    })
    .catch(error => {
        console.error('Error:', error.response ? error.response.data : error.message);
    });

// Using fetch (Browser/Modern Node.js)
fetch(apiUrl, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-API-KEY': apiKey
    },
    body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
    console.log('Order ID:', result.data.order_id);
    console.log('Status:', result.data.payment_status);
})
.catch(error => console.error('Error:', error));
// SonicPesa API - Create Order (Java)
import java.net.http.*;
import java.net.URI;
import org.json.JSONObject;

public class SonicPesaAPI {
    public static void main(String[] args) throws Exception {
        String apiKey = "YOUR_API_KEY";
        String apiUrl = "https://api.sonicpesa.com/api/v1/payment/create_order";
        
        JSONObject data = new JSONObject();
        data.put("buyer_email", "customer@example.com");
        data.put("buyer_name", "John Doe");
        data.put("buyer_phone", "255682812345");
        data.put("amount", 10000);
        data.put("currency", "TZS");
        
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(apiUrl))
            .header("Content-Type", "application/json")
            .header("X-API-KEY", apiKey)
            .POST(HttpRequest.BodyPublishers.ofString(data.toString()))
            .build();
        
        HttpResponse response = client.send(request, 
            HttpResponse.BodyHandlers.ofString());
        
        if (response.statusCode() == 200) {
            JSONObject result = new JSONObject(response.body());
            System.out.println("Order ID: " + 
                result.getJSONObject("data").getString("order_id"));
            System.out.println("Status: " + 
                result.getJSONObject("data").getString("payment_status"));
        } else {
            System.out.println("Error: " + response.body());
        }
    }
}
// SonicPesa API - Create Order (C#)
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class SonicPesaAPI
{
    private static readonly HttpClient client = new HttpClient();
    
    public static async Task Main()
    {
        string apiKey = "YOUR_API_KEY";
        string apiUrl = "https://api.sonicpesa.com/api/v1/payment/create_order";
        
        var data = new
        {
            buyer_email = "customer@example.com",
            buyer_name = "John Doe",
            buyer_phone = "255682812345",
            amount = 10000,
            currency = "TZS"
        };
        
        client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);
        
        var json = JsonSerializer.Serialize(data);
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        
        var response = await client.PostAsync(apiUrl, content);
        var responseString = await response.Content.ReadAsStringAsync();
        
        if (response.IsSuccessStatusCode)
        {
            var result = JsonSerializer.Deserialize(responseString);
            Console.WriteLine($"Order ID: {result.GetProperty("data").GetProperty("order_id")}");
            Console.WriteLine($"Status: {result.GetProperty("data").GetProperty("payment_status")}");
        }
        else
        {
            Console.WriteLine($"Error: {responseString}");
        }
    }
}
# SonicPesa API - Create Order (Ruby)
require 'net/http'
require 'json'
require 'uri'

api_key = 'YOUR_API_KEY'
api_url = URI('https://api.sonicpesa.com/api/v1/payment/create_order')

data = {
  buyer_email: 'customer@example.com',
  buyer_name: 'John Doe',
  buyer_phone: '255682812345',
  amount: 10000,
  currency: 'TZS'
}

http = Net::HTTP.new(api_url.host, api_url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(api_url)
request['Content-Type'] = 'application/json'
request['X-API-KEY'] = api_key
request.body = data.to_json

response = http.request(request)

if response.code == '200'
  result = JSON.parse(response.body)
  puts "Order ID: #{result['data']['order_id']}"
  puts "Status: #{result['data']['payment_status']}"
else
  puts "Error: #{response.body}"
end
// SonicPesa API - Create Order (Go)
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type OrderRequest struct {
    BuyerEmail string `json:"buyer_email"`
    BuyerName  string `json:"buyer_name"`
    BuyerPhone string `json:"buyer_phone"`
    Amount     int    `json:"amount"`
    Currency   string `json:"currency"`
}

type OrderResponse struct {
    Status  string `json:"status"`
    Message string `json:"message"`
    Data    struct {
        OrderID       string `json:"order_id"`
        PaymentStatus string `json:"payment_status"`
    } `json:"data"`
}

func main() {
    apiKey := "YOUR_API_KEY"
    apiURL := "https://api.sonicpesa.com/api/v1/payment/create_order"
    
    data := OrderRequest{
        BuyerEmail: "customer@example.com",
        BuyerName:  "John Doe",
        BuyerPhone: "255682812345",
        Amount:     10000,
        Currency:   "TZS",
    }
    
    jsonData, _ := json.Marshal(data)
    
    req, _ := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonData))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("X-API-KEY", apiKey)
    
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer resp.Body.Close()
    
    body, _ := ioutil.ReadAll(resp.Body)
    
    if resp.StatusCode == 200 {
        var result OrderResponse
        json.Unmarshal(body, &result)
        fmt.Printf("Order ID: %s\n", result.Data.OrderID)
        fmt.Printf("Status: %s\n", result.Data.PaymentStatus)
    } else {
        fmt.Println("Error:", string(body))
    }
}
# SonicPesa API - Create Order (cURL)

curl -X POST https://api.sonicpesa.com/api/v1/payment/create_order \
  -H "Content-Type: application/json" \
  -H "X-API-KEY: YOUR_API_KEY" \
  -d '{
    "buyer_email": "customer@example.com",
    "buyer_name": "John Doe",
    "buyer_phone": "255682812345",
    "amount": 10000,
    "currency": "TZS"
  }'

Check Order Status - Code Examples

Examples showing how to check payment order status in different programming languages.

<?php
// SonicPesa API - Check Order Status (PHP)

$apiKey = 'YOUR_API_KEY';
$apiUrl = 'https://api.sonicpesa.com/api/v1/payment/order_status';

$data = [
    'order_id' => 'sp_67890abcdef'
];

$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'X-API-KEY: ' . $apiKey
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode === 200) {
    $result = json_decode($response, true);
    echo "Payment Status: " . $result['data']['payment_status'] . "\n";
    echo "Amount: " . $result['data']['amount'] . " TZS\n";
    echo "Channel: " . $result['data']['channel'] . "\n";
} else {
    echo "Error: " . $response . "\n";
}
?>
# SonicPesa API - Check Order Status (Python)
import requests

api_key = 'YOUR_API_KEY'
api_url = 'https://api.sonicpesa.com/api/v1/payment/order_status'

headers = {
    'Content-Type': 'application/json',
    'X-API-KEY': api_key
}

data = {
    'order_id': 'sp_67890abcdef'
}

response = requests.post(api_url, headers=headers, json=data)

if response.status_code == 200:
    result = response.json()
    print(f"Payment Status: {result['data']['payment_status']}")
    print(f"Amount: {result['data']['amount']} TZS")
    print(f"Channel: {result['data']['channel']}")
else:
    print(f"Error: {response.text}")
// SonicPesa API - Check Order Status (JavaScript/Node.js)
const axios = require('axios');

const apiKey = 'YOUR_API_KEY';
const apiUrl = 'https://api.sonicpesa.com/api/v1/payment/order_status';

const data = {
    order_id: 'sp_67890abcdef'
};

const config = {
    headers: {
        'Content-Type': 'application/json',
        'X-API-KEY': apiKey
    }
};

axios.post(apiUrl, data, config)
    .then(response => {
        console.log('Payment Status:', response.data.data.payment_status);
        console.log('Amount:', response.data.data.amount, 'TZS');
        console.log('Channel:', response.data.data.channel);
    })
    .catch(error => {
        console.error('Error:', error.response ? error.response.data : error.message);
    });
// Similar structure to Create Order example
// Replace endpoint and data accordingly
// Similar structure to Create Order example
// Replace endpoint and data accordingly
# Similar structure to Create Order example
# Replace endpoint and data accordingly
// Similar structure to Create Order example
// Replace endpoint and data accordingly
curl -X POST https://api.sonicpesa.com/api/v1/payment/order_status \
  -H "Content-Type: application/json" \
  -H "X-API-KEY: YOUR_API_KEY" \
  -d '{"order_id": "sp_67890abcdef"}'

Webhook Signature Verification - Code Examples

Examples showing how to verify webhook signatures for security.

<?php
// Webhook Signature Verification (PHP)

$apiSecret = 'YOUR_API_SECRET';
$payload = file_get_contents('php://input');
$receivedSignature = $_SERVER['HTTP_X_SONICPESA_SIGNATURE'] ?? '';

$calculatedSignature = hash_hmac('sha256', $payload, $apiSecret);

if (hash_equals($calculatedSignature, $receivedSignature)) {
    // Webhook is authentic
    $data = json_decode($payload, true);
    
    // Process webhook data
    $event = $data['event'];
    $orderId = $data['order_id'];
    $status = $data['status'];
    
    // Your business logic here
    error_log("Webhook received: $event for order $orderId with status $status");
    
    http_response_code(200);
    echo json_encode(['status' => 'success']);
} else {
    // Invalid signature
    http_response_code(401);
    echo json_encode(['error' => 'Invalid signature']);
}
?>
# Webhook Signature Verification (Python/Flask)
from flask import Flask, request, jsonify
import hmac
import hashlib

app = Flask(__name__)
API_SECRET = 'YOUR_API_SECRET'

@app.route('/webhook', methods=['POST'])
def webhook():
    payload = request.get_data()
    received_signature = request.headers.get('X-SonicPesa-Signature', '')
    
    calculated_signature = hmac.new(
        API_SECRET.encode(),
        payload,
        hashlib.sha256
    ).hexdigest()
    
    if hmac.compare_digest(calculated_signature, received_signature):
        # Webhook is authentic
        data = request.get_json()
        
        event = data['event']
        order_id = data['order_id']
        status = data['status']
        
        # Your business logic here
        print(f"Webhook received: {event} for order {order_id} with status {status}")
        
        return jsonify({'status': 'success'}), 200
    else:
        return jsonify({'error': 'Invalid signature'}), 401

if __name__ == '__main__':
    app.run()
// Webhook Signature Verification (Node.js/Express)
const express = require('express');
const crypto = require('crypto');

const app = express();
const API_SECRET = 'YOUR_API_SECRET';

app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
    const payload = req.body;
    const receivedSignature = req.headers['x-sonicpesa-signature'] || '';
    
    const calculatedSignature = crypto
        .createHmac('sha256', API_SECRET)
        .update(payload)
        .digest('hex');
    
    if (crypto.timingSafeEqual(
        Buffer.from(calculatedSignature),
        Buffer.from(receivedSignature)
    )) {
        // Webhook is authentic
        const data = JSON.parse(payload);
        
        const { event, order_id, status } = data;
        
        // Your business logic here
        console.log(`Webhook received: ${event} for order ${order_id} with status ${status}`);
        
        res.status(200).json({ status: 'success' });
    } else {
        res.status(401).json({ error: 'Invalid signature' });
    }
});

app.listen(3000, () => console.log('Webhook server running on port 3000'));
# Webhook Signature Verification (Ruby/Sinatra)
require 'sinatra'
require 'json'
require 'openssl'

API_SECRET = 'YOUR_API_SECRET'

post '/webhook' do
  payload = request.body.read
  received_signature = request.env['HTTP_X_SONICPESA_SIGNATURE'] || ''
  
  calculated_signature = OpenSSL::HMAC.hexdigest(
    'SHA256',
    API_SECRET,
    payload
  )
  
  if Rack::Utils.secure_compare(calculated_signature, received_signature)
    # Webhook is authentic
    data = JSON.parse(payload)
    
    event = data['event']
    order_id = data['order_id']
    status = data['status']
    
    # Your business logic here
    puts "Webhook received: #{event} for order #{order_id} with status #{status}"
    
    status 200
    { status: 'success' }.to_json
  else
    status 401
    { error: 'Invalid signature' }.to_json
  end
end