Skip to main content

razorpay_api/resources/
refunds.rs

1//! Refunds — returning money for a captured payment.
2
3use serde::{Deserialize, Serialize};
4
5use crate::client::RazorpayClient;
6use crate::error::RazorpayError;
7use crate::resources::common::{Notes, NotesUpdate};
8use crate::util::pagination::{Collection, ListOptions};
9
10/// How quickly a refund is processed.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum RefundSpeed {
14    /// Processed at the normal rate, at no extra cost.
15    Normal,
16    /// Processed immediately where the instrument supports it; carries a fee.
17    Optimum,
18    /// A speed this crate does not model yet.
19    #[serde(other)]
20    Unknown,
21}
22
23/// Lifecycle state of a [`Refund`].
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum RefundState {
27    /// Queued but not yet sent to the bank.
28    Pending,
29    /// The refund completed.
30    Processed,
31    /// The refund failed and the money stayed with you.
32    Failed,
33    /// A state this crate does not model yet.
34    #[serde(other)]
35    Unknown,
36}
37
38/// A refund returned by the API.
39#[derive(Debug, Clone, PartialEq, Deserialize)]
40pub struct Refund {
41    /// Unique identifier, e.g. `rfnd_FgRAHdNOM4ZVbO`.
42    pub id: String,
43    /// Always `"refund"`.
44    #[serde(default)]
45    pub entity: String,
46    /// Amount refunded, in the smallest currency unit.
47    pub amount: i64,
48    /// ISO 4217 currency code.
49    pub currency: String,
50    /// The payment this refund is against.
51    pub payment_id: String,
52    /// Current state.
53    #[serde(default)]
54    pub status: Option<RefundState>,
55    /// Speed requested at creation.
56    #[serde(default)]
57    pub speed_requested: Option<RefundSpeed>,
58    /// Speed actually used.
59    #[serde(default)]
60    pub speed_processed: Option<RefundSpeed>,
61    /// Your reference for this refund.
62    #[serde(default)]
63    pub receipt: Option<String>,
64    /// Reference number to share with the customer for tracing.
65    #[serde(default)]
66    pub acquirer_data: Option<serde_json::Value>,
67    /// The batch this refund belonged to, for bulk refunds.
68    #[serde(default)]
69    pub batch_id: Option<String>,
70    /// Your metadata.
71    #[serde(default)]
72    pub notes: Notes,
73    /// Creation time as a Unix timestamp in seconds.
74    pub created_at: i64,
75}
76
77/// Parameters for creating a refund.
78///
79/// Construct with [`full`](Self::full) or [`partial`](Self::partial) — the
80/// difference is only whether `amount` is sent.
81#[derive(Debug, Clone, Default, PartialEq, Serialize)]
82pub struct CreateRefundParams {
83    /// Amount to refund in the smallest unit. Omitted means refund everything.
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub amount: Option<i64>,
86    /// Requested processing speed.
87    #[serde(skip_serializing_if = "Option::is_none")]
88    pub speed: Option<RefundSpeed>,
89    /// Your reference for this refund.
90    #[serde(skip_serializing_if = "Option::is_none")]
91    pub receipt: Option<String>,
92    /// Metadata to attach.
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub notes: Option<Notes>,
95}
96
97impl CreateRefundParams {
98    /// Refund the payment's entire remaining amount.
99    ///
100    /// ```
101    /// use razorpay_api::resources::CreateRefundParams;
102    /// assert!(CreateRefundParams::full().amount.is_none());
103    /// ```
104    pub fn full() -> Self {
105        Self::default()
106    }
107
108    /// Refund only `amount`, in the smallest currency unit.
109    ///
110    /// ```
111    /// use razorpay_api::resources::CreateRefundParams;
112    /// assert_eq!(CreateRefundParams::partial(10_000).amount, Some(10_000));
113    /// ```
114    pub fn partial(amount: i64) -> Self {
115        Self {
116            amount: Some(amount),
117            ..Self::default()
118        }
119    }
120
121    /// Request a specific processing speed.
122    pub fn speed(mut self, speed: RefundSpeed) -> Self {
123        self.speed = Some(speed);
124        self
125    }
126
127    /// Attach your own reference.
128    pub fn receipt(mut self, receipt: impl Into<String>) -> Self {
129        self.receipt = Some(receipt.into());
130        self
131    }
132
133    /// Attach metadata.
134    pub fn notes(mut self, notes: Notes) -> Self {
135        self.notes = Some(notes);
136        self
137    }
138}
139
140/// Refund endpoints. Obtain one from [`RazorpayClient::refunds`].
141///
142/// Creating a refund lives on the payment it belongs to:
143/// [`PaymentsClient::refund`](crate::resources::payments::PaymentsClient::refund).
144pub struct RefundsClient<'a> {
145    pub(crate) client: &'a RazorpayClient,
146}
147
148impl<'a> RefundsClient<'a> {
149    /// Fetch one refund by id — `GET /v1/refunds/{id}`.
150    pub async fn fetch(&self, id: &str) -> Result<Refund, RazorpayError> {
151        self.client.get::<(), _>(&format!("refunds/{id}"), None).await
152    }
153
154    /// List all refunds across payments — `GET /v1/refunds`.
155    pub async fn all(&self, options: ListOptions) -> Result<Collection<Refund>, RazorpayError> {
156        self.client.get("refunds", Some(&options)).await
157    }
158
159    /// Replace a refund's notes — `PATCH /v1/refunds/{id}`.
160    pub async fn edit(&self, id: &str, notes: Notes) -> Result<Refund, RazorpayError> {
161        self.client
162            .patch(&format!("refunds/{id}"), Some(&NotesUpdate::new(notes)))
163            .await
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    #[test]
172    fn full_refund_omits_amount() {
173        assert_eq!(serde_json::to_string(&CreateRefundParams::full()).unwrap(), "{}");
174    }
175
176    #[test]
177    fn partial_refund_sends_amount() {
178        let json = serde_json::to_string(&CreateRefundParams::partial(500)).unwrap();
179        assert_eq!(json, r#"{"amount":500}"#);
180    }
181
182    #[test]
183    fn speed_serializes_snake_case() {
184        let json =
185            serde_json::to_string(&CreateRefundParams::full().speed(RefundSpeed::Optimum)).unwrap();
186        assert_eq!(json, r#"{"speed":"optimum"}"#);
187    }
188}