#async #accessing #api #tokio #response #request #mpesa

async-mpesa

一个用于访问 mpesa api 的 Rust 库

1 个不稳定版本

0.2.0 2023年8月12日

#185 in 财务

MIT/Apache

30KB
740 代码行

这是一个用于访问 mpesa api 的异步 Rust 库。

获取访问令牌

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

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

#[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);
}

发送请求

一个 Mpesa Express (STK Push) 请求的示例

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);

发送请求到 mpesa api 的方法

要访问不同的请求,请使用以下方法访问 mpesa 提供的 api。

  1. 账户余额
    AccountBalanceRequestArgs::Default()
    
  2. B2C
    B2CRequestArgs::Default()
    
  3. 商业购买商品
    BusinessBuyGoodsRequestArgs::Default()
    
  4. 商业支付账单
    BusinessPayBillRequestArgs::Default()
    
  5. Mpesa Express 查询
    ExpressQueryRequestArgs::Default()
    
  6. 二维码
    QRRequestArgs::Default()
    
  7. 撤销交易
    ReversalRequestArgs::Default()
    
  8. Mpesa Express (STK Push)
    ExpressPushRequestArgs::Default()
    
  9. 交易状态
    TransactionStatusRequestArgs::Default()
    
  10. 税务转账
    TaxRemitRequestArgs::Default()
    

此库仍然适用于针对 wasm 架构的版本。

依赖关系

~7–19MB
~283K SLoC