Skip to main content

cranpose_services/
purchases.rs

1//! In-app purchases: products, prices and owned entitlements.
2//!
3//! The shape is the one every mobile store agrees on — ask for a set of
4//! product ids, get back localized prices, start a purchase, and be told what
5//! the account owns — with the store-specific parts (StoreKit, Play Billing)
6//! living in platform backends installed via [`set_platform_purchases`].
7//!
8//! **The default backend reports [`StorePhase::Unavailable`] and owns
9//! nothing.** It deliberately does *not* grant entitlements: a desktop build
10//! with no store must not silently unlock paid features because a backend
11//! failed to register. An app that ships free on storeless platforms decides
12//! that itself, e.g.
13//!
14//! ```no_run
15//! # use cranpose_services::purchases::store_state;
16//! let state = store_state();
17//! // No store that will sell here — this app is free in that case.
18//! let unlocked = state.phase.cannot_sell() || state.owns("com.example.pro");
19//! ```
20//!
21//! The two phases that cannot sell say different things to a *user*:
22//! [`StorePhase::Unavailable`] is "not reached, try again", and
23//! [`StorePhase::Blocked`] is "this store will not sell to you here". Offering
24//! a retry for the second one only fails the same way again.
25//!
26//! # Reading state
27//!
28//! [`store_state`] is a cheap snapshot, safe to call every frame: backends
29//! keep the state and hand out a clone. State changes arrive asynchronously
30//! (the store answers over the network, another device restores a purchase,
31//! a parent approves an Ask-to-Buy request), so read it from the frame loop
32//! rather than expecting a reply to [`purchase`].
33//!
34//! [`take_event`] drains one-shot events — the things a snapshot cannot
35//! express, like "the user cancelled" — for showing a message once.
36
37use std::cell::RefCell;
38use std::collections::BTreeSet;
39use std::rc::Rc;
40
41/// A product as the store describes it, in the user's locale and currency.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct Product {
44    /// Store product identifier, as configured in App Store Connect or the
45    /// Play Console.
46    pub id: String,
47    /// Price formatted by the store for the user's storefront — "$34.99",
48    /// "34,99 €", "¥5,000". **Always display this string**; never format a
49    /// price yourself, and never hard-code one. Stores localize currency,
50    /// separators and placement, and they apply regional price tiers.
51    pub display_price: String,
52    /// Display name configured in the store.
53    pub title: String,
54    /// Description configured in the store.
55    pub description: String,
56}
57
58/// How far along the store connection is.
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub enum StorePhase {
61    /// No store on this platform, or no backend installed, or one that has
62    /// not reached the store yet. Nothing is owned and nothing can be bought
63    /// *right now* — a backend that is retrying reports this, so an app may
64    /// reasonably say "not reached" and offer to try again.
65    #[default]
66    Unavailable,
67    /// The store answered, and it will not sell to this app here: in-app
68    /// billing turned off on the device, an account that cannot pay, a
69    /// country the app is not distributed in.
70    ///
71    /// The difference from [`Unavailable`](Self::Unavailable) is whether
72    /// waiting helps. It does not here — no backend retries a store that has
73    /// said no — so an app should stop offering the purchase and say why,
74    /// rather than inviting a retry that can only fail the same way.
75    /// Already-known ownership remains authoritative even though the store
76    /// cannot be queried for new purchases.
77    Blocked,
78    /// A backend is installed and still talking to the store. Prices are not
79    /// known yet; owned entitlements may not be known yet either.
80    Connecting,
81    /// Product and entitlement information has been received at least once.
82    Ready,
83}
84
85impl StorePhase {
86    /// Whether nothing can be bought in this phase.
87    ///
88    /// Saves every paywall from spelling out the same two-variant match, and
89    /// keeps an app that only cares "can I sell?" from having to be updated
90    /// when a phase is added.
91    pub fn cannot_sell(self) -> bool {
92        matches!(self, Self::Unavailable | Self::Blocked)
93    }
94
95    /// Whether the store might still answer differently later.
96    ///
97    /// True while a backend is connecting or has yet to reach the store,
98    /// false once the store has said no or has already answered.
99    pub fn may_yet_change(self) -> bool {
100        matches!(self, Self::Unavailable | Self::Connecting)
101    }
102}
103
104/// Snapshot of everything known about the store right now.
105#[derive(Clone, Debug, Default, PartialEq, Eq)]
106pub struct StoreState {
107    /// How far along the connection is.
108    pub phase: StorePhase,
109    /// Products the backend was configured with and the store answered for.
110    /// A configured product missing here is one the store does not know —
111    /// usually a typo in the id, or a product not yet approved.
112    pub products: Vec<Product>,
113    /// Product ids the account currently owns. For non-consumables and
114    /// subscriptions this is the entitlement; consumables never appear.
115    pub owned: BTreeSet<String>,
116    /// Last error reported by the store, for diagnostics. A store being
117    /// briefly unreachable is normal and not worth showing to the user.
118    pub error: Option<String>,
119    /// True while a purchase or restore the user asked for is still running,
120    /// so the UI can disable the buy button and show a spinner.
121    pub busy: bool,
122}
123
124impl StoreState {
125    /// Whether `product_id` is currently owned.
126    pub fn owns(&self, product_id: &str) -> bool {
127        self.owned.contains(product_id)
128    }
129
130    /// The product with `product_id`, if the store answered for it.
131    pub fn product(&self, product_id: &str) -> Option<&Product> {
132        self.products.iter().find(|p| p.id == product_id)
133    }
134
135    /// The localized price of `product_id`, if known.
136    pub fn display_price(&self, product_id: &str) -> Option<&str> {
137        self.product(product_id).map(|p| p.display_price.as_str())
138    }
139}
140
141/// A one-shot thing that happened, which a snapshot cannot express.
142#[derive(Clone, Debug, PartialEq, Eq)]
143pub enum PurchaseEvent {
144    /// The purchase completed and the entitlement is in [`StoreState::owned`].
145    Purchased(String),
146    /// The user dismissed the payment sheet. Not an error; say nothing.
147    Cancelled,
148    /// The purchase needs someone else to finish it — Ask to Buy, or a
149    /// bank-side confirmation. It may complete minutes or days later, so tell
150    /// the user it is pending rather than that it failed.
151    Pending,
152    /// The purchase failed. The string is for the user.
153    Failed(String),
154    /// A restore finished. `restored` is how many entitlements it found —
155    /// zero means "nothing to restore on this account", which is worth
156    /// saying, because the user asked.
157    Restored {
158        /// Number of owned entitlements the restore turned up.
159        restored: usize,
160    },
161}
162
163/// A store backend.
164///
165/// Implementations are installed with [`set_platform_purchases`] and must be
166/// non-blocking: every method returns immediately and reports back by
167/// updating the snapshot returned from [`Purchases::state`].
168pub trait Purchases {
169    /// Declare the product ids this app sells and start talking to the store.
170    /// Called again on relaunch; backends should treat it as idempotent.
171    fn configure(&self, product_ids: &[&str]);
172
173    /// The current snapshot. Called every frame — keep it cheap.
174    fn state(&self) -> StoreState;
175
176    /// Begin a purchase. Presents the store's own payment sheet.
177    fn purchase(&self, product_id: &str);
178
179    /// Re-query what the account owns. Stores restore silently at launch, so
180    /// this is for the explicit "Restore purchases" button that Apple
181    /// requires a paid app to provide.
182    fn restore(&self);
183
184    /// Take the next pending one-shot event, if any.
185    fn take_event(&self) -> Option<PurchaseEvent>;
186}
187
188/// Shared handle to the active [`Purchases`] backend.
189pub type PurchasesRef = Rc<dyn Purchases>;
190
191/// The no-store backend: nothing is for sale and nothing is owned.
192struct NoPurchases;
193
194impl Purchases for NoPurchases {
195    fn configure(&self, _product_ids: &[&str]) {}
196
197    fn state(&self) -> StoreState {
198        StoreState::default()
199    }
200
201    fn purchase(&self, _product_id: &str) {}
202
203    fn restore(&self) {}
204
205    fn take_event(&self) -> Option<PurchaseEvent> {
206        None
207    }
208}
209
210thread_local! {
211    static PLATFORM_PURCHASES: RefCell<Option<PurchasesRef>> = const { RefCell::new(None) };
212    /// The no-store backend, created once per thread. [`purchases`] is on the
213    /// frame path — an app polls the snapshot every frame — so the fallback
214    /// must be a reference-count bump, not a fresh allocation each call.
215    static NO_PURCHASES: PurchasesRef = Rc::new(NoPurchases);
216}
217
218/// Installs a platform purchase backend, replacing any previous one.
219static STORE_LISTENER: std::sync::OnceLock<Box<dyn Fn() + Send + Sync>> =
220    std::sync::OnceLock::new();
221
222/// Registers a callback run whenever the store has news, so an app can be told
223/// rather than having to ask.
224///
225/// [`take_event`] and [`store_state`] are polling APIs, which assume the app is
226/// already running a frame loop to poll from. An app that has gone idle has no
227/// such loop, so a purchase that finishes while nothing moves on screen sits in
228/// the queue until something unrelated wakes the app. The listener closes that
229/// gap: it is the nudge, the queue is still the source of truth.
230///
231/// Called from whatever thread the platform reports on, so the callback must be
232/// `Send + Sync` and should do as little as possible.
233pub fn set_store_listener(listener: impl Fn() + Send + Sync + 'static) {
234    let _ = STORE_LISTENER.set(Box::new(listener));
235}
236
237/// Tells the app that the store has news. Called by a purchase backend.
238pub fn note_store_news() {
239    if let Some(listener) = STORE_LISTENER.get() {
240        listener();
241    }
242}
243
244pub fn set_platform_purchases(purchases: PurchasesRef) {
245    PLATFORM_PURCHASES.with(|cell| *cell.borrow_mut() = Some(purchases));
246}
247
248/// Removes any registered purchase backend (tests and teardown).
249pub fn clear_platform_purchases() {
250    PLATFORM_PURCHASES.with(|cell| *cell.borrow_mut() = None);
251}
252
253/// The active backend: the platform one if installed, else the no-store
254/// backend.
255pub fn purchases() -> PurchasesRef {
256    PLATFORM_PURCHASES
257        .with(|cell| cell.borrow().clone())
258        .unwrap_or_else(|| NO_PURCHASES.with(Rc::clone))
259}
260
261/// Whether a real store backend is installed on this platform.
262pub fn store_available() -> bool {
263    PLATFORM_PURCHASES.with(|cell| cell.borrow().is_some())
264}
265
266/// Convenience: declare the products this app sells and connect to the store.
267pub fn configure(product_ids: &[&str]) {
268    purchases().configure(product_ids);
269}
270
271/// Convenience: the current store snapshot.
272pub fn store_state() -> StoreState {
273    purchases().state()
274}
275
276/// Convenience: begin a purchase.
277pub fn purchase(product_id: &str) {
278    purchases().purchase(product_id);
279}
280
281/// Convenience: re-query owned entitlements.
282pub fn restore() {
283    purchases().restore();
284}
285
286/// Convenience: take the next one-shot purchase event.
287pub fn take_event() -> Option<PurchaseEvent> {
288    purchases().take_event()
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    #[test]
296    fn default_backend_sells_nothing_and_owns_nothing() {
297        clear_platform_purchases();
298        let state = store_state();
299        assert_eq!(state.phase, StorePhase::Unavailable);
300        assert!(state.owned.is_empty());
301        assert!(!state.owns("com.example.pro"));
302        assert!(!store_available());
303        // Calling through with no backend must not panic.
304        configure(&["com.example.pro"]);
305        purchase("com.example.pro");
306        restore();
307        assert_eq!(take_event(), None);
308    }
309
310    #[test]
311    fn the_two_phases_that_cannot_sell_differ_on_whether_waiting_helps() {
312        assert!(StorePhase::Unavailable.cannot_sell());
313        assert!(StorePhase::Blocked.cannot_sell());
314        assert!(!StorePhase::Connecting.cannot_sell());
315        assert!(!StorePhase::Ready.cannot_sell());
316
317        assert!(StorePhase::Unavailable.may_yet_change());
318        assert!(StorePhase::Connecting.may_yet_change());
319        assert!(
320            !StorePhase::Blocked.may_yet_change(),
321            "a store that has said no is what the phase exists to say"
322        );
323        assert!(!StorePhase::Ready.may_yet_change());
324    }
325
326    #[test]
327    fn nothing_is_owned_by_default_and_blocked_is_not_the_default() {
328        // The default has to stay the phase that invites a retry: a backend
329        // that has not answered yet must not read as one that refused.
330        assert_eq!(StorePhase::default(), StorePhase::Unavailable);
331    }
332
333    #[test]
334    fn installed_backend_answers_prices_and_ownership() {
335        struct Fake;
336        impl Purchases for Fake {
337            fn configure(&self, _product_ids: &[&str]) {}
338            fn state(&self) -> StoreState {
339                StoreState {
340                    phase: StorePhase::Ready,
341                    products: vec![Product {
342                        id: "com.example.pro".into(),
343                        display_price: "34,99 €".into(),
344                        title: "Pro".into(),
345                        description: "Everything unlocked".into(),
346                    }],
347                    owned: BTreeSet::from(["com.example.pro".to_string()]),
348                    error: None,
349                    busy: false,
350                }
351            }
352            fn purchase(&self, _product_id: &str) {}
353            fn restore(&self) {}
354            fn take_event(&self) -> Option<PurchaseEvent> {
355                Some(PurchaseEvent::Purchased("com.example.pro".into()))
356            }
357        }
358        set_platform_purchases(Rc::new(Fake));
359        let state = store_state();
360        assert_eq!(state.phase, StorePhase::Ready);
361        assert!(state.owns("com.example.pro"));
362        assert_eq!(state.display_price("com.example.pro"), Some("34,99 €"));
363        assert_eq!(state.display_price("com.example.nope"), None);
364        assert!(store_available());
365        assert_eq!(
366            take_event(),
367            Some(PurchaseEvent::Purchased("com.example.pro".into()))
368        );
369        clear_platform_purchases();
370    }
371}