use std::time::Duration;
use reqwest::{Method, Url};
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::error::{ApiErrorEnvelope, RazorpayError};
const DEFAULT_BASE_URL: &str = "https://api.razorpay.com/v1/";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const USER_AGENT: &str = concat!("razorpay-api-rust/", env!("CARGO_PKG_VERSION"));
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthMethod {
BasicAuth {
api_key: String,
api_secret: String,
},
BearerToken {
token: String,
},
}
#[derive(Debug, Clone)]
pub struct RazorpayClient {
http_client: reqwest::Client,
base_url: Url,
auth_method: AuthMethod,
}
impl RazorpayClient {
pub fn new(api_key: String, api_secret: String) -> Self {
Self::with_auth(AuthMethod::BasicAuth { api_key, api_secret })
}
pub fn new_with_bearer_token(token: String) -> Self {
Self::with_auth(AuthMethod::BearerToken { token })
}
pub fn base_url(&self) -> &Url {
&self.base_url
}
pub fn auth_method(&self) -> &AuthMethod {
&self.auth_method
}
fn with_auth(auth_method: AuthMethod) -> Self {
RazorpayClient {
http_client: reqwest::Client::builder()
.timeout(DEFAULT_TIMEOUT)
.user_agent(USER_AGENT)
.build()
.expect("failed to build HTTP client"),
base_url: DEFAULT_BASE_URL.parse().expect("Invalid base URL"),
auth_method,
}
}
pub fn with_base_url(mut self, base_url: Url) -> Self {
self.base_url = base_url;
self
}
fn url_for(&self, path: &str) -> Result<Url, RazorpayError> {
self.base_url
.join(path.trim_start_matches('/'))
.map_err(|e| RazorpayError::InvalidUrl(e.to_string()))
}
async fn request<Q, B, R>(
&self,
method: Method,
path: &str,
query: Option<&Q>,
body: Option<&B>,
) -> Result<R, RazorpayError>
where
Q: Serialize + ?Sized,
B: Serialize + ?Sized,
R: DeserializeOwned,
{
let mut req = self.http_client.request(method, self.url_for(path)?);
req = match &self.auth_method {
AuthMethod::BasicAuth { api_key, api_secret } => {
req.basic_auth(api_key, Some(api_secret))
}
AuthMethod::BearerToken { token } => req.bearer_auth(token),
};
if let Some(query) = query {
req = req.query(query);
}
if let Some(body) = body {
req = req.json(body);
}
let response = req.send().await?;
let status = response.status();
let bytes = response.bytes().await?;
if let Ok(envelope) = serde_json::from_slice::<ApiErrorEnvelope>(&bytes) {
return Err(envelope.into_error(status));
}
if !status.is_success() {
return Err(RazorpayError::UnexpectedStatus {
http_status: status,
body: String::from_utf8_lossy(&bytes).into_owned(),
});
}
let bytes: &[u8] = if bytes.is_empty() { b"null" } else { &bytes };
Ok(serde_json::from_slice(bytes)?)
}
pub(crate) async fn get<Q, R>(&self, path: &str, query: Option<&Q>) -> Result<R, RazorpayError>
where
Q: Serialize + ?Sized,
R: DeserializeOwned,
{
self.request::<Q, (), R>(Method::GET, path, query, None).await
}
pub(crate) async fn post<B, R>(&self, path: &str, body: Option<&B>) -> Result<R, RazorpayError>
where
B: Serialize + ?Sized,
R: DeserializeOwned,
{
self.request::<(), B, R>(Method::POST, path, None, body).await
}
pub(crate) async fn patch<B, R>(&self, path: &str, body: Option<&B>) -> Result<R, RazorpayError>
where
B: Serialize + ?Sized,
R: DeserializeOwned,
{
self.request::<(), B, R>(Method::PATCH, path, None, body).await
}
pub(crate) async fn put<B, R>(&self, path: &str, body: Option<&B>) -> Result<R, RazorpayError>
where
B: Serialize + ?Sized,
R: DeserializeOwned,
{
self.request::<(), B, R>(Method::PUT, path, None, body).await
}
pub(crate) async fn delete<R>(&self, path: &str) -> Result<R, RazorpayError>
where
R: DeserializeOwned,
{
self.request::<(), (), R>(Method::DELETE, path, None, None).await
}
}
impl RazorpayClient {
pub fn orders(&self) -> crate::resources::orders::OrdersClient<'_> {
crate::resources::orders::OrdersClient { client: self }
}
pub fn payments(&self) -> crate::resources::payments::PaymentsClient<'_> {
crate::resources::payments::PaymentsClient { client: self }
}
pub fn refunds(&self) -> crate::resources::refunds::RefundsClient<'_> {
crate::resources::refunds::RefundsClient { client: self }
}
pub fn customers(&self) -> crate::resources::customers::CustomersClient<'_> {
crate::resources::customers::CustomersClient { client: self }
}
pub fn cards(&self) -> crate::resources::cards::CardsClient<'_> {
crate::resources::cards::CardsClient { client: self }
}
pub fn items(&self) -> crate::resources::items::ItemsClient<'_> {
crate::resources::items::ItemsClient { client: self }
}
pub fn plans(&self) -> crate::resources::plans::PlansClient<'_> {
crate::resources::plans::PlansClient { client: self }
}
pub fn subscriptions(&self) -> crate::resources::subscriptions::SubscriptionsClient<'_> {
crate::resources::subscriptions::SubscriptionsClient { client: self }
}
pub fn invoices(&self) -> crate::resources::invoices::InvoicesClient<'_> {
crate::resources::invoices::InvoicesClient { client: self }
}
pub fn payment_links(&self) -> crate::resources::payment_links::PaymentLinksClient<'_> {
crate::resources::payment_links::PaymentLinksClient { client: self }
}
}
#[cfg(feature = "test-util")]
impl RazorpayClient {
pub async fn get_public<Q, R>(&self, path: &str, query: Option<&Q>) -> Result<R, RazorpayError>
where
Q: Serialize + ?Sized,
R: DeserializeOwned,
{
self.get(path, query).await
}
pub async fn post_public<B, R>(&self, path: &str, body: Option<&B>) -> Result<R, RazorpayError>
where
B: Serialize + ?Sized,
R: DeserializeOwned,
{
self.post(path, body).await
}
pub async fn patch_public<B, R>(&self, path: &str, body: Option<&B>) -> Result<R, RazorpayError>
where
B: Serialize + ?Sized,
R: DeserializeOwned,
{
self.patch(path, body).await
}
pub async fn put_public<B, R>(&self, path: &str, body: Option<&B>) -> Result<R, RazorpayError>
where
B: Serialize + ?Sized,
R: DeserializeOwned,
{
self.put(path, body).await
}
pub async fn delete_public<R>(&self, path: &str) -> Result<R, RazorpayError>
where
R: DeserializeOwned,
{
self.delete(path).await
}
}
#[cfg(test)]
mod send_sync_check {
use super::*;
const fn assert_send_sync<T: Send + Sync + 'static>() {}
const _: () = assert_send_sync::<RazorpayClient>();
const _: () = assert_send_sync::<AuthMethod>();
}