#mpesa #async #transaction #token #api

async-mpesa

A rust library for accessing mpesa apis

2 releases

0.2.1 Mar 25, 2025
0.2.0 Aug 12, 2023

#87 in Finance

Download history 4/week @ 2025-02-26 58/week @ 2025-03-19 62/week @ 2025-03-26

121 downloads per month

MIT/Apache

42KB
1K SLoC

This is an async rust library for accessing the mpesa apis.

To get an access token

use serde::{Serialize, Deserialize};
use base64::{Engine as _, engine::general_purpose};

#[derive(Debug. Serialize, Deserialize)]
struct Response {
    access_token: String,
    expires_in: String,
}

#[tokio::main]
async fn main() {
    let consumer_key = "Your consumer key here".to_string();
    let consumer_secret = "Your consumer secret".to_string();
    let client = reqwest::Client::new();
    let auth = format!("{}:{}", consumer_key, consumer_secret);
    let auth = general_purpose::URL_SAFE.encode(auth);
    let body = client.get("mpesa token url here")
        .header("Authorization", format!("Basic {}", auth))
        .send()
        .await
        .unwrap();
    
    let bytes = body
        .bytes()
        .await
        .unwrap();

    let response: Response = serde_json::from_slice(bytes.as_ref())
        .unwrap();

    println!("{:?}", response);
}

Making a request

An Example of a Mpesa Express (STK Push) request:

let config = MpesaConfig::new().with_access_token();

/// Create a client to make requests with default config or you can provide your own check the docs for more info
let client = Client::with_config(config);

/// all fields must be provided as strings
let request = ExpressPushRequestArgs::default()
    .PartyA("")
    .PartyB("")
    .Amount("")
    .Password(shortcode, passkey, timestamp)
    .AccountReference("")
    .TransactionType("")
    .BusinessShortCode("")
    .CallbackURL("")
    .TransactionDesc("")
    .Timestamp("")
    .PhoneNumber("")
    .build()
    .unwrap();

let response = client
    ///the appropriate method is required for the respective api you are trying to access.
    .stkpush()
    .create(request)
    .await
    .unwrap();

println!("{:?}", response);

Methods to make requests to the mpesa api

To access different request use the following methods to access the apis mpesa provides.

  1. Account Balance
AccountBalanceRequestArgs::Default()
  1. B2B Express
B2bExpressRequestArgs::Default()
  1. B2C Account Top Up
B2cTopUpRequestArgs::Default()
  1. B2C
B2CRequestArgs::Default()
  1. Business Buy Goods
BusinessBuyGoodsRequestArgs::Default()
  1. Payment and Reconciliation
ReconciliationRequestArgs::Default()
  1. Bill Manager Onboarding Generic API
BillOnboardingRequestArgs::Default()
  1. Updating Optin Details
BillUpdateArgs::Default()
  1. Business PayBill
BusinessPayBillRequestArgs::Default()
  1. Cancel Single Invoicing
CancelInvoiceRequestArgs::Default()
  1. Mpesa Express Query
ExpressQueryRequestArgs::Default()
  1. QR code
QRRequestArgs::Default()
  1. Mpesa Ratiba
RatibaRequestArgs::Default()
  1. Reverse Transaction
ReversalRequestArgs::Default()
  1. Mpesa Express (STK Push)
ExpressPushRequestArgs::Default()
  1. Transaction Status
TransactionStatusRequestArgs::Default()
  1. Tax Remit
TaxRemitRequestArgs::Default()

Note you can override the default configs eg. The Mpesa API urls. You can do this by using the

.with_access_token()
.with_api_url()
.with_environment()

functions when creating the client to override the default behaviour and switch url or switch url environments by specifying the environment, by passing this enum to the with_environment function.

pub enum Environment {
    Sandbox,
    Production,
}

Dependencies

~7–20MB
~275K SLoC