Skip to content

Latest commit

 

History

History
196 lines (144 loc) · 9.24 KB

README.md

File metadata and controls

196 lines (144 loc) · 9.24 KB

mpesa-rust

Rust

Discord

About

An unofficial Rust wrapper around the Safaricom API for accessing M-Pesa services.

Install

Cargo.toml

[dependencies]
mpesa = { version = "1" }

Optionally, you can disable default-features, which is basically the entire suite of MPESA APIs to conditionally select individual features. (See Services table for the full list of Cargo features)

Example:

[dependencies]
mpesa = { version = "1", default_features = false, features = ["b2b", "express_request"] }

In your lib or binary crate:

use mpesa::Mpesa;

Usage

Creating a Mpesa client

You will first need to create an instance of the Mpesa instance (the client). You are required to provide a CONSUMER_KEY and CONSUMER_SECRET. Here is how you can get these credentials for the Safaricom sandbox environment. It's worth noting that these credentials are only valid in the sandbox environment. To go live and get production keys read the docs here.

These are the following ways you can instantiate Mpesa:

use mpesa::{Mpesa, Environment};

#[tokio::main]
async fn main() {
    dotenvy::dotenv().ok();

    let client = Mpesa::new(
        dotenvy::var("CONSUMER_KEY").unwrap(),
        dotenvy::var("CONSUMER_SECRET").unwrap(),
        Environment::Sandbox,
    );

    assert!(client.is_connected().await);
}

Since the Environment enum implements FromStr and TryFrom for String and &str types, you can call Environment::from_str or Environment::try_from to create an Environment type. This is ideal if the environment values are stored in a .env or any other configuration file:

use mpesa::{Mpesa, Environment};
use std::convert::TryFrom;
use std::error::Error;
use std::str::FromStr;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    dotenvy::dotenv().ok();

    let client = Mpesa::new(
        dotenvy::var("CONSUMER_KEY").unwrap(),
        dotenvy::var("CONSUMER_SECRET").unwrap(),
        Environment::from_str("sandbox")?, // or
        // Environment::try_from("sandbox")?,
    );

    assert!(client.is_connected().await);
    Ok(())
}

The Mpesa struct's environment parameter is generic over any type that implements the ApiEnvironment trait. This trait expects the following methods to be implemented for a given type:

pub trait ApiEnvironment {
    fn base_url(&self) -> &str;
    fn get_certificate(&self) -> &str;
}

This trait allows you to create your own type to pass to the environment parameter. With this in place, you are able to mock http requests (for testing purposes) from the MPESA api by returning a mock server uri from the base_url method as well as using your own certificates, required to sign select requests to the MPESA api, by providing your own get_certificate implementation.

See the example below (and here so see how the trait is implemented for the Environment enum):

use mpesa::{Mpesa, ApiEnvironment};

#[derive(Clone)]
pub struct CustomEnvironment;

impl ApiEnvironment for CustomEnvironment {
    fn base_url(&self) -> &str {
        // your base url here
        "https://your_base_url.com"
    }

    fn get_certificate(&self) -> &str {
        // your certificate here
        r#"..."#
    }
}

#[tokio::main]
async fn main() {
    dotenvy::dotenv().ok();

    let client = Mpesa::new(
        dotenvy::var("CONSUMER_KEY").unwrap(),
        dotenvy::var("CONSUMER_SECRET").unwrap(),
        CustomEnvironment,
    );
}

If you intend to use in production, you will need to call a the set_initiator_password method from Mpesa after initially creating the client. Here you provide your initiator password, which overrides the default password used in sandbox "Safcom496!":

use mpesa::{Mpesa, Environment};

#[tokio::main]
async fn main() {
    dotenvy::dotenv().ok();

    let client = Mpesa::new(
        dotenvy::var("CONSUMER_KEY").unwrap(),
        dotenvy::var("CONSUMER_SECRET").unwrap(),
        Environment::Sandbox,
    );

    client.set_initiator_password("new_password");
    assert!(client.is_connected().await)
}

Services

The table below shows all the MPESA APIs from Safaricom and those supported by the crate along with their cargo features and usage examples

API Cargo Feature Status Example
Account Balance account_balance Stable ✅ account balance example
B2B Express Checkout N/A Unimplemented N/A
Bill Manager bill_manager Unstable ⚠️ bill manager examples
Business Buy Goods b2b Stable ✅ business buy goods example
Business Pay Bill N/A Unimplemented N/A
Business To Customer (B2C) b2c Stable ✅️ b2c example
Customer To Business (Register URL) c2b_register Stable ✅️ c2b register example
Customer To Business (Simulate) c2b_simulate Stable ✅️ c2b simulate example
Dynamic QR dynamic_qr Stable ✅️ dynamic qr example
M-PESA Express (Query) express Stable ✅️ ️ express query example
M-PESA Express (Simulate)/ STK push express Stable ✅️ express request example
Transaction Status transaction_status Stable ✅️ transaction status example
Transaction Reversal transaction_reversal Stable ✅️ transaction reversal example
Tax Remittance N/A Unimplemented N/A

Author

Collins Muriuki

  • Twitter: @c12i_
  • Not affiliated with Safaricom.

Contributing

Contributions, issues and feature requests are welcome!
Feel free to check issues page. You can also take a look at the contributing guide.

Made with contrib.rocks.


Copyright © 2023 Collins Muriuki.
This project is MIT licensed.