1
+//! One-time products ("in-app products") through the Play monetization API.
2
+//!
3
+//! These calls are not inside an edit: a product is changed directly and takes
4
+//! effect when its purchase option is activated. Prices are set per region, so
5
+//! a price in one currency is converted to every region first
6
+//! (`pricing:convertRegionPrices`), the way Play Console does it.
7
+
8
+use serde_json::{json, Value};
9
+
10
+use crate::error::{Error, Result};
11
+
12
+/// A price split the way the Play API wants it: whole units as a string, and
13
+/// nanos (billionths) as an integer.
14
+#[derive(Debug, Clone, PartialEq, Eq)]
15
+pub struct Money {
16
+ pub currency: String,
17
+ pub units: String,
18
+ pub nanos: i32,
19
+}
20
+
21
+impl Money {
22
+ /// Parse `4.99` (up to 9 decimals) in `currency`, for example `USD`.
23
+ pub fn parse(currency: &str, amount: &str) -> Result<Self> {
24
+ let invalid = || Error::Invalid(format!("not a price: {amount:?} (expected e.g. 4.99)"));
25
+ let currency = currency.trim().to_ascii_uppercase();
26
+ if currency.len() != 3 || !currency.chars().all(|c| c.is_ascii_alphabetic()) {
27
+ return Err(Error::Invalid(format!(
28
+ "not a currency code: {currency:?} (expected e.g. USD)"
29
+ )));
30
+ }
31
+ let (whole, frac) = amount.trim().split_once('.').unwrap_or((amount.trim(), ""));
32
+ if whole.is_empty()
33
+ || !whole.chars().all(|c| c.is_ascii_digit())
34
+ || frac.len() > 9
35
+ || !frac.chars().all(|c| c.is_ascii_digit())
36
+ {
37
+ return Err(invalid());
38
+ }
39
+ let nanos: i32 = format!("{frac:0<9}").parse().map_err(|_| invalid())?;
40
+ let units = whole.trim_start_matches('0');
41
+ let units = if units.is_empty() { "0" } else { units };
42
+ if units == "0" && nanos == 0 {
43
+ return Err(Error::Invalid("the price must be above zero".to_string()));
44
+ }
45
+ Ok(Self {
46
+ currency,
47
+ units: units.to_string(),
48
+ nanos,
49
+ })
50
+ }
51
+
52
+ pub fn to_json(&self) -> Value {
53
+ json!({ "currencyCode": self.currency, "units": self.units, "nanos": self.nanos })
54
+ }
55
+}
56
+
57
+/// What a new one-time product says about itself.
58
+#[derive(Debug, Clone)]
59
+pub struct NewProduct {
60
+ pub package: String,
61
+ pub product_id: String,
62
+ pub language: String,
63
+ pub title: String,
64
+ pub description: String,
65
+ pub purchase_option_id: String,
66
+}
67
+
68
+pub const TITLE_MAX_LEN: usize = 55;
69
+pub const DESCRIPTION_MAX_LEN: usize = 200;
70
+
71
+impl NewProduct {
72
+ pub fn check(&self) -> Result<()> {
73
+ let id = &self.product_id;
74
+ let id_ok = !id.is_empty()
75
+ && id.len() <= 100
76
+ && id
77
+ .chars()
78
+ .next()
79
+ .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
80
+ && id.chars().all(|c| {
81
+ c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-')
82
+ });
83
+ if !id_ok {
84
+ return Err(Error::Invalid(format!(
85
+ "product id {id:?}: use lowercase letters, digits, _ . - (starting with a letter or digit)"
86
+ )));
87
+ }
88
+ for (name, value, max) in [
89
+ ("title", &self.title, TITLE_MAX_LEN),
90
+ ("description", &self.description, DESCRIPTION_MAX_LEN),
91
+ ] {
92
+ let len = value.chars().count();
93
+ if len == 0 || len > max {
94
+ return Err(Error::Invalid(format!(
95
+ "{name} must be 1 to {max} characters (got {len})"
96
+ )));
97
+ }
98
+ }
99
+ Ok(())
100
+ }
101
+}
102
+
103
+/// The `OneTimeProduct` body: one listing and one purchase option, priced in
104
+/// every region from a `pricing:convertRegionPrices` answer.
105
+pub fn product_body(product: &NewProduct, converted: &Value) -> Result<Value> {
106
+ let regions = converted
107
+ .get("convertedRegionPrices")
108
+ .and_then(Value::as_object)
109
+ .filter(|m| !m.is_empty())
110
+ .ok_or_else(|| Error::Invalid("Play returned no regional prices".to_string()))?;
111
+ let mut configs: Vec<Value> = regions
112
+ .iter()
113
+ .filter_map(|(code, entry)| {
114
+ let price = entry.get("price")?;
115
+ Some(json!({ "regionCode": code, "price": price, "availability": "AVAILABLE" }))
116
+ })
117
+ .collect();
118
+ configs.sort_by(|a, b| a["regionCode"].as_str().cmp(&b["regionCode"].as_str()));
119
+
120
+ let mut option = json!({
121
+ "purchaseOptionId": product.purchase_option_id,
122
+ "buyOption": { "legacyCompatible": true, "multiQuantityEnabled": false },
123
+ "regionalPricingAndAvailabilityConfigs": configs,
124
+ });
125
+ if let Some(other) = converted.get("convertedOtherRegionsPrice") {
126
+ option["newRegionsConfig"] = json!({
127
+ "usdPrice": other.get("usdPrice").cloned().unwrap_or(Value::Null),
128
+ "eurPrice": other.get("eurPrice").cloned().unwrap_or(Value::Null),
129
+ "availability": "AVAILABLE",
130
+ });
131
+ }
132
+ Ok(json!({
133
+ "packageName": product.package,
134
+ "productId": product.product_id,
135
+ "listings": [{
136
+ "languageCode": product.language,
137
+ "title": product.title,
138
+ "description": product.description,
139
+ }],
140
+ "purchaseOptions": [option],
141
+ }))
142
+}
143
+
144
+/// The regions version Play priced the conversion against, which the product
145
+/// write must quote back.
146
+pub fn regions_version(converted: &Value) -> Result<String> {
147
+ converted
148
+ .pointer("/regionVersion/version")
149
+ .and_then(Value::as_str)
150
+ .map(str::to_string)
151
+ .ok_or_else(|| Error::Invalid("Play returned no regions version".to_string()))
152
+}
153
+
154
+#[cfg(test)]
155
+mod tests {
156
+ use super::*;
157
+
158
+ fn product() -> NewProduct {
159
+ NewProduct {
160
+ package: "com.example.app".into(),
161
+ product_id: "app.unlock".into(),
162
+ language: "en-GB".into(),
163
+ title: "Unlock".into(),
164
+ description: "Removes the limit.".into(),
165
+ purchase_option_id: "buy".into(),
166
+ }
167
+ }
168
+
169
+ #[test]
170
+ fn prices_split_into_units_and_nanos() {
171
+ let m = Money::parse("usd", "4.99").unwrap();
172
+ assert_eq!(
173
+ (m.currency.as_str(), m.units.as_str(), m.nanos),
174
+ ("USD", "4", 990_000_000)
175
+ );
176
+ let m = Money::parse("USD", "5").unwrap();
177
+ assert_eq!((m.units.as_str(), m.nanos), ("5", 0));
178
+ let m = Money::parse("USD", "0.5").unwrap();
179
+ assert_eq!((m.units.as_str(), m.nanos), ("0", 500_000_000));
180
+ }
181
+
182
+ #[test]
183
+ fn bad_prices_are_refused() {
184
+ for bad in ["", "abc", "-1", "4.9.9", "0", "0.0", "1.1234567891", ".5"] {
185
+ assert!(Money::parse("USD", bad).is_err(), "{bad:?}");
186
+ }
187
+ assert!(Money::parse("US", "1").is_err());
188
+ assert!(Money::parse("U5D", "1").is_err());
189
+ }
190
+
191
+ #[test]
192
+ fn product_ids_and_text_are_checked() {
193
+ assert!(product().check().is_ok());
194
+ let mut p = product();
195
+ p.product_id = "Bad Id".into();
196
+ assert!(p.check().is_err());
197
+ let mut p = product();
198
+ p.title = "x".repeat(56);
199
+ assert!(p.check().is_err());
200
+ let mut p = product();
201
+ p.description = String::new();
202
+ assert!(p.check().is_err());
203
+ }
204
+
205
+ #[test]
206
+ fn the_body_prices_every_region_and_keeps_new_regions_in() {
207
+ let converted = json!({
208
+ "regionVersion": { "version": "2022/02" },
209
+ "convertedRegionPrices": {
210
+ "US": { "price": { "currencyCode": "USD", "units": "4", "nanos": 990000000 } },
211
+ "GB": { "price": { "currencyCode": "GBP", "units": "3", "nanos": 990000000 } }
212
+ },
213
+ "convertedOtherRegionsPrice": {
214
+ "usdPrice": { "currencyCode": "USD", "units": "4", "nanos": 990000000 },
215
+ "eurPrice": { "currencyCode": "EUR", "units": "4", "nanos": 990000000 }
216
+ }
217
+ });
218
+ let body = product_body(&product(), &converted).unwrap();
219
+ assert_eq!(body["productId"], "app.unlock");
220
+ let option = &body["purchaseOptions"][0];
221
+ assert_eq!(option["buyOption"]["legacyCompatible"], true);
222
+ let regions = option["regionalPricingAndAvailabilityConfigs"]
223
+ .as_array()
224
+ .unwrap();
225
+ assert_eq!(regions.len(), 2);
226
+ assert_eq!(regions[0]["regionCode"], "GB");
227
+ assert_eq!(regions[0]["availability"], "AVAILABLE");
228
+ assert_eq!(
229
+ option["newRegionsConfig"]["eurPrice"]["currencyCode"],
230
+ "EUR"
231
+ );
232
+ assert_eq!(regions_version(&converted).unwrap(), "2022/02");
233
+ }
234
+
235
+ #[test]
236
+ fn an_empty_conversion_is_an_error() {
237
+ assert!(product_body(&product(), &json!({ "convertedRegionPrices": {} })).is_err());
238
+ assert!(regions_version(&json!({})).is_err());
239
+ }
240
+}