SDKs
SDK Libraries
Official libraries and code examples for JavaScript, Python, PHP, Ruby, Java, Go, C#, Swift, Kotlin, TypeScript, Dart, Elixir, Rust, and cURL.
JavaScript / Node.js
javascript
const axios = require('axios');
class PayNexusClient {
constructor(apiKey, baseUrl = 'https://paynexus.co.ke/api') {
this.client = axios.create({
baseURL: baseUrl,
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json',
},
timeout: 30000,
});
}
async validatePhone(phone) {
const response = await this.client.post('/mpesa/validate-phone', { phone });
return response.data;
}
async initiatePayment(amount, phone, description = null) {
const response = await this.client.post('/mpesa/payment/initiate', {
amount,
phone,
description,
});
return response.data;
}
async getPaymentAccounts() {
const response = await this.client.get('/merchant/payment-accounts');
return response.data;
}
async getPaymentStatus(reference) {
const response = await this.client.get(`/payments/${reference}`);
return response.data;
}
async registerWebhook(name, url, events = []) {
const response = await this.client.post('/webhooks/register', {
name,
url,
events,
});
return response.data;
}
}
const client = new PayNexusClient('sk_your_secret_key_here');
async function processPayment() {
const payment = await client.initiatePayment(
100,
'0746990866',
'Order #12345'
);
if (payment.success) {
const status = await client.getPaymentStatus(payment.data.reference);
console.log('Status:', status);
}
}
Python
python
import requests
class PayNexusClient:
def __init__(self, api_key, base_url='https://paynexus.co.ke/api'):
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update({
'X-API-Key': api_key,
'Content-Type': 'application/json',
'Accept': 'application/json',
})
self.session.timeout = 30
def validate_phone(self, phone):
response = self.session.post(
f'{self.base_url}/mpesa/validate-phone',
json={'phone': phone}
)
return response.json()
def initiate_payment(self, amount=None, phone=None, description=None):
response = self.session.post(
f'{self.base_url}/mpesa/payment/initiate',
json={
'amount': amount,
'phone': phone,
'description': description,
}
)
return response.json()
def get_payment_accounts(self):
response = self.session.get(f'{self.base_url}/merchant/payment-accounts')
return response.json()
def get_payment_status(self, reference):
response = self.session.get(f'{self.base_url}/payments/{reference}')
return response.json()
def register_webhook(self, name, url, events=None):
response = self.session.post(
f'{self.base_url}/webhooks/register',
json={'name': name, 'url': url, 'events': events or []}
)
return response.json()
# Install from PyPI: pip install paynexus-gateway
client = PayNexusClient('sk_your_secret_key_here')
payment = client.initiate_payment(
amount=100,
phone='0746990866',
description='Order #12345'
)
print(f"Payment initiated: {payment.get('data', {}).get('reference')}")
PHP (Guzzle)
php
<?php
use GuzzleHttp\Client;
class PayNexusClient
{
private Client $client;
public function __construct(string $apiKey, string $baseUrl = 'https://paynexus.co.ke/api')
{
$this->client = new Client([
'base_uri' => $baseUrl,
'headers' => [
'X-API-Key' => $apiKey,
'Content-Type' => 'application/json',
'Accept' => 'application/json',
],
'timeout' => 30,
]);
}
public function validatePhone(string $phone): array
{
$response = $this->client->post('/mpesa/validate-phone', [
'json' => ['phone' => $phone]
]);
return json_decode($response->getBody()->getContents(), true);
}
public function initiatePayment(float $amount, string $phone, ?string $description = null): array
{
$response = $this->client->post('/mpesa/payment/initiate', [
'json' => [
'amount' => $amount,
'phone' => $phone,
'description' => $description,
]
]);
return json_decode($response->getBody()->getContents(), true);
}
public function getPaymentAccounts(): array
{
$response = $this->client->get('/merchant/payment-accounts');
return json_decode($response->getBody()->getContents(), true);
}
public function getPaymentStatus(string $reference): array
{
$response = $this->client->get("/payments/{$reference}");
return json_decode($response->getBody()->getContents(), true);
}
public function registerWebhook(string $name, string $url, array $events = []): array
{
$response = $this->client->post('/webhooks/register', [
'json' => [
'name' => $name,
'url' => $url,
'events' => $events,
]
]);
return json_decode($response->getBody()->getContents(), true);
}
}
$client = new PayNexusClient('sk_your_secret_key_here');
$payment = $client->initiatePayment(
100,
'0746990866',
'Order #12345'
);
Ruby
ruby
require 'net/http'
require 'uri'
require 'json'
class PayNexusClient
def initialize(api_key, base_url = 'https://paynexus.co.ke/api')
@api_key = api_key
@base_url = base_url
end
def initiate_payment(amount, phone, description = nil)
uri = URI("#{@base_url}/mpesa/payment/initiate")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri)
request['X-API-Key'] = @api_key
request['Content-Type'] = 'application/json'
request.body = {
amount: amount,
phone: phone,
description: description
}.to_json
response = http.request(request)
JSON.parse(response.body)
end
def get_payment_status(reference)
uri = URI("#{@base_url}/payments/#{reference}")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri)
request['X-API-Key'] = @api_key
response = http.request(request)
JSON.parse(response.body)
end
end
client = PayNexusClient.new('sk_your_secret_key_here')
payment = client.initiate_payment(100, '0746990866', 'Order #12345')
puts "Payment initiated: #{payment.dig('data', 'reference')}"
Java
java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
public class PayNexusClient {
private final String apiKey;
private final String baseUrl;
private final HttpClient client;
private final ObjectMapper mapper;
public PayNexusClient(String apiKey) {
this.apiKey = apiKey;
this.baseUrl = "https://paynexus.co.ke/api";
this.client = HttpClient.newHttpClient();
this.mapper = new ObjectMapper();
}
public Map initiatePayment(double amount, String phone, String description)
throws Exception {
var payload = Map.of(
"amount", amount,
"phone", phone,
"description", description
);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/mpesa/payment/initiate"))
.header("X-API-Key", apiKey)
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofString(mapper.writeValueAsString(payload)))
.build();
HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
return mapper.readValue(response.body(), Map.class);
}
}
PayNexusClient client = new PayNexusClient("sk_your_secret_key_here");
Map payment = client.initiatePayment(100, "0746990866", "Order #12345");
Go
go
package paynexus
import (
"bytes"
"encoding/json"
"net/http"
)
type PayNexusClient struct {
APIKey string
BaseURL string
}
type PaymentRequest struct {
Amount float64 `json:"amount"`
Phone string `json:"phone"`
Description string `json:"description,omitempty"`
}
func (c *PayNexusClient) InitiatePayment(amount float64, phone, description string) (map[string]interface{}, error) {
payload := PaymentRequest{
Amount: amount,
Phone: phone,
Description: description,
}
jsonData, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", c.BaseURL+"/mpesa/payment/initiate", bytes.NewBuffer(jsonData))
req.Header.Set("X-API-Key", c.APIKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
return result, nil
}
client := &PayNexusClient{APIKey: "sk_your_secret_key_here", BaseURL: "https://paynexus.co.ke/api"}
payment, _ := client.InitiatePayment(100, "0746990866", "Order #12345")
C# (.NET)
csharp
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
public class PayNexusClient
{
private readonly HttpClient _httpClient;
private readonly string _apiKey;
public PayNexusClient(string apiKey)
{
_apiKey = apiKey;
_httpClient = new HttpClient { BaseAddress = new Uri("https://paynexus.co.ke/api") };
}
public async Task> InitiatePayment(
double amount, string phone, string description = null)
{
var payload = new Dictionary
{
["amount"] = amount,
["phone"] = phone,
["description"] = description
};
var json = JsonSerializer.Serialize(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, "/mpesa/payment/initiate")
{
Content = content
};
request.Headers.Add("X-API-Key", _apiKey);
var response = await _httpClient.SendAsync(request);
var responseJson = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize>(responseJson);
}
}
var client = new PayNexusClient("sk_your_secret_key_here");
var payment = await client.InitiatePayment(100, "0746990866", "Order #12345");
Swift (iOS)
swift
import Foundation
class PayNexusClient {
private let apiKey: String
private let baseURL = "https://paynexus.co.ke/api"
init(apiKey: String) {
self.apiKey = apiKey
}
func initiatePayment(amount: Double, phone: String, description: String?) async throws -> [String: Any] {
var payload: [String: Any] = [
"amount": amount,
"phone": phone
]
if let description = description {
payload["description"] = description
}
let url = URL(string: "\(baseURL)/mpesa/payment/initiate")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONSerialization.data(withJSONObject: payload)
let (data, _) = try await URLSession.shared.data(for: request)
return try JSONSerialization.jsonObject(with: data) as! [String: Any]
}
}
let client = PayNexusClient(apiKey: "sk_your_secret_key_here")
let payment = try await client.initiatePayment(amount: 100, phone: "0746990866", description: "Order #12345")
Kotlin (Android)
kotlin
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.put
import kotlinx.serialization.json.buildJsonObject
import java.net.URL
import java.net.HttpURLConnection
class PayNexusClient(private val apiKey: String) {
private val baseUrl = "https://paynexus.co.ke/api"
suspend fun initiatePayment(amount: Double, phone: String, description: String? = null): Map {
val payload = buildJsonObject {
put("amount", amount)
put("phone", phone)
description?.let { put("description", it) }
}
return withContext(Dispatchers.IO) {
val url = URL("$baseUrl/mpesa/payment/initiate")
val conn = (url.openConnection() as HttpURLConnection).apply {
requestMethod = "POST"
setRequestProperty("X-API-Key", apiKey)
setRequestProperty("Content-Type", "application/json")
doOutput = true
}
conn.outputStream.use { it.write(payload.toString().toByteArray()) }
val response = conn.inputStream.bufferedReader().use { it.readText() }
Json.parseToJson(response).toMap()
}
}
}
TypeScript
typescript
import axios from 'axios';
interface PaymentResponse {
success: boolean;
data?: { reference: string; checkout_request_id?: string };
error?: string;
}
class PayNexusClient {
private client: axios.AxiosInstance;
constructor(apiKey: string, baseUrl = 'https://paynexus.co.ke/api') {
this.client = axios.create({
baseURL: baseUrl,
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json',
},
timeout: 30000,
});
}
async initiatePayment(
amount: number,
phone: string,
description?: string
): Promise {
const response = await this.client.post('/mpesa/payment/initiate', {
amount,
phone,
description,
});
return response.data;
}
async getPaymentStatus(reference: string): Promise {
const response = await this.client.get(`/payments/${reference}`);
return response.data;
}
}
const client = new PayNexusClient('sk_your_secret_key_here');
const payment = await client.initiatePayment(100, '0746990866', 'Order #12345');
console.log('Payment reference:', payment.data?.reference);
Dart (Flutter)
dart
import 'dart:convert';
import 'package:http/http.dart' as http;
class PayNexusClient {
final String apiKey;
final String baseUrl;
PayNexusClient(this.apiKey, [this.baseUrl = 'https://paynexus.co.ke/api']);
Future
Elixir
elixir
defmodule PayNexusClient do
def initiate_payment(api_key, amount, phone, description \\ nil) do
headers = [
{"X-API-Key", api_key},
{"Content-Type", "application/json"}
]
payload = %{
amount: amount,
phone: phone,
description: description
} |> Jason.encode!()
url = "https://paynexus.co.ke/api/mpesa/payment/initiate"
case HTTPoison.post(url, payload, headers) do
{:ok, %HTTPoison.Response{body: body}} ->
Jason.decode!(body)
{:error, reason} ->
{:error, reason}
end
end
end
payment = PayNexusClient.initiate_payment(
"sk_your_secret_key_here",
100,
"0746990866",
"Order #12345"
)
Rust
rust
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
#[derive(Serialize)]
struct PaymentRequest {
amount: f64,
phone: String,
#[serde(skip_serializing_if = "Option::is_none")]
description: Option,
}
struct PayNexusClient {
api_key: String,
client: reqwest::Client,
}
impl PayNexusClient {
fn new(api_key: &str) -> Self {
let mut headers = HeaderMap::new();
headers.insert("X-API-Key", HeaderValue::from_str(api_key).unwrap());
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
Self {
api_key: api_key.to_string(),
client: reqwest::Client::builder().default_headers(headers).build().unwrap(),
}
}
async fn initiate_payment(&self, amount: f64, phone: &str, description: Option<&str>) -> Result, reqwest::Error> {
let payload = PaymentRequest {
amount,
phone: phone.to_string(),
description: description.map(|s| s.to_string()),
};
let resp = self.client
.post("https://paynexus.co.ke/api/mpesa/payment/initiate")
.json(&payload)
.send()
.await?
.json::>()
.await?;
Ok(resp)
}
}
let client = PayNexusClient::new("sk_your_secret_key_here");
let payment = client.initiate_payment(100.0, "0746990866", Some("Order #12345")).await?;
cURL (Raw HTTP)
bash
curl -X POST https://paynexus.co.ke/api/mpesa/payment/initiate \
-H "X-API-Key: sk_your_secret_key_here" \
-H "Content-Type: application/json" \
-d '{
"amount": 100,
"phone": "0746990866",
"description": "Order #12345"
}'