Skip to content

Commit

Permalink
Simplify auth method
Browse files Browse the repository at this point in the history
  • Loading branch information
c12i committed Nov 9, 2023
1 parent abbfa0d commit 9c0a66f
Showing 1 changed file with 10 additions and 17 deletions.
27 changes: 10 additions & 17 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ use crate::services::{
OnboardModifyBuilder, ReconciliationBuilder, SingleInvoiceBuilder, TransactionReversalBuilder,
TransactionStatusBuilder,
};
use crate::{ApiError, MpesaError};
use crate::MpesaError;
use openssl::base64;
use openssl::rsa::Padding;
use openssl::x509::X509;
use reqwest::Client as HttpClient;
use serde_json::Value;
use std::cell::RefCell;

/// Source: [test credentials](https://developer.safaricom.co.ke/test_credentials)
Expand Down Expand Up @@ -113,22 +112,11 @@ impl<'mpesa, Env: ApiEnvironment> Mpesa<Env> {
.get(&url)
.basic_auth(&self.client_key, Some(&self.client_secret))
.send()
.await?
.error_for_status()?
.json::<AuthResponse>()
.await?;
if response.status().is_success() {
let value = response.json::<Value>().await?;
let access_token = value
.get("access_token")
.ok_or_else(|| String::from("Failed to extract token from the response"))
.unwrap();
let access_token = access_token
.as_str()
.ok_or_else(|| String::from("Error converting access token to string"))
.unwrap();

return Ok(access_token.to_string());
}
let error = response.json::<ApiError>().await?;
Err(MpesaError::AuthenticationError(error))
Ok(response.access_token)
}

/// **B2C Builder**
Expand Down Expand Up @@ -524,6 +512,11 @@ impl<'mpesa, Env: ApiEnvironment> Mpesa<Env> {
}
}

#[derive(Debug, serde::Deserialize)]
struct AuthResponse {
pub access_token: String,
}

#[cfg(test)]
mod tests {
use crate::Sandbox;
Expand Down

0 comments on commit 9c0a66f

Please sign in to comment.