1
+//! Auto-renewing subscriptions through the Play monetization API
2
+//! (`monetization.subscriptions`).
3
+//!
4
+//! Like one-time products these are not inside an edit. A subscription is
5
+//! created with one base plan, priced in every region from one price via
6
+//! `pricing:convertRegionPrices`, and is not sold until that base plan is
7
+//! activated.
8
+//!
9
+//! The API has no field for the subscription's icon: Play Console's "Icon"
10
+//! upload has no API counterpart (checked against the v3 discovery document),
11
+//! so icons stay a Console step.
12
+
13
+use serde_json::{json, Value};
14
+
15
+use crate::error::{Error, Result};
16
+use crate::product::{regions_version, Money};
17
+
18
+pub const TITLE_MAX_LEN: usize = 55;
19
+pub const DESCRIPTION_MAX_LEN: usize = 200;
20
+pub const BENEFIT_MAX_LEN: usize = 40;
21
+pub const BENEFITS_MAX: usize = 4;
22
+
23
+/// What a new subscription says about itself.
24
+#[derive(Debug, Clone)]
25
+pub struct NewSubscription {
26
+ pub package: String,
27
+ pub product_id: String,
28
+ pub language: String,
29
+ pub title: String,
30
+ pub description: Option<String>,
31
+ pub benefits: Vec<String>,
32
+ pub base_plan_id: String,
33
+ /// ISO 8601, for example `P1M`.
34
+ pub billing_period: String,
35
+ /// ISO 8601 grace period after a failed renewal, for example `P3D`.
36
+ /// `None` leaves Play's default.
37
+ pub grace_period: Option<String>,
38
+}
39
+
40
+fn valid_id(id: &str, max: usize, allow_dot: bool) -> bool {
41
+ !id.is_empty()
42
+ && id.len() <= max
43
+ && id
44
+ .chars()
45
+ .next()
46
+ .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
47
+ && id.chars().all(|c| {
48
+ c.is_ascii_lowercase()
49
+ || c.is_ascii_digit()
50
+ || c == '_'
51
+ || c == '-'
52
+ || (allow_dot && c == '.')
53
+ })
54
+}
55
+
56
+fn check_len(name: &str, value: &str, max: usize) -> Result<()> {
57
+ let len = value.chars().count();
58
+ if len == 0 || len > max {
59
+ return Err(Error::Invalid(format!(
60
+ "{name} must be 1 to {max} characters (got {len})"
61
+ )));
62
+ }
63
+ Ok(())
64
+}
65
+
66
+impl NewSubscription {
67
+ pub fn check(&self) -> Result<()> {
68
+ if !valid_id(&self.product_id, 100, true) {
69
+ return Err(Error::Invalid(format!(
70
+ "product id {:?}: use lowercase letters, digits, _ . - (starting with a letter or digit)",
71
+ self.product_id
72
+ )));
73
+ }
74
+ // Base plan ids allow no dots and at most 63 characters.
75
+ if !valid_id(&self.base_plan_id, 63, false) {
76
+ return Err(Error::Invalid(format!(
77
+ "base plan id {:?}: use lowercase letters, digits and - (starting with a letter or digit)",
78
+ self.base_plan_id
79
+ )));
80
+ }
81
+ check_len("title", &self.title, TITLE_MAX_LEN)?;
82
+ if let Some(description) = &self.description {
83
+ check_len("description", description, DESCRIPTION_MAX_LEN)?;
84
+ }
85
+ if self.benefits.len() > BENEFITS_MAX {
86
+ return Err(Error::Invalid(format!(
87
+ "at most {BENEFITS_MAX} benefits (got {})",
88
+ self.benefits.len()
89
+ )));
90
+ }
91
+ for benefit in &self.benefits {
92
+ check_len("each benefit", benefit, BENEFIT_MAX_LEN)?;
93
+ }
94
+ if !self.billing_period.starts_with('P') {
95
+ return Err(Error::Invalid(format!(
96
+ "billing period {:?} is not ISO 8601 (expected e.g. P1M)",
97
+ self.billing_period
98
+ )));
99
+ }
100
+ Ok(())
101
+ }
102
+}
103
+
104
+/// The `Subscription` body for `monetization.subscriptions.create`: one
105
+/// listing and one auto-renewing base plan, priced in every region from a
106
+/// `pricing:convertRegionPrices` answer. The base plan is created in draft;
107
+/// activate it to start selling.
108
+pub fn subscription_body(subscription: &NewSubscription, converted: &Value) -> Result<Value> {
109
+ let regions = converted
110
+ .get("convertedRegionPrices")
111
+ .and_then(Value::as_object)
112
+ .filter(|m| !m.is_empty())
113
+ .ok_or_else(|| Error::Invalid("Play returned no regional prices".to_string()))?;
114
+ let mut configs: Vec<Value> = regions
115
+ .iter()
116
+ .filter_map(|(code, entry)| {
117
+ let price = entry.get("price")?;
118
+ Some(json!({ "regionCode": code, "price": price, "newSubscriberAvailability": true }))
119
+ })
120
+ .collect();
121
+ configs.sort_by(|a, b| a["regionCode"].as_str().cmp(&b["regionCode"].as_str()));
122
+
123
+ let mut base_plan = json!({
124
+ "basePlanId": subscription.base_plan_id,
125
+ "autoRenewingBasePlanType": {
126
+ "billingPeriodDuration": subscription.billing_period,
127
+ "legacyCompatible": true,
128
+ "resubscribeState": "RESUBSCRIBE_STATE_ACTIVE",
129
+ "prorationMode": "SUBSCRIPTION_PRORATION_MODE_CHARGE_ON_NEXT_BILLING_DATE",
130
+ },
131
+ "regionalConfigs": configs,
132
+ });
133
+ if let Some(grace) = &subscription.grace_period {
134
+ base_plan["autoRenewingBasePlanType"]["gracePeriodDuration"] = json!(grace);
135
+ }
136
+ if let Some(other) = converted.get("convertedOtherRegionsPrice") {
137
+ base_plan["otherRegionsConfig"] = json!({
138
+ "usdPrice": other.get("usdPrice").cloned().unwrap_or(Value::Null),
139
+ "eurPrice": other.get("eurPrice").cloned().unwrap_or(Value::Null),
140
+ "newSubscriberAvailability": true,
141
+ });
142
+ }
143
+
144
+ let mut listing = json!({
145
+ "languageCode": subscription.language,
146
+ "title": subscription.title,
147
+ });
148
+ if let Some(description) = &subscription.description {
149
+ listing["description"] = json!(description);
150
+ }
151
+ if !subscription.benefits.is_empty() {
152
+ listing["benefits"] = json!(subscription.benefits);
153
+ }
154
+
155
+ Ok(json!({
156
+ "packageName": subscription.package,
157
+ "productId": subscription.product_id,
158
+ "listings": [listing],
159
+ "basePlans": [base_plan],
160
+ }))
161
+}
162
+
163
+/// The `basePlans.activate` request body.
164
+pub fn activate_body(package: &str, product_id: &str, base_plan_id: &str) -> Value {
165
+ json!({ "packageName": package, "productId": product_id, "basePlanId": base_plan_id })
166
+}
167
+
168
+/// The regions version Play priced the conversion against.
169
+pub fn converted_regions_version(converted: &Value) -> Result<String> {
170
+ regions_version(converted)
171
+}
172
+
173
+/// A compact row for `subscriptions list`: id, title, and each base plan with
174
+/// its state and period.
175
+pub fn summary(subscription: &Value) -> Value {
176
+ let plans: Vec<Value> = subscription
177
+ .get("basePlans")
178
+ .and_then(Value::as_array)
179
+ .into_iter()
180
+ .flatten()
181
+ .map(|plan| {
182
+ json!({
183
+ "basePlanId": plan.get("basePlanId"),
184
+ "state": plan.get("state"),
185
+ "billingPeriod": plan.pointer("/autoRenewingBasePlanType/billingPeriodDuration"),
186
+ "regions": plan.get("regionalConfigs").and_then(Value::as_array).map(Vec::len),
187
+ })
188
+ })
189
+ .collect();
190
+ json!({
191
+ "productId": subscription.get("productId"),
192
+ "title": subscription.pointer("/listings/0/title"),
193
+ "archived": subscription.get("archived"),
194
+ "basePlans": plans,
195
+ })
196
+}
197
+
198
+/// The state Play reports for a base plan (`DRAFT`, `ACTIVE`, `INACTIVE`).
199
+pub fn base_plan_state<'a>(subscription: &'a Value, base_plan_id: &str) -> Option<&'a str> {
200
+ subscription
201
+ .get("basePlans")
202
+ .and_then(Value::as_array)?
203
+ .iter()
204
+ .find(|p| p.get("basePlanId").and_then(Value::as_str) == Some(base_plan_id))?
205
+ .get("state")
206
+ .and_then(Value::as_str)
207
+}
208
+
209
+/// Check the subscription as read back carries the listing that was sent.
210
+pub fn check_applied(stored: &Value, sent: &Value) -> std::result::Result<(), String> {
211
+ for listing in sent
212
+ .get("listings")
213
+ .and_then(Value::as_array)
214
+ .into_iter()
215
+ .flatten()
216
+ {
217
+ let code = listing.get("languageCode");
218
+ let found = stored
219
+ .get("listings")
220
+ .and_then(Value::as_array)
221
+ .into_iter()
222
+ .flatten()
223
+ .find(|l| l.get("languageCode") == code);
224
+ for field in ["title", "description", "benefits"] {
225
+ if found.and_then(|l| l.get(field)) != listing.get(field) {
226
+ return Err(format!(
227
+ "created, but the read-back {field} for {} differs",
228
+ code.and_then(Value::as_str).unwrap_or("?")
229
+ ));
230
+ }
231
+ }
232
+ }
233
+ Ok(())
234
+}
235
+
236
+/// Parse a price for a new subscription.
237
+pub fn price(currency: &str, amount: &str) -> Result<Money> {
238
+ Money::parse(currency, amount)
239
+}
240
+
241
+#[cfg(test)]
242
+mod tests {
243
+ use super::*;
244
+
245
+ fn sample() -> NewSubscription {
246
+ NewSubscription {
247
+ package: "xyz.example.app".into(),
248
+ product_id: "business_starter_monthly".into(),
249
+ language: "en-US".into(),
250
+ title: "Business Starter".into(),
251
+ description: Some("Custom-domain email for a small team.".into()),
252
+ benefits: vec!["Up to 5 team members".into(), "Your own domain".into()],
253
+ base_plan_id: "monthly".into(),
254
+ billing_period: "P1M".into(),
255
+ grace_period: Some("P3D".into()),
256
+ }
257
+ }
258
+
259
+ fn converted() -> Value {
260
+ json!({
261
+ "convertedRegionPrices": {
262
+ "US": { "regionCode": "US", "price": { "currencyCode": "USD", "units": "15", "nanos": 0 } },
263
+ "SE": { "regionCode": "SE", "price": { "currencyCode": "SEK", "units": "169", "nanos": 0 } }
264
+ },
265
+ "convertedOtherRegionsPrice": {
266
+ "usdPrice": { "currencyCode": "USD", "units": "15", "nanos": 0 },
267
+ "eurPrice": { "currencyCode": "EUR", "units": "14", "nanos": 0 }
268
+ },
269
+ "regionVersion": { "version": "2025/03" }
270
+ })
271
+ }
272
+
273
+ #[test]
274
+ fn the_body_has_one_listing_and_one_monthly_base_plan_priced_per_region() {
275
+ let body = subscription_body(&sample(), &converted()).unwrap();
276
+ assert_eq!(body["productId"], "business_starter_monthly");
277
+ assert_eq!(body["listings"][0]["title"], "Business Starter");
278
+ assert_eq!(body["listings"][0]["benefits"][0], "Up to 5 team members");
279
+ let plan = &body["basePlans"][0];
280
+ assert_eq!(plan["basePlanId"], "monthly");
281
+ assert_eq!(
282
+ plan["autoRenewingBasePlanType"]["billingPeriodDuration"],
283
+ "P1M"
284
+ );
285
+ assert_eq!(
286
+ plan["autoRenewingBasePlanType"]["gracePeriodDuration"],
287
+ "P3D"
288
+ );
289
+ let regions = plan["regionalConfigs"].as_array().unwrap();
290
+ assert_eq!(regions.len(), 2);
291
+ assert_eq!(regions[0]["regionCode"], "SE");
292
+ assert_eq!(regions[1]["price"]["units"], "15");
293
+ assert_eq!(regions[1]["newSubscriberAvailability"], true);
294
+ assert_eq!(
295
+ plan["otherRegionsConfig"]["eurPrice"]["currencyCode"],
296
+ "EUR"
297
+ );
298
+ assert!(plan.get("state").is_none());
299
+ }
300
+
301
+ #[test]
302
+ fn checks_reject_bad_ids_long_benefits_and_too_many_benefits() {
303
+ let mut bad = sample();
304
+ bad.base_plan_id = "monthly.plan".into();
305
+ assert!(bad.check().is_err());
306
+
307
+ let mut long = sample();
308
+ long.benefits = vec!["x".repeat(41)];
309
+ assert!(long.check().is_err());
310
+
311
+ let mut many = sample();
312
+ many.benefits = vec!["a".into(); 5];
313
+ assert!(many.check().is_err());
314
+
315
+ assert!(sample().check().is_ok());
316
+ assert_eq!(converted_regions_version(&converted()).unwrap(), "2025/03");
317
+ }
318
+
319
+ #[test]
320
+ fn summary_and_state_read_base_plans() {
321
+ let stored = json!({
322
+ "productId": "p", "listings": [{ "languageCode": "en-US", "title": "P" }],
323
+ "basePlans": [{ "basePlanId": "monthly", "state": "ACTIVE",
324
+ "autoRenewingBasePlanType": { "billingPeriodDuration": "P1M" },
325
+ "regionalConfigs": [{}, {}] }]
326
+ });
327
+ assert_eq!(base_plan_state(&stored, "monthly"), Some("ACTIVE"));
328
+ let row = summary(&stored);
329
+ assert_eq!(row["basePlans"][0]["regions"], 2);
330
+ assert_eq!(row["title"], "P");
331
+ }
332
+
333
+ #[test]
334
+ fn read_back_must_match_the_sent_listing() {
335
+ let sent = subscription_body(&sample(), &converted()).unwrap();
336
+ let mut stored = sent.clone();
337
+ assert!(check_applied(&stored, &sent).is_ok());
338
+ stored["listings"][0]["title"] = json!("Other");
339
+ assert!(check_applied(&stored, &sent).is_err());
340
+ }
341
+}