@smbcloud / smbcloud-ascapi Mirror · read-only / commits / 149d59a
Fork 0

Read-only mirror of github.com/smbcloudXYZ/smbcloud-ascapi.

Mirrored from https://github.com/smbcloudXYZ/smbcloud-ascapi.git

Synced Nov 25, 09:15 UTC

Add Play subscriptions: list, get and create

asc play products only handles one-time products. asc play subscriptions create makes an auto-renewing subscription with one base plan, prices it in every region from one price through convertRegionPrices, activates the base plan and reads the listing back. It refuses an id that exists. Play's API has no field for a subscription's icon (checked against the v3 discovery document), so that stays a Console upload; the module docs and the command help say so. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: siGit Code v1.7.10 <noreply@sigit.si> Co-Authored-By: OndeCode v1.1.2 <noreply@ondeinference.com>

Seto Elkahfi committed Nov 19, 2026 at 23:08 UTC 149d59a06d014d36f3a7d129c33ea95b9567d707
4 files changed +532
crates/frontend/src/play.rs
+109
@@ -1024,6 +1024,115 @@ pub async fn create_product(
1024 })
1025 }
1026
1027 +/// Every auto-renewing subscription of the app, one summary row each.
1028 +pub async fn read_subscriptions(
1029 + client: &PlayClient,
1030 + package: &str,
1031 +) -> Result<Vec<serde_json::Value>, String> {
1032 + let all = client.list_subscriptions(package).await.map_err(err)?;
1033 + Ok(all
1034 + .iter()
1035 + .map(smbcloud_ascapi_play::subscription::summary)
1036 + .collect())
1037 +}
1038 +
1039 +/// One subscription by id, as Play stores it.
1040 +pub async fn read_subscription(
1041 + client: &PlayClient,
1042 + package: &str,
1043 + product_id: &str,
1044 +) -> Result<serde_json::Value, String> {
1045 + client
1046 + .get_subscription(package, product_id)
1047 + .await
1048 + .map_err(err)
1049 +}
1050 +
1051 +/// The result of creating a subscription.
1052 +#[derive(Debug, Serialize)]
1053 +#[serde(rename_all = "camelCase")]
1054 +pub struct SubscriptionCreated {
1055 + pub dry_run: bool,
1056 + /// The subscription body that is sent (dry run) or was sent.
1057 + pub sent: serde_json::Value,
1058 + /// The subscription as Play stores it, read back after activation.
1059 + /// `None` on a dry run.
1060 + pub stored: Option<serde_json::Value>,
1061 +}
1062 +
1063 +/// Create an auto-renewing subscription with one base plan priced in one
1064 +/// currency and converted to every region, then activate the base plan.
1065 +/// Refuses a product id that already exists. A dry run converts prices (a
1066 +/// read) and sends nothing.
1067 +pub async fn create_subscription(
1068 + client: &PlayClient,
1069 + subscription: &smbcloud_ascapi_play::NewSubscription,
1070 + price: &Money,
1071 + dry_run: bool,
1072 +) -> Result<SubscriptionCreated, String> {
1073 + use smbcloud_ascapi_play::subscription::{
1074 + base_plan_state, check_applied, converted_regions_version, subscription_body,
1075 + };
1076 +
1077 + subscription.check().map_err(err)?;
1078 + let package = subscription.package.as_str();
1079 + let id = subscription.product_id.as_str();
1080 + match client.get_subscription(package, id).await {
1081 + Ok(_) => {
1082 + return Err(format!(
1083 + "{id} already exists in {package}; it was left alone"
1084 + ))
1085 + }
1086 + Err(smbcloud_ascapi_play::Error::Api { status: 404, .. }) => {}
1087 + Err(e) => return Err(err(e)),
1088 + }
1089 + let converted = client
1090 + .convert_region_prices(package, price)
1091 + .await
1092 + .map_err(err)?;
1093 + let body = subscription_body(subscription, &converted).map_err(err)?;
1094 + if dry_run {
1095 + return Ok(SubscriptionCreated {
1096 + dry_run,
1097 + sent: body,
1098 + stored: None,
1099 + });
1100 + }
1101 + let version = converted_regions_version(&converted).map_err(err)?;
1102 + client
1103 + .create_subscription(package, id, &body, &version)
1104 + .await
1105 + .map_err(with_billing_hint)?;
1106 + client
1107 + .activate_base_plan(package, id, &subscription.base_plan_id)
1108 + .await
1109 + .map_err(|e| {
1110 + format!(
1111 + "created {id}, but activating base plan {} failed: {}",
1112 + subscription.base_plan_id,
1113 + with_billing_hint(e)
1114 + )
1115 + })?;
1116 + let stored = client
1117 + .get_subscription(package, id)
1118 + .await
1119 + .map_err(|e| format!("created {id}, but reading it back failed: {}", err(e)))?;
1120 + check_applied(&stored, &body)?;
1121 + let state = base_plan_state(&stored, &subscription.base_plan_id);
1122 + if state != Some("ACTIVE") {
1123 + return Err(format!(
1124 + "created {id}, but base plan {} is {} and not ACTIVE",
1125 + subscription.base_plan_id,
1126 + state.unwrap_or("missing")
1127 + ));
1128 + }
1129 + Ok(SubscriptionCreated {
1130 + dry_run,
1131 + sent: body,
1132 + stored: Some(stored),
1133 + })
1134 +}
1135 +
1136 /// The result of activating or deactivating a purchase option.
1137 #[derive(Debug, Serialize)]
1138 #[serde(rename_all = "camelCase")]
crates/play/src/client.rs
+80
@@ -30,6 +30,11 @@ pub(crate) fn products_path(package: &str, suffix: &str) -> String {
30 format!("/androidpublisher/v3/applications/{package}/oneTimeProducts{suffix}")
31 }
32
33 +/// Build `/androidpublisher/v3/applications/{package}/subscriptions…`.
34 +pub(crate) fn subscriptions_path(package: &str, suffix: &str) -> String {
35 + format!("/androidpublisher/v3/applications/{package}/subscriptions{suffix}")
36 +}
37 +
38 /// `onetimeproducts.patch` is the one call in this resource whose path is
39 /// all lowercase (`onetimeproducts`); get, list and the state changes use
40 /// `oneTimeProducts`. Google's discovery document says so, and a wrong case is
@@ -489,6 +494,81 @@ impl PlayClient {
494 .await
495 }
496
497 + /// All auto-renewing subscriptions of the app, following `nextPageToken`.
498 + pub async fn list_subscriptions(&self, package: &str) -> Result<Vec<serde_json::Value>> {
499 + let mut subscriptions = Vec::new();
500 + let mut page_token: Option<String> = None;
501 + loop {
502 + let suffix = match &page_token {
503 + Some(token) => format!("?pageToken={token}"),
504 + None => String::new(),
505 + };
506 + // Like products, an app with none can answer with an empty body.
507 + let text = self
508 + .send(Method::GET, &subscriptions_path(package, &suffix), None)
509 + .await?
510 + .text()
511 + .await?;
512 + if text.trim().is_empty() {
513 + break;
514 + }
515 + let page: serde_json::Value = serde_json::from_str(&text)?;
516 + if let Some(items) = page.get("subscriptions").and_then(|v| v.as_array()) {
517 + subscriptions.extend(items.iter().cloned());
518 + }
519 + match page.get("nextPageToken").and_then(|v| v.as_str()) {
520 + Some(token) if !token.is_empty() => page_token = Some(token.to_string()),
521 + _ => break,
522 + }
523 + }
524 + Ok(subscriptions)
525 + }
526 +
527 + pub async fn get_subscription(
528 + &self,
529 + package: &str,
530 + product_id: &str,
531 + ) -> Result<serde_json::Value> {
532 + self.json(
533 + Method::GET,
534 + &subscriptions_path(package, &format!("/{product_id}")),
535 + None::<&()>,
536 + )
537 + .await
538 + }
539 +
540 + /// `monetization.subscriptions.create`. Fails if the product id exists.
541 + /// `regions_version` is the one the prices were converted against.
542 + pub async fn create_subscription(
543 + &self,
544 + package: &str,
545 + product_id: &str,
546 + body: &serde_json::Value,
547 + regions_version: &str,
548 + ) -> Result<serde_json::Value> {
549 + let path = format!(
550 + "{}?productId={product_id}&regionsVersion.version={}",
551 + subscriptions_path(package, ""),
552 + regions_version.replace('/', "%2F"),
553 + );
554 + self.json(Method::POST, &path, Some(body)).await
555 + }
556 +
557 + /// `basePlans.activate`: what makes a subscription's base plan buyable.
558 + pub async fn activate_base_plan(
559 + &self,
560 + package: &str,
561 + product_id: &str,
562 + base_plan_id: &str,
563 + ) -> Result<serde_json::Value> {
564 + let path = subscriptions_path(
565 + package,
566 + &format!("/{product_id}/basePlans/{base_plan_id}:activate"),
567 + );
568 + let body = crate::subscription::activate_body(package, product_id, base_plan_id);
569 + self.json(Method::POST, &path, Some(&body)).await
570 + }
571 +
572 /// `pricing:convertRegionPrices`: one price in, a price for every region out.
573 pub async fn convert_region_prices(
574 &self,
crates/play/src/lib.rs
+2
@@ -14,6 +14,7 @@ pub mod error;
14 pub mod image;
15 pub mod listing;
16 pub mod product;
17 +pub mod subscription;
18 pub mod track;
19
20 pub use auth::ServiceAccount;
@@ -26,4 +27,5 @@ pub use listing::{
27 SHORT_DESCRIPTION_MAX_LEN, TITLE_MAX_LEN,
28 };
29 pub use product::{Money, NewProduct, ProductChanges};
30 +pub use subscription::NewSubscription;
31 pub use track::{LocalizedText, PromotePlan, RolloutAction, RolloutPlan, Track, TrackRelease};
crates/play/src/subscription.rs new
+341
@@ -0,0 +1,341 @@
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 +}