tillbell 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,273 @@
1
+ module Pay
2
+ module AppStore
3
+ # An App Store auto-renewable subscription, stored as a Pay subscription.
4
+ #
5
+ # [processor_id] The +originalTransactionId+: it stays the same across renewals and plan
6
+ # changes within the subscription group.
7
+ # [processor_plan] The App Store product id of the latest transaction.
8
+ # [status] A Pay status: "active" (including the billing grace period), "past_due" (Apple
9
+ # retries a failed payment, without access) or "canceled" (expired or refunded).
10
+ # [ends_at] Set once the subscription will not renew, has expired or was refunded.
11
+ # [object] The last signed transaction payload, for debugging.
12
+ #
13
+ # App Store details live in +data+: +environment+ ("Production" or "Sandbox"),
14
+ # +transaction_id+, +purchase_date_ms+, +renewal_signed_ms+, +auto_renewing+,
15
+ # +auto_renew_product_id+, +billing_retry+, +grace_period_ends_at+ and +revoked_at+.
16
+ class Subscription < Pay::Subscription
17
+ store_accessor :data, :environment, :transaction_id, :purchase_date_ms, :renewal_signed_ms, :auto_renewing, :auto_renew_product_id,
18
+ :billing_retry, :grace_period_ends_at, :revoked_at
19
+
20
+ class << self
21
+ # Saves a verified transaction (see Tillbell::AppStore.verify_transaction!) and, when a
22
+ # notification brings it, its renewal information, then emits the matching Tillbell
23
+ # events. A transaction older than the one already saved changes nothing, so restores
24
+ # and notifications can arrive in any order.
25
+ #
26
+ # Returns the subscription, or nil when the transaction was not made through Tillbell
27
+ # (no known +appAccountToken+) or was shared through Family Sharing: the family member's
28
+ # transaction is not the buyer's purchase, and the iOS app never reports it either.
29
+ def sync(transaction, renewal_info = nil)
30
+ return if transaction["inAppOwnershipType"] == "FAMILY_SHARED"
31
+
32
+ pay_customer = Pay::AppStore::Customer.for_account_id(transaction["appAccountToken"])
33
+ if pay_customer.nil?
34
+ Rails.logger.warn "[Tillbell] Ignoring App Store transaction #{transaction["transactionId"]}: unknown account"
35
+ return
36
+ end
37
+
38
+ subscription, events = save_from_apple(pay_customer, transaction, renewal_info)
39
+ events.each { |event| Tillbell.instrument(event, subscription) }
40
+ subscription
41
+ end
42
+
43
+ private
44
+ # Applies the transaction under a row lock, so a purchase request and a notification
45
+ # for the same subscription serialize and only one of them emits each event.
46
+ def save_from_apple(pay_customer, transaction, renewal_info)
47
+ attempts = 0
48
+ begin
49
+ transaction(requires_new: true) do
50
+ subscription = pay_customer.subscriptions.lock.find_or_initialize_by(processor_id: transaction["originalTransactionId"])
51
+ subscription.apply(transaction, renewal_info)
52
+ events = subscription.events_for_changes
53
+ subscription.save!
54
+ [ subscription, events ]
55
+ end
56
+ rescue ActiveRecord::RecordNotUnique
57
+ # Another process inserted the row first; a second attempt finds it and locks it.
58
+ attempts += 1
59
+ attempts == 1 ? retry : raise
60
+ end
61
+ end
62
+ end
63
+
64
+ # Assigns what +transaction+ and +renewal_info+ (Apple payloads) say, without saving.
65
+ # The renewal information only comes with notifications; without it, the last known
66
+ # renewal state is kept.
67
+ def apply(transaction, renewal_info = nil)
68
+ if new_record? || transaction["purchaseDate"].to_i >= purchase_date_ms.to_i
69
+ assign_attributes(
70
+ name: Tillbell.subscription_name.call(product_id: transaction["productId"], base_plan_id: nil),
71
+ processor_plan: transaction["productId"],
72
+ current_period_end: Tillbell::AppStore.time(transaction["expiresDate"]),
73
+ object: transaction,
74
+ environment: transaction["environment"],
75
+ transaction_id: transaction["transactionId"],
76
+ purchase_date_ms: transaction["purchaseDate"].to_i,
77
+ revoked_at: Tillbell::AppStore.time(transaction["revocationDate"])&.iso8601
78
+ )
79
+ end
80
+ # Renewal information is ordered by its own signing date, so a stale notification processed
81
+ # late (a billing failure after the renewal that fixed it) never brings back old state.
82
+ if renewal_info && renewal_info["signedDate"].to_i >= renewal_signed_ms.to_i
83
+ assign_attributes(
84
+ renewal_signed_ms: renewal_info["signedDate"].to_i,
85
+ auto_renewing: renewal_info["autoRenewStatus"] == 1,
86
+ auto_renew_product_id: renewal_info["autoRenewProductId"],
87
+ billing_retry: renewal_info["isInBillingRetryPeriod"] == true,
88
+ grace_period_ends_at: Tillbell::AppStore.time(renewal_info["gracePeriodExpiresDate"])&.iso8601
89
+ )
90
+ end
91
+ self.auto_renewing = true if auto_renewing.nil?
92
+ assign_status
93
+ end
94
+
95
+ # The Tillbell event that describes the pending changes, or nil when nothing a host app
96
+ # cares about changed. Called before saving. Same rules as for Google Play.
97
+ def event_for_changes
98
+ return :subscription_created if new_record?
99
+ return if (changed - %w[object updated_at]).none?
100
+ return :subscription_revoked if revoked_at_changed? && revoked?
101
+ return :subscription_expired if status_changed? && status == "canceled"
102
+ return :subscription_canceled if ends_at_changed? && ends_at.present? && status == "active"
103
+
104
+ :subscription_updated
105
+ end
106
+
107
+ # Every event the pending changes call for, the generic one first. Called before saving.
108
+ def events_for_changes
109
+ events = [ event_for_changes ]
110
+ if persisted? && !revoked?
111
+ events << :plan_changed if processor_plan_changed?
112
+ events << :subscription_reactivated if reactivated?
113
+ events << :subscription_renewed if status == "active" && !processor_plan_changed? && current_period_end_changed? && current_period_end_was.present? && current_period_end > current_period_end_was
114
+ # The store accessor's +_was+ answers nil for a value that did not change.
115
+ was_retrying = billing_retry_changed? ? billing_retry_was : billing_retry
116
+ events << :payment_failed if billing_retry && !was_retrying
117
+ events << :payment_recovered if !billing_retry && was_retrying
118
+ end
119
+ events.compact
120
+ end
121
+
122
+ # True when Apple refunded the purchase.
123
+ def revoked?
124
+ revoked_at.present?
125
+ end
126
+
127
+ # True for a purchase made with a sandbox Apple Account (TestFlight, App Review) or in
128
+ # Xcode's StoreKit Testing, which costs nothing. Tillbell accepts them so App Review and
129
+ # testers can buy; check this to keep them out of revenue reports, or to refuse them.
130
+ def sandbox?
131
+ environment == "Sandbox" || environment == "Xcode"
132
+ end
133
+
134
+ # False once the period ended more than +config.apple.stale_after+ ago (see +stale?+).
135
+ def grants_access?
136
+ super && !stale?
137
+ end
138
+
139
+ # True when the period ended more than +config.apple.stale_after+ ago and no notification
140
+ # renewed or ended the subscription since: App Store Server Notifications stopped reaching
141
+ # the app, and the last known state can no longer be trusted. Always false without
142
+ # +stale_after+.
143
+ def stale?
144
+ stale_after = Tillbell.apple.stale_after
145
+ stale_after.present? && current_period_end.present? && current_period_end < stale_after.ago
146
+ end
147
+
148
+ # Price the customer paid for the last transaction, in the units of its currency (a
149
+ # +BigDecimal+: 12.99 euros), or nil when Apple gave none. Apple sends it in thousandths.
150
+ # It is what was charged for that period, an introductory offer included. Meant for
151
+ # analytics and conversion events, like Pay::GooglePlay::Subscription#price_amount.
152
+ def price_amount
153
+ price = object&.dig("price")
154
+ BigDecimal(price.to_s) / 1000 if price
155
+ end
156
+
157
+ # ISO 4217 code of the currency of +price_amount+ ("EUR"), or nil.
158
+ def price_currency
159
+ object&.dig("currency")
160
+ end
161
+
162
+ # The App Store never replaces a subscription with a new purchase: a plan change keeps the
163
+ # same +originalTransactionId+. Defined so code written for both stores can ask.
164
+ def replacement?
165
+ false
166
+ end
167
+
168
+ # See +replacement?+.
169
+ def replaced?
170
+ false
171
+ end
172
+
173
+ # The App Store has no base plans: each duration is its own product.
174
+ def base_plan_id
175
+ nil
176
+ end
177
+
178
+ # The plan of +Tillbell.plans+ whose +product_id+ is this App Store product, or nil.
179
+ def plan
180
+ Tillbell.plan(app_store_product_id: processor_plan)
181
+ end
182
+
183
+ # The App Store has no pause.
184
+ def paused?
185
+ false
186
+ end
187
+
188
+ # True while Apple retries a failed payment and the customer keeps access.
189
+ def in_grace_period?
190
+ billing_retry && status == "active"
191
+ end
192
+
193
+ # True when the payment failed after the grace period and access is suspended.
194
+ def on_hold?
195
+ status == "past_due"
196
+ end
197
+
198
+ # True while the App Store still counts the subscription as the customer's: buying it
199
+ # again would be answered "already subscribed".
200
+ def owned?
201
+ !revoked? && (status == "active" || status == "past_due")
202
+ end
203
+
204
+ # The product the customer moves to at the next renewal (a downgrade within the
205
+ # subscription group), or nil.
206
+ def deferred_product_id
207
+ auto_renew_product_id if auto_renew_product_id.present? && auto_renew_product_id != processor_plan
208
+ end
209
+
210
+ # True while a plan change waits for the next renewal. See +deferred_product_id+.
211
+ def plan_change_pending?
212
+ deferred_product_id.present?
213
+ end
214
+
215
+ # The App Store page where the customer manages their subscriptions.
216
+ def manage_url
217
+ Tillbell::AppStore::MANAGE_URL
218
+ end
219
+
220
+ # A stable identifier of the subscription that is safe to send to a third party.
221
+ def token_digest
222
+ Digest::SHA256.hexdigest(processor_id).first(16)
223
+ end
224
+
225
+ # Only the customer can stop an App Store subscription, in the App Store: Apple offers no
226
+ # server API for it. This leaves the subscription unchanged instead of raising, so
227
+ # deleting an owner (Pay calls +cancel_now!+) never fails on it. Tell the customer to
228
+ # cancel it in the App Store (+manage_url+) before deleting their account.
229
+ def cancel(**)
230
+ Rails.logger.warn "[Tillbell] App Store subscription #{token_digest} can only be canceled by the customer, in the App Store"
231
+ self
232
+ end
233
+
234
+ def cancel_now!(**)
235
+ cancel
236
+ end
237
+
238
+ %i[swap pause resume change_quantity].each do |method_name|
239
+ define_method(method_name) do |*, **|
240
+ raise Tillbell::Error, "App Store subscriptions cannot #{method_name} from the server; use the app or the App Store"
241
+ end
242
+ end
243
+
244
+ private
245
+ # True when the pending changes take back a cancellation before it took effect: the end
246
+ # date goes away while the subscription stays active (not an expired one bought again).
247
+ def reactivated?
248
+ status == "active" && !status_changed? && ends_at_changed? && ends_at.nil?
249
+ end
250
+
251
+ # Pay status from what Apple last said, at the time of the sync. Apple notifies every
252
+ # change (renewal, expiry, billing retry, refund), so the status stays current as long
253
+ # as App Store Server Notifications reach the app.
254
+ def assign_status
255
+ expires_at = current_period_end
256
+ grace_ends_at = grace_period_ends_at.present? ? Time.zone.parse(grace_period_ends_at) : nil
257
+
258
+ self.status, self.ends_at =
259
+ if revoked?
260
+ [ "canceled", Time.zone.parse(revoked_at) ]
261
+ elsif expires_at.nil? || expires_at.future?
262
+ [ "active", (expires_at unless auto_renewing) ]
263
+ elsif billing_retry && grace_ends_at&.future?
264
+ [ "active", nil ]
265
+ elsif billing_retry
266
+ [ "past_due", nil ]
267
+ else
268
+ [ "canceled", expires_at ]
269
+ end
270
+ end
271
+ end
272
+ end
273
+ end
@@ -207,6 +207,13 @@ module Pay
207
207
  status == "paused"
208
208
  end
209
209
 
210
+ # True for a purchase made by a license tester, which Google does not charge: Google's
211
+ # answer then carries +testPurchase+. Check it to keep test purchases out of revenue
212
+ # reports and conversion events.
213
+ def sandbox?
214
+ google_object.key?(:test_purchase)
215
+ end
216
+
210
217
  # True while Google still counts the purchase as the customer's: buying the same product
211
218
  # again would be answered +ALREADY_OWNED+, so offer +manage_url+ rather than a paywall. It
212
219
  # covers states that give no access (see +grants_access?+): a paused subscription resumes
@@ -338,11 +345,13 @@ module Pay
338
345
  # Events that say what happened to an existing subscription, deduced from its pending
339
346
  # changes: +:plan_changed+ (the product or base plan changed on the same purchase, e.g. a
340
347
  # deferred downgrade that took effect), +:subscription_renewed+, +:payment_failed+ (the
341
- # first failure only: the move from the grace period to the hold is not a second one) and
342
- # +:payment_recovered+. A replacement purchase is announced by +Subscription.sync+.
348
+ # first failure only: the move from the grace period to the hold is not a second one),
349
+ # +:payment_recovered+ and +:subscription_reactivated+ (a cancellation taken back before the
350
+ # end of the period). A replacement purchase is announced by +Subscription.sync+.
343
351
  def detail_events
344
352
  events = []
345
353
  events << :plan_changed if processor_plan_changed? || base_plan_id_changed?
354
+ events << :subscription_reactivated if status == "active" && !status_changed? && ends_at_changed? && ends_at.nil?
346
355
  events << :subscription_renewed if renewed?
347
356
  events << :payment_failed if PAYMENT_PROBLEM_STATES.include?(subscription_state) && !PAYMENT_PROBLEM_STATES.include?(previous_state)
348
357
  events << :payment_recovered if subscription_state == ACTIVE_STATE && PAYMENT_PROBLEM_STATES.include?(previous_state)
data/config/routes.rb CHANGED
@@ -4,4 +4,7 @@ Tillbell::Engine.routes.draw do
4
4
 
5
5
  # Pub/Sub push endpoint for Google Play real-time developer notifications.
6
6
  post "notifications/google_play", to: "notifications#create", as: :google_play_notifications
7
+
8
+ # App Store Server Notifications (version 2), set as the server URL in App Store Connect.
9
+ post "notifications/app_store", to: "app_store_notifications#create", as: :app_store_notifications
7
10
  end
@@ -0,0 +1,4 @@
1
+ {
2
+ "result": "pending",
3
+ "productId": "premium.monthly"
4
+ }
@@ -18,37 +18,52 @@
18
18
  "unavailable",
19
19
  "error"
20
20
  ],
21
- "description": "purchased: Purchase.PurchaseState.PURCHASED. pending: PurchaseState.PENDING (e.g. cash payment). canceled: USER_CANCELED. already_owned: ITEM_ALREADY_OWNED. unavailable: BILLING_UNAVAILABLE, SERVICE_UNAVAILABLE or FEATURE_NOT_SUPPORTED. error: anything else."
21
+ "description": "purchased: Purchase.PurchaseState.PURCHASED, or a verified StoreKit transaction. pending: PurchaseState.PENDING (e.g. cash payment), or a StoreKit purchase waiting for approval (Ask to Buy), which has no purchaseToken yet. canceled: USER_CANCELED. already_owned: ITEM_ALREADY_OWNED, or a current App Store entitlement. unavailable: BILLING_UNAVAILABLE, SERVICE_UNAVAILABLE or FEATURE_NOT_SUPPORTED. error: anything else."
22
22
  },
23
23
  "productId": {
24
24
  "type": "string",
25
25
  "minLength": 1,
26
- "description": "Google Play product id (subscription id)."
26
+ "description": "Google Play product id (subscription id), or App Store product identifier."
27
27
  },
28
28
  "purchaseToken": {
29
29
  "type": "string",
30
30
  "minLength": 1,
31
- "description": "Purchase.getPurchaseToken()."
31
+ "description": "Purchase.getPurchaseToken(), or the signed StoreKit transaction (VerificationResult.jwsRepresentation)."
32
32
  },
33
33
  "message": {
34
34
  "type": "string",
35
35
  "description": "Developer-facing detail, never shown to the customer."
36
36
  }
37
37
  },
38
- "if": {
39
- "properties": {
40
- "result": {
41
- "enum": [
42
- "purchased",
43
- "pending"
38
+ "allOf": [
39
+ {
40
+ "if": {
41
+ "properties": {
42
+ "result": {
43
+ "const": "purchased"
44
+ }
45
+ }
46
+ },
47
+ "then": {
48
+ "required": [
49
+ "productId",
50
+ "purchaseToken"
51
+ ]
52
+ }
53
+ },
54
+ {
55
+ "if": {
56
+ "properties": {
57
+ "result": {
58
+ "const": "pending"
59
+ }
60
+ }
61
+ },
62
+ "then": {
63
+ "required": [
64
+ "productId"
44
65
  ]
45
66
  }
46
67
  }
47
- },
48
- "then": {
49
- "required": [
50
- "productId",
51
- "purchaseToken"
52
- ]
53
- }
68
+ ]
54
69
  }
@@ -1,4 +1,4 @@
1
- # Tillbell: Google Play subscriptions stored as Pay subscriptions.
1
+ # Tillbell: Google Play and App Store subscriptions stored as Pay subscriptions.
2
2
  # See https://github.com/pmakerhq/tillbell-rails#configuration
3
3
  #
4
4
  # The two values below come from Google: the README's "Google Play setup" has the credentials
@@ -18,6 +18,18 @@ Tillbell.configure do |config|
18
18
  # Audience of the Pub/Sub OIDC token, if it is not the notification endpoint URL.
19
19
  # config.google.pubsub_audience = "https://example.com/tillbell/notifications/google_play"
20
20
 
21
+ # Bundle identifier of the iOS app, to accept App Store purchases (tillbell-ios). Set the
22
+ # App Store Server Notifications URL to https://<your host>/tillbell/notifications/app_store
23
+ # (version 2) in App Store Connect.
24
+ # config.apple.bundle_id = "com.example.app"
25
+
26
+ # Accept Xcode StoreKit Testing transactions (a .storekit file), unsigned by Apple. Ignored
27
+ # outside the development and test environments.
28
+ # config.apple.allow_xcode_transactions = Rails.env.development?
29
+
30
+ # Stop giving access that long after the end of a period no App Store notification renewed.
31
+ # config.apple.stale_after = 16.days
32
+
21
33
  # Who is buying. Evaluated in the controller and the view of the paywall.
22
34
  # config.current_owner = -> { current_user }
23
35
 
@@ -6,12 +6,20 @@
6
6
  // "tillbell" bridge component. Everywhere else the paywall keeps its buttons disabled
7
7
  // and shows its fallback, so a purchase can never start without the native app.
8
8
  //
9
- // Events dispatched on the paywall element, for your own code to listen to:
10
- // tillbell:verified the purchase grants access. Cancel the event to stay on the page
11
- // instead of going to the success URL.
9
+ // Events dispatched on the paywall element, for your own code to listen to (analytics, for
10
+ // example, without changing this file):
11
+ // tillbell:verified the purchase grants access (detail: the server's answer, with
12
+ // subscription_status). Cancel the event to stay on the page instead of
13
+ // going to the success URL.
12
14
  // tillbell:status a status message is shown (detail: { key, message }).
15
+ //
16
+ // The last prices the store gave are kept on the device and shown while it answers again, so
17
+ // the paywall does not open with empty prices. They are only shown: buying waits for the store,
18
+ // whose purchase sheet shows the price actually charged.
13
19
  import { BridgeComponent } from "@hotwired/hotwire-native-bridge"
14
20
 
21
+ const PRICES_KEY = "tillbell:prices"
22
+
15
23
  export default class extends BridgeComponent {
16
24
  static component = "tillbell"
17
25
  static targets = ["plan", "price", "action", "status", "fallback"]
@@ -20,29 +28,36 @@ export default class extends BridgeComponent {
20
28
  connect() {
21
29
  super.connect()
22
30
  this.fallbackTargets.forEach((element) => element.hidden = true)
31
+ this.#showKeptPrices()
23
32
  this.loadPrices()
24
33
  }
25
34
 
26
- // Asks Google Play for the localized price of every plan, then enables the paywall.
35
+ // Asks the store (Google Play or the App Store) for the localized price of every plan,
36
+ // then enables the paywall.
27
37
  loadPrices() {
28
38
  const products = this.planTargets.map((plan) => this.#productOf(plan))
29
39
 
30
40
  this.send("products", { products }, ({ data }) => {
31
- if (data.result !== "ok") return this.#showStatus(data.result === "unavailable" ? "unavailable" : "error")
41
+ if (data.result !== "ok") {
42
+ this.#priceTargetsOf().forEach(({ price }) => { if (price) price.textContent = "" })
43
+ return this.#showStatus(data.result === "unavailable" ? "unavailable" : "error")
44
+ }
45
+ this.#keepPrices(data.products)
32
46
 
33
47
  this.planTargets.forEach((plan) => {
34
48
  const { productId, basePlanId } = this.#productOf(plan)
35
49
  const product = data.products.find((p) => p.productId === productId && (p.basePlanId ?? null) === basePlanId)
36
50
  const price = plan.closest("label")?.querySelector("[data-tillbell-target~='price']")
37
51
 
38
- if (price && product) price.textContent = product.formattedPrice
52
+ // A product the store no longer offers loses its kept price.
53
+ if (price) price.textContent = product ? product.formattedPrice : ""
39
54
  plan.disabled = !product
40
55
  })
41
56
  this.#setBusy(false)
42
57
  })
43
58
  }
44
59
 
45
- // Opens the Google Play purchase sheet for the checked plan.
60
+ // Opens the store's purchase sheet for the checked plan.
46
61
  purchase() {
47
62
  const plan = this.planTargets.find((plan) => plan.checked && !plan.disabled)
48
63
  if (!plan) return
@@ -55,7 +70,7 @@ export default class extends BridgeComponent {
55
70
  this.send("purchase", message, ({ data }) => this.#handlePurchase(data))
56
71
  }
57
72
 
58
- // Records again the purchases Google Play knows for this device's account.
73
+ // Records again the purchases the store knows for this device's account.
59
74
  restorePurchases() {
60
75
  this.#setBusy(true)
61
76
  this.send("restore", {}, async ({ data }) => {
@@ -68,7 +83,7 @@ export default class extends BridgeComponent {
68
83
  })
69
84
  }
70
85
 
71
- // Opens the Play Store page where the customer manages the subscription.
86
+ // Opens the store page where the customer manages the subscription.
72
87
  manage() {
73
88
  const plan = this.planTargets.find((plan) => plan.checked) ?? this.planTargets[0]
74
89
  this.send("manage", { productId: plan ? plan.dataset.productId : null })
@@ -78,6 +93,9 @@ export default class extends BridgeComponent {
78
93
  switch (result) {
79
94
  case "purchased":
80
95
  case "pending":
96
+ // An App Store purchase waiting for approval (Ask to Buy) has no token yet: the
97
+ // server records it from Apple's notification once it is approved.
98
+ if (!purchaseToken) return this.#fail("pending")
81
99
  return this.#finish(await this.#record(purchaseToken))
82
100
  case "already_owned":
83
101
  return this.restorePurchases()
@@ -90,7 +108,7 @@ export default class extends BridgeComponent {
90
108
  }
91
109
  }
92
110
 
93
- // Sends the purchase token to Rails, which verifies it with Google.
111
+ // Sends the purchase token to Rails, which verifies it with Google or Apple.
94
112
  async #record(purchaseToken) {
95
113
  this.#showStatus("verifying")
96
114
  try {
@@ -137,6 +155,43 @@ export default class extends BridgeComponent {
137
155
  this.actionTargets.forEach((element) => element.disabled = busy)
138
156
  }
139
157
 
158
+ #priceTargetsOf() {
159
+ return this.planTargets.map((plan) => ({ plan, price: plan.closest("label")?.querySelector("[data-tillbell-target~='price']") }))
160
+ }
161
+
162
+ #showKeptPrices() {
163
+ const prices = this.#keptPrices()
164
+ this.planTargets.forEach((plan) => {
165
+ const price = plan.closest("label")?.querySelector("[data-tillbell-target~='price']")
166
+ const kept = prices[this.#priceKey(this.#productOf(plan))]
167
+ if (price && typeof kept === "string") price.textContent = kept
168
+ })
169
+ }
170
+
171
+ #keepPrices(products) {
172
+ const prices = this.#keptPrices()
173
+ products.forEach((product) => prices[this.#priceKey(product)] = product.formattedPrice)
174
+ try {
175
+ localStorage.setItem(PRICES_KEY, JSON.stringify(prices))
176
+ } catch {
177
+ // Storage full or blocked: the next paywall waits for the store, as without it.
178
+ }
179
+ }
180
+
181
+ // Storage can be missing, blocked or hold anything: then no price is kept.
182
+ #keptPrices() {
183
+ try {
184
+ const prices = JSON.parse(localStorage.getItem(PRICES_KEY))
185
+ return prices && typeof prices === "object" ? prices : {}
186
+ } catch {
187
+ return {}
188
+ }
189
+ }
190
+
191
+ #priceKey({ productId, basePlanId }) {
192
+ return `${productId}:${basePlanId ?? ""}`
193
+ }
194
+
140
195
  #productOf(plan) {
141
196
  return { productId: plan.dataset.productId, basePlanId: plan.dataset.basePlanId ?? null }
142
197
  }