mpesa-rust
About
An unofficial Rust wrapper around the Safaricom API for accessing M-Pesa services.
Install
Cargo.toml
[dependencies]
mpesa = "0.3.5"
In your lib or binary crate:
use 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 CLIENT_KEY and
CLIENT_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.
NOTE:
- Only calling
unwrap
for demonstration purposes. Errors are handled appropriately in the lib via theMpesaError
enum.
These are the following ways you can instantiate Mpesa
:
use ;
use env;
let client = new;
assert!
Since the Environment
enum implements FromStr
and TryFrom
, you can pass the name of the environment as a &str
and call the parse()
or try_into()
method to create an Environment
type from the string slice (Pascal case and Uppercase string slices also valid):
use Mpesa;
use env;
let client = new;
assert!
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;
use env;
let client = new;
client.set_initiator_password;
assert!
Services
The following services are currently available from the Mpesa
client as methods that return builders:
- B2C
let response = client
.b2c
.party_a
.party_b
.result_url
.timeout_url
.amount
.send;
assert!
- B2B
let response = client
.b2b
.party_a
.party_b
.result_url
.timeout_url
.account_ref
.amount
.send;
assert!
- C2B Register
let response = client
.c2b_register
.short_code
.confirmation_url
.validation_url
.send;
assert!
- C2B Simulate
let response = client
.c2b_simulate
.short_code
.msisdn
.amount
.send;
assert!
- Account Balance
let response = client
.account_balance
.result_url
.timeout_url
.party_a
.send;
assert!
- Mpesa Express Request / STK push / Lipa na M-PESA online
let response = client
.express_request
.phone_number
.party_a
.party_b
.amount
.callback_url
.send;
assert!
More will be added progressively, pull requests welcome
Author
Collins Muriuki
- Twitter: @collinsmuriuki_
- 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.
Copyright © 2021 Collins Muriuki. This project is MIT licensed.