1use std::time::Duration;
2
3use reqwest::{Method, Url};
4use serde::Serialize;
5use serde::de::DeserializeOwned;
6
7use crate::error::{ApiErrorEnvelope, RazorpayError};
8
9const DEFAULT_BASE_URL: &str = "https://api.razorpay.com/v1/";
10const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
11const USER_AGENT: &str = concat!("razorpay-api-rust/", env!("CARGO_PKG_VERSION"));
12
13#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum AuthMethod {
20 BasicAuth {
22 api_key: String,
24 api_secret: String,
26 },
27 BearerToken {
29 token: String,
31 },
32}
33
34#[derive(Debug, Clone)]
50pub struct RazorpayClient {
51 http_client: reqwest::Client,
52 base_url: Url,
53 auth_method: AuthMethod,
54}
55
56impl RazorpayClient {
57 pub fn new(api_key: String, api_secret: String) -> Self {
73 Self::with_auth(AuthMethod::BasicAuth { api_key, api_secret })
74 }
75
76 pub fn new_with_bearer_token(token: String) -> Self {
78 Self::with_auth(AuthMethod::BearerToken { token })
79 }
80
81 pub fn base_url(&self) -> &Url {
83 &self.base_url
84 }
85
86 pub fn auth_method(&self) -> &AuthMethod {
90 &self.auth_method
91 }
92
93 fn with_auth(auth_method: AuthMethod) -> Self {
94 RazorpayClient {
95 http_client: reqwest::Client::builder()
96 .timeout(DEFAULT_TIMEOUT)
97 .user_agent(USER_AGENT)
98 .build()
99 .expect("failed to build HTTP client"),
100 base_url: DEFAULT_BASE_URL.parse().expect("Invalid base URL"),
101 auth_method,
102 }
103 }
104
105 pub fn with_base_url(mut self, base_url: Url) -> Self {
120 self.base_url = base_url;
121 self
122 }
123
124 fn url_for(&self, path: &str) -> Result<Url, RazorpayError> {
129 self.base_url
130 .join(path.trim_start_matches('/'))
131 .map_err(|e| RazorpayError::InvalidUrl(e.to_string()))
132 }
133
134 async fn request<Q, B, R>(
137 &self,
138 method: Method,
139 path: &str,
140 query: Option<&Q>,
141 body: Option<&B>,
142 ) -> Result<R, RazorpayError>
143 where
144 Q: Serialize + ?Sized,
145 B: Serialize + ?Sized,
146 R: DeserializeOwned,
147 {
148 let mut req = self.http_client.request(method, self.url_for(path)?);
149
150 req = match &self.auth_method {
151 AuthMethod::BasicAuth { api_key, api_secret } => {
152 req.basic_auth(api_key, Some(api_secret))
153 }
154 AuthMethod::BearerToken { token } => req.bearer_auth(token),
155 };
156
157 if let Some(query) = query {
158 req = req.query(query);
159 }
160 if let Some(body) = body {
161 req = req.json(body);
162 }
163
164 let response = req.send().await?;
165 let status = response.status();
166 let bytes = response.bytes().await?;
167
168 if let Ok(envelope) = serde_json::from_slice::<ApiErrorEnvelope>(&bytes) {
171 return Err(envelope.into_error(status));
172 }
173
174 if !status.is_success() {
175 return Err(RazorpayError::UnexpectedStatus {
178 http_status: status,
179 body: String::from_utf8_lossy(&bytes).into_owned(),
180 });
181 }
182
183 let bytes: &[u8] = if bytes.is_empty() { b"null" } else { &bytes };
186 Ok(serde_json::from_slice(bytes)?)
187 }
188
189 pub(crate) async fn get<Q, R>(&self, path: &str, query: Option<&Q>) -> Result<R, RazorpayError>
190 where
191 Q: Serialize + ?Sized,
192 R: DeserializeOwned,
193 {
194 self.request::<Q, (), R>(Method::GET, path, query, None).await
195 }
196
197 pub(crate) async fn post<B, R>(&self, path: &str, body: Option<&B>) -> Result<R, RazorpayError>
198 where
199 B: Serialize + ?Sized,
200 R: DeserializeOwned,
201 {
202 self.request::<(), B, R>(Method::POST, path, None, body).await
203 }
204
205 pub(crate) async fn patch<B, R>(&self, path: &str, body: Option<&B>) -> Result<R, RazorpayError>
206 where
207 B: Serialize + ?Sized,
208 R: DeserializeOwned,
209 {
210 self.request::<(), B, R>(Method::PATCH, path, None, body).await
211 }
212
213 pub(crate) async fn put<B, R>(&self, path: &str, body: Option<&B>) -> Result<R, RazorpayError>
214 where
215 B: Serialize + ?Sized,
216 R: DeserializeOwned,
217 {
218 self.request::<(), B, R>(Method::PUT, path, None, body).await
219 }
220
221 pub(crate) async fn delete<R>(&self, path: &str) -> Result<R, RazorpayError>
222 where
223 R: DeserializeOwned,
224 {
225 self.request::<(), (), R>(Method::DELETE, path, None, None).await
226 }
227}
228
229impl RazorpayClient {
235 pub fn orders(&self) -> crate::resources::orders::OrdersClient<'_> {
237 crate::resources::orders::OrdersClient { client: self }
238 }
239
240 pub fn payments(&self) -> crate::resources::payments::PaymentsClient<'_> {
242 crate::resources::payments::PaymentsClient { client: self }
243 }
244
245 pub fn refunds(&self) -> crate::resources::refunds::RefundsClient<'_> {
247 crate::resources::refunds::RefundsClient { client: self }
248 }
249
250 pub fn customers(&self) -> crate::resources::customers::CustomersClient<'_> {
252 crate::resources::customers::CustomersClient { client: self }
253 }
254
255 pub fn cards(&self) -> crate::resources::cards::CardsClient<'_> {
257 crate::resources::cards::CardsClient { client: self }
258 }
259
260 pub fn items(&self) -> crate::resources::items::ItemsClient<'_> {
262 crate::resources::items::ItemsClient { client: self }
263 }
264
265 pub fn plans(&self) -> crate::resources::plans::PlansClient<'_> {
267 crate::resources::plans::PlansClient { client: self }
268 }
269
270 pub fn subscriptions(&self) -> crate::resources::subscriptions::SubscriptionsClient<'_> {
272 crate::resources::subscriptions::SubscriptionsClient { client: self }
273 }
274
275 pub fn invoices(&self) -> crate::resources::invoices::InvoicesClient<'_> {
277 crate::resources::invoices::InvoicesClient { client: self }
278 }
279
280 pub fn payment_links(&self) -> crate::resources::payment_links::PaymentLinksClient<'_> {
282 crate::resources::payment_links::PaymentLinksClient { client: self }
283 }
284}
285
286#[cfg(feature = "test-util")]
289impl RazorpayClient {
290 pub async fn get_public<Q, R>(&self, path: &str, query: Option<&Q>) -> Result<R, RazorpayError>
292 where
293 Q: Serialize + ?Sized,
294 R: DeserializeOwned,
295 {
296 self.get(path, query).await
297 }
298
299 pub async fn post_public<B, R>(&self, path: &str, body: Option<&B>) -> Result<R, RazorpayError>
301 where
302 B: Serialize + ?Sized,
303 R: DeserializeOwned,
304 {
305 self.post(path, body).await
306 }
307
308 pub async fn patch_public<B, R>(&self, path: &str, body: Option<&B>) -> Result<R, RazorpayError>
310 where
311 B: Serialize + ?Sized,
312 R: DeserializeOwned,
313 {
314 self.patch(path, body).await
315 }
316
317 pub async fn put_public<B, R>(&self, path: &str, body: Option<&B>) -> Result<R, RazorpayError>
319 where
320 B: Serialize + ?Sized,
321 R: DeserializeOwned,
322 {
323 self.put(path, body).await
324 }
325
326 pub async fn delete_public<R>(&self, path: &str) -> Result<R, RazorpayError>
328 where
329 R: DeserializeOwned,
330 {
331 self.delete(path).await
332 }
333}
334
335#[cfg(test)]
336mod send_sync_check {
337 use super::*;
338 const fn assert_send_sync<T: Send + Sync + 'static>() {}
339 const _: () = assert_send_sync::<RazorpayClient>();
340 const _: () = assert_send_sync::<AuthMethod>();
341}