Struct mpesa::Mpesa

source ·
pub struct Mpesa<Env: ApiEnvironment> { /* private fields */ }
Expand description

Mpesa client that will facilitate communication with the Safaricom API

Implementations§

source§

impl<'mpesa, Env: ApiEnvironment> Mpesa<Env>

source

pub fn new<S: Into<String>>( client_key: S, client_secret: S, environment: Env ) -> Self

Constructs a new Mpesa instance.

Example
let client: Mpesa = Mpesa::new(
    env!("CLIENT_KEY"),
    env!("CLIENT_SECRET"),
    Environment::Sandbox,
);
Panics

This method can panic if a TLS backend cannot be initialized for the internal http_client

source

pub fn set_initiator_password<S: Into<String>>(&self, initiator_password: S)

Optional in development but required for production, you will need to call this method and set your production initiator password. If in development, default initiator password is already pre-set

use mpesa::Mpesa;

let client: Mpesa = Mpesa::new(
    env::var("CLIENT_KEY").unwrap(),
    env::var("CLIENT_SECRET").unwrap(),
    Environment::Sandbox,
);

client.set_initiator_password("your_initiator_password");
source

pub async fn is_connected(&self) -> bool

Checks if the client can be authenticated

source

pub fn b2c(&'mpesa self, initiator_name: &'mpesa str) -> B2cBuilder<'mpesa, Env>

B2C Builder

Creates a B2cBuilder for building a B2C transaction struct. The builder is consumed and request made by calling its send method. See more from Safaricom the API docs here.

Requires an initiator_name, the credential/ username used to authenticate the transaction request

Example
let response = client
    .b2c("testapi496")
    .party_a("600496")
    .party_b("600000")
    .result_url("https://testdomain.com/err")
    .timeout_url("https://testdomain.com/ok")
    .amount(1000)
    .remarks("Your Remark") // optional, defaults to "None"
    .occasion("Your Occasion") // optional, defaults to "None"
    .command_id(mpesa::CommandId::BusinessPayment) // optional, defaults to `CommandId::BusinessPayment`
    .send();
source

pub fn b2b(&'mpesa self, initiator_name: &'mpesa str) -> B2bBuilder<'mpesa, Env>

B2B Builder

Creates a B2bBuilder for building B2B transaction struct.

See more from the Safaricom API docs here

Requires an initiator_name, the credential/ username used to authenticate the transaction request

Example
let response = client.b2b("testapi496")
   .party_a("600496")
   .party_b("600000")
   .result_url("https://testdomain.com/err")
   .timeout_url("https://testdomain.com/ok")
   .account_ref("254708374149")
   .amount(1000)
   .command_id(mpesa::CommandId::BusinessToBusinessTransfer) // optional, defaults to `CommandId::BusinessToBusinessTransfer`
   .remarks("None") // optional, defaults to "None"
   .sender_id(mpesa::IdentifierTypes::ShortCode) // optional, defaults to `IdentifierTypes::ShortCode`
   .receiver_id(mpesa::IdentifierTypes::ShortCode) // optional, defaults to `IdentifierTypes::ShortCode`
   .send();
source

pub fn onboard(&'mpesa self) -> OnboardBuilder<'mpesa, Env>

Bill Manager Onboard Builder

Creates a OnboardBuilder which allows you to opt in as a biller to the bill manager features.

See more from the Safaricom API docs here

Example
let response = client
    .onboard()
    .callback_url("https://testdomain.com/true")
    .email("email@test.com")
    .logo("https://file.domain/file.png")
    .official_contact("0712345678")
    .send_reminders(SendRemindersTypes::Enable)
    .short_code("600496")
    .send()
    .await;
source

pub fn onboard_modify(&'mpesa self) -> OnboardModifyBuilder<'mpesa, Env>

Bill Manager Onboard Modify Builder

Creates a OnboardModifyBuilder which allows you to opt in as a biller to the bill manager features.

See more from the Safaricom API docs here

Example
let response = client
    .onboard_modify()
    .callback_url("https://testdomain.com/true")
    .email("email@test.com")
    .logo("https://file.domain/file.png")
    .official_contact("0712345678")
    .send_reminders(SendRemindersTypes::Enable)
    .short_code("600496")
    .send()
    .await;
source

pub fn bulk_invoice(&'mpesa self) -> BulkInvoiceBuilder<'mpesa, Env>

Bill Manager Bulk Invoice Builder

Creates a BulkInvoiceBuilder which allows you to send invoices to your customers in bulk. See more from the Safaricom API docs here

Example
use chrone::prelude::Utc;

let response = client
    .bulk_invoice()

    // Add multiple invoices at once
    .invoices(vec![
        Invoice {
            amount: 1000.0,
            account_reference: "John Doe",
            billed_full_name: "John Doe",
            billed_period: "August 2021",
            billed_phone_number: "0712345678",
            due_date: Utc::now(),
            external_reference: "INV2345",
            invoice_items: Some(
                vec![InvoiceItem {amount: 1000.0, item_name: "An item"}]
            ),
            invoice_name: "Invoice 001"
        }
    ])

    // Add a single invoice
    .invoice(
        Invoice {
            amount: 1000.0,
            account_reference: "John Doe",
            billed_full_name: "John Doe",
            billed_period: "August 2021",
            billed_phone_number: "0712345678",
            due_date: Utc::now(),
            external_reference: "INV2345",
            invoice_items: Some(vec![InvoiceItem {
                amount: 1000.0,
                item_name: "An item",
            }]),
            invoice_name: "Invoice 001",
        }
    )
    .send()
    .await;
source

pub fn single_invoice(&'mpesa self) -> SingleInvoiceBuilder<'mpesa, Env>

Bill Manager Single Invoice Builder

Creates a SingleInvoiceBuilder which allows you to create and send invoices to your customers. See more from the Safaricom API docs here

Example
use chrono::prelude::Utc;

let response = client
    .single_invoice()
    .amount(1000.0)
    .account_reference("John Doe")
    .billed_full_name("John Doe")
    .billed_period("August 2021")
    .billed_phone_number("0712345678")
    .due_date(Utc::now())
    .external_reference("INV2345")
    .invoice_items(vec![
        InvoiceItem {amount: 1000.0, item_name: "An item"}
    ])
    .invoice_name("Invoice 001")
    .send()
    .await;
source

pub fn reconciliation(&'mpesa self) -> ReconciliationBuilder<'mpesa, Env>

Bill Manager Reconciliation Builder

Creates a ReconciliationBuilder which enables your customers to receive e-receipts for payments made to your paybill account. See more from the Safaricom API docs here

Example
use chrono::prelude::Utc;

let response = client
    .reconciliation()
    .account_reference("John Doe")
    .external_reference("INV2345")
    .full_name("John Doe")
    .invoice_name("Invoice 001")
    .paid_amount(1000.0)
    .payment_date(Utc::now())
    .phone_number("0712345678")
    .transaction_id("TRANSACTION_ID")
    .send()
    .await;
source

pub fn cancel_invoice(&'mpesa self) -> CancelInvoiceBuilder<'mpesa, Env>

Bill Manager Cancel Invoice Builder

Creates a CancelInvoiceBuilder which allows you to recall a sent invoice. See more from the Safaricom API docs here

Example
use chrono::prelude::Utc;

let response = client
    .cancel_invoice()
    .external_references(vec!["9KLSS011"])
    .send()
    .await;
source

pub fn c2b_register(&'mpesa self) -> C2bRegisterBuilder<'mpesa, Env>

C2B Register builder

Creates a C2bRegisterBuilder for registering URLs to the 3rd party shortcode.

See more from the Safaricom API docs here

Example
let response = client
   .c2b_register()
   .short_code("600496")
   .confirmation_url("https://testdomain.com/true")
   .validation_url("https://testdomain.com/valid")
   .response_type(mpesa::ResponseTypes::Complete) // optional, defaults to `ResponseTypes::Complete`
   .send();
source

pub fn c2b_simulate(&'mpesa self) -> C2bSimulateBuilder<'mpesa, Env>

C2B Simulate Builder

Creates a C2bSimulateBuilder for simulating C2B transactions

See more here

Example
let response = client.c2b_simulate()
   .short_code("600496")
   .msisdn("254700000000")
   .amount(1000)
   .command_id(mpesa::CommandId::CustomerPayBillOnline) // optional, defaults to `CommandId::CustomerPayBillOnline`
   .bill_ref_number("Your_BillRefNumber>") // optional, defaults to "None"
   .send();
source

pub fn account_balance( &'mpesa self, initiator_name: &'mpesa str ) -> AccountBalanceBuilder<'mpesa, Env>

Account Balance Builder

Creates an AccountBalanceBuilder for enquiring the balance on an MPESA BuyGoods. Requires an initiator_name.

See more from the Safaricom API docs here

Example
let response = client
   .account_balance("testapi496")
   .result_url("https://testdomain.com/err")
   .timeout_url("https://testdomain.com/ok")
   .party_a("600496")
   .command_id(mpesa::CommandId::AccountBalance) // optional, defaults to `CommandId::AccountBalance`
   .identifier_type(mpesa::IdentifierTypes::ShortCode) // optional, defaults to `IdentifierTypes::ShortCode`
   .remarks("Your Remarks") // optional, defaults to "None"
   .send();
source

pub fn express_request( &'mpesa self, business_short_code: &'mpesa str ) -> MpesaExpressRequestBuilder<'mpesa, Env>

Mpesa Express Request/ STK push Builder

Creates a MpesaExpressRequestBuilder struct Requires a business_short_code - The organization shortcode used to receive the transaction

See more from the Safaricom API docs here

Example
 let response = client
    .express_request("174379")
    .phone_number("254708374149")
    .party_a("254708374149")
    .party_b("174379")
    .amount(500)
    .callback_url("https://test.example.com/api")
    .transaction_type(CommandId::CustomerPayBillOnline) // Optional, defaults to `CommandId::CustomerPayBillOnline`
    .transaction_desc("Description") // Optional, defaults to "None"
    .send();
source

pub fn transaction_reversal( &'mpesa self, initiator_name: &'mpesa str ) -> TransactionReversalBuilder<'mpesa, Env>

Transaction Reversal Builder Reverses a B2B, B2C or C2B M-Pesa transaction.

See more from the Safaricom API docs here

source

pub fn transaction_status( &'mpesa self, initiator_name: &'mpesa str ) -> TransactionStatusBuilder<'mpesa, Env>

Transaction Status Builder Queries the status of a B2B, B2C or C2B M-Pesa transaction.

See more from the Safaricom API docs here

Example
let response = client
  .transaction_status("testapi496")
  .party_a("600496")
  .identifier_type(mpesa::IdentifierTypes::ShortCode) // optional, defaults to `IdentifierTypes::ShortCode`
  .remarks("Your Remarks") // optional, defaults to "None"
  .result_url("https://testdomain.com/err")
  .timeout_url("https://testdomain.com/ok")
  .send()
  .await;
source

pub fn dynamic_qr(&'mpesa self) -> DynamicQRBuilder<'mpesa, Env>

** Dynamic QR Code Builder **

Generates a QR code that can be scanned by a M-Pesa customer to make payments.

See more from the Safaricom API docs [here](https://developer.safaricom. co.ke/APIs/DynamicQRCode)

Example
let response = client
    .dynamic_qr_code()
    .amount(1000)
    .ref_no("John Doe")
    .size("300")
    .merchant_name("John Doe")
    .credit_party_identifier("600496")
    .try_transaction_type("bg")
    .unwrap()
    .build()
    .unwrap()
    .send()
    .await;

Trait Implementations§

source§

impl<Env: Clone + ApiEnvironment> Clone for Mpesa<Env>

source§

fn clone(&self) -> Mpesa<Env>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<Env: Debug + ApiEnvironment> Debug for Mpesa<Env>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<Env> !RefUnwindSafe for Mpesa<Env>

§

impl<Env> Send for Mpesa<Env>where Env: Send,

§

impl<Env> !Sync for Mpesa<Env>

§

impl<Env> Unpin for Mpesa<Env>where Env: Unpin,

§

impl<Env> !UnwindSafe for Mpesa<Env>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more