Skip to main content

razorpay_api/resources/
orders.rs

1//! Orders — the entity you create before opening Checkout.
2//!
3//! An order ties a payment attempt to an amount you control server-side. Creating
4//! one is the first step of nearly every Razorpay integration.
5
6use serde::{Deserialize, Serialize};
7
8use crate::client::RazorpayClient;
9use crate::error::RazorpayError;
10use crate::resources::common::{Notes, NotesUpdate};
11use crate::resources::payments::Payment;
12use crate::util::pagination::{Collection, ListOptions};
13
14/// Lifecycle state of an [`Order`].
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum OrderStatus {
18    /// Created but not yet paid against.
19    Created,
20    /// At least one payment was attempted and failed.
21    Attempted,
22    /// Paid in full.
23    Paid,
24    /// A status this crate does not model yet.
25    #[serde(other)]
26    Unknown,
27}
28
29/// An order returned by the API.
30#[derive(Debug, Clone, PartialEq, Deserialize)]
31pub struct Order {
32    /// Unique identifier, e.g. `order_EKwxwAgItmmXdp`.
33    pub id: String,
34    /// Always `"order"`.
35    #[serde(default)]
36    pub entity: String,
37    /// Amount in the currency's smallest unit (paise for INR).
38    pub amount: i64,
39    /// Amount already paid, in the smallest unit.
40    #[serde(default)]
41    pub amount_paid: i64,
42    /// Amount still outstanding, in the smallest unit.
43    #[serde(default)]
44    pub amount_due: i64,
45    /// ISO 4217 currency code, e.g. `INR`.
46    pub currency: String,
47    /// Your own reference for this order, if you set one.
48    #[serde(default)]
49    pub receipt: Option<String>,
50    /// Current lifecycle state.
51    pub status: OrderStatus,
52    /// Number of payment attempts made against this order.
53    #[serde(default)]
54    pub attempts: u32,
55    /// Your metadata.
56    #[serde(default)]
57    pub notes: Notes,
58    /// Creation time as a Unix timestamp in seconds.
59    pub created_at: i64,
60}
61
62/// Parameters for [`OrdersClient::create`].
63///
64/// Build with [`CreateOrderParams::new`], which takes the two required fields.
65#[derive(Debug, Clone, PartialEq, Serialize)]
66pub struct CreateOrderParams {
67    /// Amount in the smallest currency unit (paise for INR). Minimum is 100 (₹1).
68    pub amount: i64,
69    /// ISO 4217 currency code, e.g. `INR`.
70    pub currency: String,
71    /// Your own reference, typically an internal order id. Max 40 characters.
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub receipt: Option<String>,
74    /// Metadata to attach; echoed back on the [`Order`] and in webhooks.
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub notes: Option<Notes>,
77    /// Whether to capture automatically (`0`) or require explicit capture (`1`).
78    ///
79    /// Razorpay encodes this as an integer; see [`CreateOrderParams::manual_capture`].
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub payment_capture: Option<u8>,
82    /// Restrict this order to a single [`crate::resources::common::PaymentMethod`].
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub method: Option<String>,
85}
86
87impl CreateOrderParams {
88    /// A new order for `amount` in the smallest unit of `currency`.
89    ///
90    /// # Examples
91    ///
92    /// ```
93    /// use razorpay_api::resources::CreateOrderParams;
94    ///
95    /// // ₹500.00 — amounts are in paise, never rupees.
96    /// let params = CreateOrderParams::new(50_000, "INR");
97    /// assert_eq!(params.amount, 50_000);
98    /// ```
99    pub fn new(amount: i64, currency: impl Into<String>) -> Self {
100        Self {
101            amount,
102            currency: currency.into(),
103            receipt: None,
104            notes: None,
105            payment_capture: None,
106            method: None,
107        }
108    }
109
110    /// Attach your own reference to this order.
111    pub fn receipt(mut self, receipt: impl Into<String>) -> Self {
112        self.receipt = Some(receipt.into());
113        self
114    }
115
116    /// Attach metadata.
117    pub fn notes(mut self, notes: Notes) -> Self {
118        self.notes = Some(notes);
119        self
120    }
121
122    /// Require an explicit [`capture`](crate::resources::payments::PaymentsClient::capture)
123    /// instead of capturing automatically.
124    ///
125    /// Uncaptured payments are auto-refunded by Razorpay after a window, so only
126    /// choose this if you really do capture later.
127    pub fn manual_capture(mut self) -> Self {
128        self.payment_capture = Some(0);
129        self
130    }
131
132    /// Restrict the order to a single payment method, e.g. `"upi"`.
133    pub fn method(mut self, method: impl Into<String>) -> Self {
134        self.method = Some(method.into());
135        self
136    }
137}
138
139/// Order endpoints. Obtain one from [`RazorpayClient::orders`].
140pub struct OrdersClient<'a> {
141    pub(crate) client: &'a RazorpayClient,
142}
143
144impl<'a> OrdersClient<'a> {
145    /// Create an order — `POST /v1/orders`.
146    ///
147    /// The returned [`Order::id`] is what you hand to Checkout on the front end.
148    ///
149    /// # Examples
150    ///
151    /// ```no_run
152    /// # use razorpay_api::{RazorpayClient, RazorpayError};
153    /// # use razorpay_api::resources::CreateOrderParams;
154    /// # async fn demo() -> Result<(), RazorpayError> {
155    /// let client = RazorpayClient::new("key_id".into(), "key_secret".into());
156    /// let order = client
157    ///     .orders()
158    ///     .create(CreateOrderParams::new(50_000, "INR").receipt("rcpt#1"))
159    ///     .await?;
160    /// println!("open checkout with {}", order.id);
161    /// # Ok(())
162    /// # }
163    /// ```
164    pub async fn create(&self, params: CreateOrderParams) -> Result<Order, RazorpayError> {
165        self.client.post("orders", Some(&params)).await
166    }
167
168    /// Fetch one order by id — `GET /v1/orders/{id}`.
169    pub async fn fetch(&self, id: &str) -> Result<Order, RazorpayError> {
170        self.client.get::<(), _>(&format!("orders/{id}"), None).await
171    }
172
173    /// List orders — `GET /v1/orders`.
174    ///
175    /// Pass [`ListOptions::default()`] when you do not need filtering.
176    pub async fn all(&self, options: ListOptions) -> Result<Collection<Order>, RazorpayError> {
177        self.client.get("orders", Some(&options)).await
178    }
179
180    /// List the payments made against an order — `GET /v1/orders/{id}/payments`.
181    ///
182    /// Useful when reconciling: a `paid` order has exactly one captured payment,
183    /// while an `attempted` order may have several failed ones.
184    pub async fn fetch_payments(&self, id: &str) -> Result<Collection<Payment>, RazorpayError> {
185        self.client
186            .get::<(), _>(&format!("orders/{id}/payments"), None)
187            .await
188    }
189
190    /// Replace an order's notes — `PATCH /v1/orders/{id}`.
191    ///
192    /// Notes are the only editable field, and the map replaces the existing one
193    /// rather than merging into it.
194    pub async fn edit(&self, id: &str, notes: Notes) -> Result<Order, RazorpayError> {
195        self.client
196            .patch(&format!("orders/{id}"), Some(&NotesUpdate::new(notes)))
197            .await
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204
205    #[test]
206    fn unset_optional_params_are_omitted() {
207        let json = serde_json::to_string(&CreateOrderParams::new(100, "INR")).unwrap();
208        assert_eq!(json, r#"{"amount":100,"currency":"INR"}"#);
209    }
210
211    #[test]
212    fn builder_sets_fields() {
213        let p = CreateOrderParams::new(100, "INR").receipt("r1").manual_capture();
214        assert_eq!(p.receipt.as_deref(), Some("r1"));
215        assert_eq!(p.payment_capture, Some(0));
216    }
217
218    #[test]
219    fn unknown_status_does_not_fail_decoding() {
220        // Razorpay shipping a new status must not break existing integrations.
221        let order: Order = serde_json::from_str(
222            r#"{"id":"order_1","amount":1,"currency":"INR","status":"brand_new","created_at":1}"#,
223        )
224        .unwrap();
225        assert_eq!(order.status, OrderStatus::Unknown);
226    }
227}