Skip to main content

razorpay_api/
client.rs

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/// How the client authenticates.
14///
15/// An enum rather than two `Option` fields: two `Option`s make four states, of
16/// which two ("both set" and "neither set") are invalid. This makes those
17/// unrepresentable.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum AuthMethod {
20    /// HTTP Basic auth with an API key pair — the usual mode.
21    BasicAuth {
22        /// The key id from your Razorpay dashboard.
23        api_key: String,
24        /// The matching key secret.
25        api_secret: String,
26    },
27    /// Bearer token auth, used for OAuth-issued access tokens.
28    BearerToken {
29        /// The access token.
30        token: String,
31    },
32}
33
34/// The entry point to the API.
35///
36/// Construct one at startup and share it. [`reqwest::Client`] holds a connection
37/// pool internally, so building a client per request discards pooling and TLS
38/// session reuse and will exhaust sockets under load. Cloning is cheap — the
39/// underlying HTTP client is reference-counted.
40///
41/// # Examples
42///
43/// ```
44/// use razorpay_api::RazorpayClient;
45///
46/// let client = RazorpayClient::new("rzp_test_key".into(), "secret".into());
47/// assert_eq!(client.base_url().as_str(), "https://api.razorpay.com/v1/");
48/// ```
49#[derive(Debug, Clone)]
50pub struct RazorpayClient {
51    http_client: reqwest::Client,
52    base_url: Url,
53    auth_method: AuthMethod,
54}
55
56impl RazorpayClient {
57    /// A client authenticating with an API key pair.
58    ///
59    /// Get these from the Razorpay dashboard. Keep the secret out of source
60    /// control — read it from the environment or a secret manager.
61    ///
62    /// # Examples
63    ///
64    /// ```no_run
65    /// use razorpay_api::RazorpayClient;
66    ///
67    /// let client = RazorpayClient::new(
68    ///     std::env::var("RAZORPAY_KEY_ID").unwrap(),
69    ///     std::env::var("RAZORPAY_KEY_SECRET").unwrap(),
70    /// );
71    /// ```
72    pub fn new(api_key: String, api_secret: String) -> Self {
73        Self::with_auth(AuthMethod::BasicAuth { api_key, api_secret })
74    }
75
76    /// A client authenticating with an OAuth access token.
77    pub fn new_with_bearer_token(token: String) -> Self {
78        Self::with_auth(AuthMethod::BearerToken { token })
79    }
80
81    /// The base URL requests are sent to.
82    pub fn base_url(&self) -> &Url {
83        &self.base_url
84    }
85
86    /// The configured authentication method.
87    ///
88    /// Note this exposes the key secret; avoid logging the result.
89    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    /// Point the client at a different host.
106    ///
107    /// Exists so the crate is testable without network access: point it at a mock
108    /// server and every request goes there instead. Keep the trailing slash —
109    /// [`Url::join`] discards the last path segment without one.
110    ///
111    /// # Examples
112    ///
113    /// ```
114    /// # use razorpay_api::RazorpayClient;
115    /// let client = RazorpayClient::new("k".into(), "s".into())
116    ///     .with_base_url("http://127.0.0.1:8080/v1/".parse().unwrap());
117    /// assert_eq!(client.base_url().as_str(), "http://127.0.0.1:8080/v1/");
118    /// ```
119    pub fn with_base_url(mut self, base_url: Url) -> Self {
120        self.base_url = base_url;
121        self
122    }
123
124    /// Join a resource path onto the base URL.
125    ///
126    /// `Url::join` treats a leading `/` as absolute (discarding any base path), so
127    /// paths are trimmed and the base is kept trailing-slashed at construction.
128    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    /// The single place every API call funnels through: auth, query, body, send,
135    /// status check, then parse.
136    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        // Razorpay sometimes answers 200 with an error envelope, so the body is
169        // probed for one regardless of status rather than trusting the code alone.
170        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            // Non-2xx that didn't carry a parseable envelope — surface the raw body
176            // instead of a misleading `Decode` error.
177            return Err(RazorpayError::UnexpectedStatus {
178                http_status: status,
179                body: String::from_utf8_lossy(&bytes).into_owned(),
180            });
181        }
182
183        // A 204 (and some DELETEs) return an empty body; `()` and `Option<T>` still
184        // need valid JSON, so an empty body is normalized to `null`.
185        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
229/// Resource accessors.
230///
231/// Each returns a zero-cost borrowing view rather than an owned client, so
232/// `client.orders().fetch(id)` allocates nothing and the whole API does not
233/// collapse into a hundred flat methods on [`RazorpayClient`].
234impl RazorpayClient {
235    /// [Orders](crate::resources::orders) — create these before opening Checkout.
236    pub fn orders(&self) -> crate::resources::orders::OrdersClient<'_> {
237        crate::resources::orders::OrdersClient { client: self }
238    }
239
240    /// [Payments](crate::resources::payments) — fetch, capture, and refund.
241    pub fn payments(&self) -> crate::resources::payments::PaymentsClient<'_> {
242        crate::resources::payments::PaymentsClient { client: self }
243    }
244
245    /// [Refunds](crate::resources::refunds) — fetch and list issued refunds.
246    pub fn refunds(&self) -> crate::resources::refunds::RefundsClient<'_> {
247        crate::resources::refunds::RefundsClient { client: self }
248    }
249
250    /// [Customers](crate::resources::customers) — saved payer identities.
251    pub fn customers(&self) -> crate::resources::customers::CustomersClient<'_> {
252        crate::resources::customers::CustomersClient { client: self }
253    }
254
255    /// [Cards](crate::resources::cards) — read card details behind a payment.
256    pub fn cards(&self) -> crate::resources::cards::CardsClient<'_> {
257        crate::resources::cards::CardsClient { client: self }
258    }
259
260    /// [Items](crate::resources::items) — reusable priced line items.
261    pub fn items(&self) -> crate::resources::items::ItemsClient<'_> {
262        crate::resources::items::ItemsClient { client: self }
263    }
264
265    /// [Plans](crate::resources::plans) — billing cadences for subscriptions.
266    pub fn plans(&self) -> crate::resources::plans::PlansClient<'_> {
267        crate::resources::plans::PlansClient { client: self }
268    }
269
270    /// [Subscriptions](crate::resources::subscriptions) — recurring billing.
271    pub fn subscriptions(&self) -> crate::resources::subscriptions::SubscriptionsClient<'_> {
272        crate::resources::subscriptions::SubscriptionsClient { client: self }
273    }
274
275    /// [Invoices](crate::resources::invoices) — itemized requests for payment.
276    pub fn invoices(&self) -> crate::resources::invoices::InvoicesClient<'_> {
277        crate::resources::invoices::InvoicesClient { client: self }
278    }
279
280    /// [Payment links](crate::resources::payment_links) — shareable payment URLs.
281    pub fn payment_links(&self) -> crate::resources::payment_links::PaymentLinksClient<'_> {
282        crate::resources::payment_links::PaymentLinksClient { client: self }
283    }
284}
285
286/// Public mirrors of the private wrappers, for integration tests only. Enabled by
287/// the `test-util` feature so the real surface stays crate-private.
288#[cfg(feature = "test-util")]
289impl RazorpayClient {
290    /// Issue a raw `GET`. Test-only; use the resource accessors instead.
291    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    /// Issue a raw `POST`. Test-only; use the resource accessors instead.
300    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    /// Issue a raw `PATCH`. Test-only; use the resource accessors instead.
309    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    /// Issue a raw `PUT`. Test-only; use the resource accessors instead.
318    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    /// Issue a raw `DELETE`. Test-only; use the resource accessors instead.
327    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}