Skip to main content

razorpay_api/resources/
subscriptions.rs

1//! Subscriptions — recurring charges against a [`Plan`](crate::resources::plans::Plan).
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/// Lifecycle state of a [`Subscription`].
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum SubscriptionStatus {
14    /// Created but the customer has not yet authorized it.
15    Created,
16    /// Waiting on the customer to complete authentication.
17    Authenticated,
18    /// Billing normally.
19    Active,
20    /// Paused; no charges are attempted.
21    Paused,
22    /// A charge failed and Razorpay is retrying.
23    Pending,
24    /// Retries exhausted.
25    Halted,
26    /// Ran to its scheduled end.
27    Completed,
28    /// Cancelled before completing.
29    Cancelled,
30    /// Expired without being authorized.
31    Expired,
32    /// A status this crate does not model yet.
33    #[serde(other)]
34    Unknown,
35}
36
37/// A subscription returned by the API.
38#[derive(Debug, Clone, PartialEq, Deserialize)]
39pub struct Subscription {
40    /// Unique identifier, e.g. `sub_00000000000001`.
41    pub id: String,
42    /// Always `"subscription"`.
43    #[serde(default)]
44    pub entity: String,
45    /// The plan being billed.
46    pub plan_id: String,
47    /// Current lifecycle state.
48    pub status: SubscriptionStatus,
49    /// The customer being billed.
50    #[serde(default)]
51    pub customer_id: Option<String>,
52    /// Total billing cycles scheduled.
53    #[serde(default)]
54    pub total_count: u32,
55    /// Cycles billed so far.
56    #[serde(default)]
57    pub paid_count: u32,
58    /// Cycles remaining.
59    #[serde(default)]
60    pub remaining_count: u32,
61    /// How many charges have failed.
62    #[serde(default)]
63    pub auth_attempts: u32,
64    /// Quantity of the plan being billed each cycle.
65    #[serde(default)]
66    pub quantity: u32,
67    /// URL where the customer authorizes the subscription.
68    #[serde(default)]
69    pub short_url: Option<String>,
70    /// Whether Razorpay sends the customer notifications.
71    #[serde(default)]
72    pub customer_notify: bool,
73    /// Start of the current billing cycle, Unix seconds.
74    #[serde(default)]
75    pub current_start: Option<i64>,
76    /// End of the current billing cycle, Unix seconds.
77    #[serde(default)]
78    pub current_end: Option<i64>,
79    /// When the subscription began, Unix seconds.
80    #[serde(default)]
81    pub start_at: Option<i64>,
82    /// When the subscription is scheduled to end, Unix seconds.
83    #[serde(default)]
84    pub end_at: Option<i64>,
85    /// When it was actually ended, Unix seconds.
86    #[serde(default)]
87    pub ended_at: Option<i64>,
88    /// When the trial period ends, Unix seconds.
89    #[serde(default)]
90    pub expire_by: Option<i64>,
91    /// When it was charged most recently, Unix seconds.
92    #[serde(default)]
93    pub charge_at: Option<i64>,
94    /// Any one-off charges added on top of the plan.
95    #[serde(default)]
96    pub addons: Vec<serde_json::Value>,
97    /// Your metadata.
98    #[serde(default)]
99    pub notes: Notes,
100    /// Creation time as a Unix timestamp in seconds.
101    #[serde(default)]
102    pub created_at: i64,
103}
104
105impl Subscription {
106    /// Whether the subscription is currently billing.
107    pub fn is_active(&self) -> bool {
108        matches!(self.status, SubscriptionStatus::Active)
109    }
110}
111
112/// Parameters for creating a [`Subscription`].
113#[derive(Debug, Clone, PartialEq, Serialize)]
114pub struct CreateSubscriptionParams {
115    /// The plan to bill against.
116    pub plan_id: String,
117    /// How many cycles to bill before completing.
118    pub total_count: u32,
119    /// Quantity of the plan per cycle.
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub quantity: Option<u32>,
122    /// Whether Razorpay should email/SMS the customer.
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub customer_notify: Option<u8>,
125    /// When to start billing, Unix seconds. Omitted means immediately.
126    #[serde(skip_serializing_if = "Option::is_none")]
127    pub start_at: Option<i64>,
128    /// Deadline for the customer to authorize, Unix seconds.
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub expire_by: Option<i64>,
131    /// Cycles to skip charging at the start, for a free trial.
132    #[serde(skip_serializing_if = "Option::is_none")]
133    pub customer_id: Option<String>,
134    /// Metadata to attach.
135    #[serde(skip_serializing_if = "Option::is_none")]
136    pub notes: Option<Notes>,
137}
138
139impl CreateSubscriptionParams {
140    /// Bill `plan_id` for `total_count` cycles.
141    pub fn new(plan_id: impl Into<String>, total_count: u32) -> Self {
142        Self {
143            plan_id: plan_id.into(),
144            total_count,
145            quantity: None,
146            customer_notify: None,
147            start_at: None,
148            expire_by: None,
149            customer_id: None,
150            notes: None,
151        }
152    }
153
154    /// Bill an existing customer.
155    pub fn customer_id(mut self, customer_id: impl Into<String>) -> Self {
156        self.customer_id = Some(customer_id.into());
157        self
158    }
159
160    /// Bill more than one unit of the plan per cycle.
161    pub fn quantity(mut self, quantity: u32) -> Self {
162        self.quantity = Some(quantity);
163        self
164    }
165
166    /// Delay the first charge until this Unix timestamp.
167    pub fn start_at(mut self, start_at: i64) -> Self {
168        self.start_at = Some(start_at);
169        self
170    }
171
172    /// Let Razorpay notify the customer about this subscription.
173    pub fn customer_notify(mut self, notify: bool) -> Self {
174        self.customer_notify = Some(u8::from(notify));
175        self
176    }
177
178    /// Attach metadata.
179    pub fn notes(mut self, notes: Notes) -> Self {
180        self.notes = Some(notes);
181        self
182    }
183}
184
185/// Body for [`SubscriptionsClient::cancel`].
186#[derive(Debug, Clone, PartialEq, Serialize)]
187struct CancelParams {
188    cancel_at_cycle_end: u8,
189}
190
191/// Body for [`SubscriptionsClient::pause`] and [`SubscriptionsClient::resume`].
192#[derive(Debug, Clone, PartialEq, Serialize)]
193struct PauseResumeParams {
194    #[serde(skip_serializing_if = "Option::is_none")]
195    pause_at: Option<&'static str>,
196    #[serde(skip_serializing_if = "Option::is_none")]
197    resume_at: Option<&'static str>,
198}
199
200/// Subscription endpoints. Obtain one from [`RazorpayClient::subscriptions`].
201pub struct SubscriptionsClient<'a> {
202    pub(crate) client: &'a RazorpayClient,
203}
204
205impl<'a> SubscriptionsClient<'a> {
206    /// Create a subscription — `POST /v1/subscriptions`.
207    ///
208    /// The returned [`Subscription::short_url`] is where the customer authorizes
209    /// recurring charges; nothing is billed until they do.
210    pub async fn create(
211        &self,
212        params: CreateSubscriptionParams,
213    ) -> Result<Subscription, RazorpayError> {
214        self.client.post("subscriptions", Some(&params)).await
215    }
216
217    /// Fetch one subscription by id — `GET /v1/subscriptions/{id}`.
218    pub async fn fetch(&self, id: &str) -> Result<Subscription, RazorpayError> {
219        self.client
220            .get::<(), _>(&format!("subscriptions/{id}"), None)
221            .await
222    }
223
224    /// List subscriptions — `GET /v1/subscriptions`.
225    pub async fn all(
226        &self,
227        options: ListOptions,
228    ) -> Result<Collection<Subscription>, RazorpayError> {
229        self.client.get("subscriptions", Some(&options)).await
230    }
231
232    /// Cancel a subscription — `POST /v1/subscriptions/{id}/cancel`.
233    ///
234    /// `at_cycle_end` of `true` lets the customer keep access through the period
235    /// they already paid for; `false` cancels immediately.
236    pub async fn cancel(
237        &self,
238        id: &str,
239        at_cycle_end: bool,
240    ) -> Result<Subscription, RazorpayError> {
241        let body = CancelParams {
242            cancel_at_cycle_end: u8::from(at_cycle_end),
243        };
244        self.client
245            .post(&format!("subscriptions/{id}/cancel"), Some(&body))
246            .await
247    }
248
249    /// Pause a subscription — `POST /v1/subscriptions/{id}/pause`.
250    ///
251    /// Charging stops until [`resume`](Self::resume); the schedule is not extended.
252    pub async fn pause(&self, id: &str) -> Result<Subscription, RazorpayError> {
253        let body = PauseResumeParams {
254            pause_at: Some("now"),
255            resume_at: None,
256        };
257        self.client
258            .post(&format!("subscriptions/{id}/pause"), Some(&body))
259            .await
260    }
261
262    /// Resume a paused subscription — `POST /v1/subscriptions/{id}/resume`.
263    pub async fn resume(&self, id: &str) -> Result<Subscription, RazorpayError> {
264        let body = PauseResumeParams {
265            pause_at: None,
266            resume_at: Some("now"),
267        };
268        self.client
269            .post(&format!("subscriptions/{id}/resume"), Some(&body))
270            .await
271    }
272
273    /// Replace a subscription's notes — `PATCH /v1/subscriptions/{id}`.
274    pub async fn edit(&self, id: &str, notes: Notes) -> Result<Subscription, RazorpayError> {
275        self.client
276            .patch(&format!("subscriptions/{id}"), Some(&NotesUpdate::new(notes)))
277            .await
278    }
279
280    /// List invoices raised for a subscription — `GET /v1/invoices?subscription_id={id}`.
281    pub async fn invoices(
282        &self,
283        id: &str,
284    ) -> Result<Collection<crate::resources::invoices::Invoice>, RazorpayError> {
285        #[derive(Serialize)]
286        struct Query<'q> {
287            subscription_id: &'q str,
288        }
289        self.client
290            .get("invoices", Some(&Query { subscription_id: id }))
291            .await
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn create_omits_unset_fields() {
301        let json = serde_json::to_string(&CreateSubscriptionParams::new("plan_1", 12)).unwrap();
302        assert_eq!(json, r#"{"plan_id":"plan_1","total_count":12}"#);
303    }
304
305    #[test]
306    fn customer_notify_maps_bool_to_int() {
307        let json = serde_json::to_string(
308            &CreateSubscriptionParams::new("plan_1", 1).customer_notify(true),
309        )
310        .unwrap();
311        assert!(json.contains(r#""customer_notify":1"#));
312    }
313
314    #[test]
315    fn active_helper_reflects_status() {
316        let sub: Subscription = serde_json::from_str(
317            r#"{"id":"sub_1","plan_id":"plan_1","status":"active"}"#,
318        )
319        .unwrap();
320        assert!(sub.is_active());
321    }
322}