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