diff --git a/src/client.rs b/src/client.rs index 65c87ee7b..b20f966f0 100644 --- a/src/client.rs +++ b/src/client.rs @@ -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) @@ -113,22 +112,11 @@ impl<'mpesa, Env: ApiEnvironment> Mpesa { .get(&url) .basic_auth(&self.client_key, Some(&self.client_secret)) .send() + .await? + .error_for_status()? + .json::() .await?; - if response.status().is_success() { - let value = response.json::().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::().await?; - Err(MpesaError::AuthenticationError(error)) + Ok(response.access_token) } /// **B2C Builder** @@ -524,6 +512,11 @@ impl<'mpesa, Env: ApiEnvironment> Mpesa { } } +#[derive(Debug, serde::Deserialize)] +struct AuthResponse { + pub access_token: String, +} + #[cfg(test)] mod tests { use crate::Sandbox;