tillbell 0.6.0 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5a030c9d323ef3704d390da2665576a2954d63276ffefd860c944e3fba36a5b0
4
- data.tar.gz: 0f8fa7153ca08bc85b4eccd33bb5e287920aa63078ef83348ccf860d26323bf0
3
+ metadata.gz: 40023bb1bf7c5e6140bea7065efc6477edc7e38a0f0936ddbb1d9f36cea664f1
4
+ data.tar.gz: 23fcd6c419b6cbbcd98fe18fe23bfc0d1dc1f551c1bf2fcb0aff13a1c9d4b6c9
5
5
  SHA512:
6
- metadata.gz: c01db7a93ad7220b2c8a138f11915cb5f8663e44f7759a5ef34188ac2803c260edd93db84c13ad0b5ee5ee075576cf33c0f31ca55b89d0694fb3c2afe75cb451
7
- data.tar.gz: 9f99bd6f10ba65428ec5b3d942cafbd718462f0f560e14a72e69d69a8873d887f023991065306f7123588614819f0d883d2ce492c5d6a29304e0a007b3d52467
6
+ metadata.gz: '096b0bf3173c8fec91188e04d1b0ccec039b063334609019d7be2695dca8046493fbbd14f5531981c497f9a2510c8a84790c3df934e0c265b4d434be870f4901'
7
+ data.tar.gz: 7ae176e370fbdceefd46e35d004b5f3b44a85e80c93d5e2225a0b758ccf36cf9fcd5d4ad8ab8cd6e75d63463663104637fce2068d9814ac3e58315efc984e905
data/CHANGELOG.md CHANGED
@@ -6,6 +6,44 @@ All notable changes to this project are documented in this file. The format foll
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.7.0] - 2026-11-14
10
+
11
+ ### Added
12
+
13
+ - Helpers that work for both stores, so an app needs no `is_a?` on the processor classes:
14
+ `store?` and `store_name` ("Google Play", "App Store") on Pay subscriptions (`store?` on
15
+ customers too), `renewing?` (gives access and has no end date) and `sandbox?` (an App Store
16
+ sandbox purchase or a Google Play license tester's; always false for other processors).
17
+ - `Tillbell::Owner#store_subscription`, `#store_on_hold?` and `#owned_store_subscription`, the
18
+ Google Play helpers extended to the App Store, and `#subscriptions_to_cancel_in_store`, the App
19
+ Store subscriptions still renewing that only the customer can stop.
20
+ - `Tillbell.store(user_agent)` and the `tillbell_store` view helper: `:app_store` in the Hotwire
21
+ Native iOS app, `:google_play` in the Android one, nil in a browser.
22
+ - `Pay::AppStore::Subscription#replacement?` and `#replaced?`, always false, and
23
+ `Tillbell::AppStore::REFUND_URL`.
24
+ - `config.apple.allow_xcode_transactions` accepts Xcode StoreKit Testing transactions, unsigned
25
+ by Apple, in the development and test environments only.
26
+ - `config.apple.stale_after`: an App Store subscription stops giving access that long after the
27
+ end of a period no notification renewed (`stale?`).
28
+ - `price_amount` and `price_currency` on App Store subscriptions.
29
+ - `app_store_product_id` on plans (the Google Play `product_id` by default, unless several plans
30
+ share that product; an App Store-only plan has no `product_id`), `paywall.plan_option(plan:)`
31
+ with the ids of the app's store, and `paywall.plan_change` from an App Store subscription.
32
+ - The `subscription_reactivated` event, when a customer takes a cancellation back before the end
33
+ of the period.
34
+ - `require "tillbell/test_helpers"`: `Tillbell::TestHelpers` creates store subscriptions in a
35
+ host app's tests.
36
+ - The paywall controller keeps the last store prices on the device and shows them while the
37
+ store answers. Copy the new `tillbell_controller.js` from the generator template into your app.
38
+ - Bridge contract: the iOS component can be limited to the hosts of the app's pages
39
+ (`allowedHosts` in tillbell-ios); a message from another host gets an `error` reply. On
40
+ Android, Hotwire Native's `originTrustPolicy` already does it.
41
+
42
+ ### Changed
43
+
44
+ - App Store `sandbox?` is also true for Xcode StoreKit Testing purchases.
45
+ - `tillbell:check` skips plans without a Google Play `product_id`.
46
+
9
47
  ## [0.6.0] - 2026-11-11
10
48
 
11
49
  ### Added
data/README.md CHANGED
@@ -206,7 +206,7 @@ The values marked "credentials" below come from Google: the [Google Play setup](
206
206
  | `google.pubsub_audience` | endpoint URL | Audience of the Pub/Sub OIDC token. Set it when a proxy changes the URL Rails sees. |
207
207
  | `current_owner` | `-> { current_user }` | Returns who is buying. Evaluated in the controller and in the view, so any helper available there works (`Current.user`, `current_account`, ...). |
208
208
  | `parent_controller` | `"ApplicationController"` | Controller the purchase endpoint inherits from, to reuse your authentication, CSRF protection and error handling. |
209
- | `plans` | `[]` | The plans you sell, lowest first: `[{ name: :solo, product_id: "app_solo", base_plan_id: "monthly" }, ...]`. `tillbell:check` verifies them, `subscription.plan` finds the one a subscription is on, and `Tillbell.replacement_mode` and `paywall.plan_change` use their order to tell an upgrade from a downgrade. |
209
+ | `plans` | `[]` | The plans you sell, lowest first: `[{ name: :solo, product_id: "app_solo", base_plan_id: "monthly" }, ...]`. Add `app_store_product_id:` when the App Store product has another id than the Google Play one, or when several plans share a Google Play product (each App Store product is one duration, so they get no default); an App Store-only plan has no `product_id`. `tillbell:check` verifies the Google Play ones, `subscription.plan` finds the one a subscription is on, and `Tillbell.replacement_mode` and `paywall.plan_change` use their order to tell an upgrade from a downgrade. |
210
210
  | `subscription_name` | `->(product_id:, base_plan_id:) { Pay.default_product_name }` | Pay subscription `name` of a Google Play product, as used by `subscribed?(name:)`. |
211
211
 
212
212
  ## The paywall
@@ -232,7 +232,7 @@ The markup is unstyled and every builder method accepts HTML attributes (`class:
232
232
 
233
233
  | Builder method | Renders |
234
234
  |---|---|
235
- | `plan_option(product_id:, base_plan_id: nil, checked: false, replacing: nil, replacement_mode: nil)` | A radio button wrapped in a label with the block's content. |
235
+ | `plan_option(product_id: nil, base_plan_id: nil, plan: nil, checked: false, replacing: nil, replacement_mode: nil)` | A radio button wrapped in a label with the block's content. `plan_option(plan: :family)` takes a plan of `config.plans` instead of ids, with the ids of the store of the app showing the page; a plan that store does not sell renders nothing. |
236
236
  | `price(placeholder = "")` | Where the price localized by Google Play is written. Use it inside `plan_option`. |
237
237
  | `submit(text)` | Starts the purchase of the checked plan. |
238
238
  | `restore(text)` | Records again the purchases Google Play knows for the device, e.g. after a reinstall. |
@@ -340,7 +340,7 @@ Tillbell.plan(:family) # by name, or Tillbell.pla
340
340
  Tillbell.replacement_mode(from: :solo, to: :family) # => "CHARGE_PRORATED_PRICE" (upgrade); a downgrade gives "DEFERRED"
341
341
  ```
342
342
 
343
- A plan change from the settings page is then one option in a paywall:
343
+ A plan change from the settings page is then one option in a paywall. `from` may be a Google Play or an App Store subscription: on the App Store the option is the target product alone, and Apple replaces the subscription of the same group by itself.
344
344
 
345
345
  ```erb
346
346
  <%= tillbell_paywall(success_url: settings_path) do |paywall| %>
@@ -359,6 +359,9 @@ A plan change from the settings page is then one option in a paywall:
359
359
  |---|---|
360
360
  | `google_play_subscription` | The Google Play subscription, whatever the default processor. |
361
361
  | `google_play_on_hold?` | True when Google suspended the subscription for a failed payment: send the customer to `manage_url` rather than to a second subscription, which would bill twice if Google's retry succeeds. |
362
+ | `store_subscription`, `store_on_hold?` | The same for either store: the most relevant Google Play or App Store subscription, and whether the store suspended it. |
363
+ | `owned_store_subscription` | The store subscription the store still counts as the customer's, with or without access (`owned?`): offer its `manage_url`, not a second purchase on the web, which would bill twice. |
364
+ | `subscriptions_to_cancel_in_store` | App Store subscriptions that still renew. Only the customer can stop them, so show their `manage_url` before closing the account. |
362
365
  | `current_subscription` | The subscription to show and decide access from: the one that renews, then one that is canceled but running, then one whose payment is retried or that is paused; the most recent breaks a tie. |
363
366
  | `billing_subscriptions` | What still bills or resumes by itself (`subscription.billing?`), Google Play first. |
364
367
  | `cancel_billing_subscriptions!` | Cancels them: call it before closing or deleting an account. |
@@ -371,7 +374,15 @@ def subscribed? = !!current_user.current_subscription&.grants_access?
371
374
 
372
375
  A customer can have a Stripe subscription and a Google Play one (a web customer who later subscribes in the app, or the reverse). `Pay::GooglePlay::Customer` is never the owner's default payment processor, so `owner.payment_processor` does not see Google Play subscriptions: look at `owner.pay_subscriptions`, or at the Google Play customer (`owner.pay_customers.google_play.first`), to decide who has access.
373
376
 
374
- Pay only knows its own processors, so Tillbell adds `google_play?` to customers and subscriptions, and a `google_play` scope next to Pay's `stripe` one (`Pay::Subscription.google_play`).
377
+ Pay only knows its own processors, so Tillbell adds `google_play?` and `app_store?` to customers and subscriptions, and matching scopes next to Pay's `stripe` one (`Pay::Subscription.google_play`). Code that does not care which store adds these, on every Pay subscription:
378
+
379
+ | Method | Returns |
380
+ |---|---|
381
+ | `store?`, `store_name` | Whether it was bought in a store, and which one: `"Google Play"`, `"App Store"`, or nil for another processor. |
382
+ | `renewing?` | Gives access and will renew by itself (not canceled with an end date to come). |
383
+ | `sandbox?` | A test purchase that costs nothing: an App Store sandbox purchase, or a Google Play license tester's. False for other processors. Keep them out of revenue reports and conversion events. |
384
+
385
+ `Tillbell.store(request.user_agent)` (`tillbell_store` in views) tells which store the Hotwire Native app showing the page buys from: `:app_store`, `:google_play`, or nil in a browser. Unlike `tillbell_native?` it does not need the `tillbell` component, so it also answers for app versions that cannot buy yet, which is what store rules need, e.g. no link to a web checkout in the iOS app.
375
386
 
376
387
  `subscription.cancel` stops the renewal through the Google Play Developer API; the customer keeps access until the end of the paid period. Google can only end a subscription immediately by refunding it, which Tillbell never does on its own, so `cancel_now!` (which Pay calls when an owner is destroyed) also just stops the renewal. Google answers 410 for a purchase token that expired more than 60 days ago: a subscription still stored as active (a missed notification) is then recorded as ended, with a `subscription_expired` event, instead of failing the deletion of its owner. Any other error is raised, a 404 from a wrong package name for example: the subscription may still be billing. A subscription ended or already canceled is left alone, and one that waits for a deferred plan change is cancelled like any other: whether it is renewing comes from Google's subscription state, not from the entitlement about to end. `swap`, `pause` and `resume` raise `Tillbell::Error`: plan changes go through the paywall, and the rest happens in the Play Store.
377
388
 
@@ -394,6 +405,7 @@ Tillbell.configure do |config|
394
405
  config.on(:payment_recovered) { |subscription| } # the payment went through after a failure
395
406
  config.on(:plan_changed) { |subscription| } # the customer is now on another product or base plan; subscription.replaced_subscription is the previous purchase, if any
396
407
  config.on(:subscription_canceled) { |subscription| } # will not renew; access until ends_at
408
+ config.on(:subscription_reactivated) { |subscription| } # the customer took a cancellation back before ends_at (also fires subscription_updated)
397
409
  config.on(:subscription_expired) { |subscription| }
398
410
  config.on(:subscription_revoked) { |subscription| } # refunded or charged back
399
411
  config.on(:purchase_rejected) { |details| } # { owner:, purchase_token: } posted by another account
@@ -609,30 +621,57 @@ The iOS app ([tillbell-ios](https://github.com/pmakerhq/tillbell-ios)) talks to
609
621
 
610
622
  3. **Point the notifications to your app.** App Store Connect › your app › *App Information* › *App Store Server Notifications*: set both the production and the sandbox URL to `https://<your host>/tillbell/notifications/app_store`, version 2. Renewals, billing retries, expiries, refunds and Ask to Buy approvals arrive there; without them, a subscription is never renewed in your database.
611
623
 
612
- 4. **Name App Store products in the paywall on iOS.** The App Store has no base plans: each duration is its own product. Render the plans of the platform the request comes from, with `base_plan_id` left out on iOS:
624
+ 4. **Name App Store products in the paywall on iOS.** The App Store has no base plans: each duration is its own product. Declare the App Store product of each plan and let the paywall pick the ids of the store of the app showing the page:
625
+
626
+ ```ruby
627
+ config.plans = [{ name: :monthly, product_id: "premium", base_plan_id: "monthly", app_store_product_id: "premium.monthly" }]
628
+ ```
613
629
 
614
630
  ```erb
615
- <% if request.user_agent.to_s.include?("iOS") %>
616
- <%= paywall.plan_option(product_id: "premium.monthly") { paywall.price } %>
617
- <% else %>
618
- <%= paywall.plan_option(product_id: "premium", base_plan_id: "monthly") { paywall.price } %>
619
- <% end %>
631
+ <%= paywall.plan_option(plan: :monthly) { paywall.price } %>
620
632
  ```
621
633
 
622
- A plan change needs nothing more on iOS: the App Store replaces the subscription of the same group by itself.
634
+ A plan change needs nothing more on iOS: the App Store replaces the subscription of the same group by itself, and `paywall.plan_change` knows it.
623
635
 
624
- 5. **Test** in the simulator with a StoreKit configuration file, then on a device with a sandbox account (*Settings* › *Developer* › *Sandbox Apple Account*). Transactions signed by Xcode's StoreKit configuration are not signed by Apple: the purchase endpoint answers `invalid` for them, as it should.
636
+ 5. **Test** in the simulator with a StoreKit configuration file, then on a device with a sandbox account (*Settings* › *Developer* › *Sandbox Apple Account*). Xcode signs StoreKit Testing transactions itself, not with Apple's chain, so the purchase endpoint answers `invalid` for them unless you allow them in development:
637
+
638
+ ```ruby
639
+ config.apple.allow_xcode_transactions = Rails.env.development?
640
+ ```
641
+
642
+ They are then accepted without checking their signature, as Apple's own server libraries do for the Xcode environment, still for your bundle id and the signed-in owner's account id. Tillbell ignores the setting outside the development and test environments: anyone could forge an unsigned transaction.
643
+
644
+ 6. **Decide what happens if notifications stop.** A renewing subscription only moves on when Apple notifies the renewal. If notifications stop reaching your server, the last state stays, access included. `config.apple.stale_after = 16.days` (at least your billing grace period) makes `grants_access?` false that long after the end of a period no notification renewed; `stale?` tells such subscriptions.
625
645
 
626
646
  How App Store subscriptions differ:
627
647
 
628
648
  - `processor_id` is the `originalTransactionId`, which stays the same across renewals and plan changes.
629
649
  - The Pay customer (`Pay::AppStore::Customer`) shares its `processor_id` with the owner's Google Play customer: the paywall sends one account id to both apps, passed to StoreKit as the `appAccountToken`.
630
650
  - Statuses: `active` (including Apple's billing grace period), `past_due` in billing retry after the grace period (no access, see `grants_access?`), `canceled` once expired or refunded.
631
- - Sandbox purchases (Xcode, TestFlight, App Review) are accepted, so App Review can buy against your production server; `sandbox?` tells them apart, for example to keep them out of revenue reports.
651
+ - Sandbox purchases (TestFlight, App Review) are accepted, so App Review can buy against your production server (Xcode StoreKit Testing ones only in development, see above); `sandbox?` tells them apart, for example to keep them out of revenue reports.
652
+ - `price_amount` and `price_currency` give what Apple charged for the last transaction (an introductory offer included), as for Google Play.
632
653
  - Family-shared subscriptions are not recorded: they belong to the family member who bought them.
633
- - Only the customer can cancel an App Store subscription, in the App Store: `cancel` and `cancel_now!` leave it unchanged (they never raise, so deleting an owner still works). Send the customer to `manage_url` before closing their account.
654
+ - Only the customer can cancel an App Store subscription, in the App Store: `cancel` and `cancel_now!` leave it unchanged (they never raise, so deleting an owner still works). Send the customer to `manage_url` before closing their account (`owner.subscriptions_to_cancel_in_store` lists them). Only Apple refunds, at `Tillbell::AppStore::REFUND_URL`.
655
+ - `replacement?` and `replaced?` are always false: a plan change keeps the same `originalTransactionId`.
634
656
  - An Ask to Buy purchase is answered `pending` without a token: the paywall shows its pending message, and the subscription is recorded from Apple's notification once a parent approves it.
635
657
 
658
+ ## Testing your app
659
+
660
+ `require "tillbell/test_helpers"` and include `Tillbell::TestHelpers` in your tests to create store subscriptions without Apple's signature or a call to Google. They go through the same code as a real purchase, events included:
661
+
662
+ ```ruby
663
+ # spec/rails_helper.rb
664
+ require "tillbell/test_helpers"
665
+ RSpec.configure { |config| config.include Tillbell::TestHelpers }
666
+
667
+ create_app_store_subscription(user, product_id: "premium.monthly", environment: "Sandbox")
668
+ create_app_store_subscription(user, renewal_info: app_store_renewal_info(billing_retry: true), expires_at: 1.hour.ago)
669
+ create_google_play_subscription(user, state: "SUBSCRIPTION_STATE_ON_HOLD")
670
+ tillbell_events { ... } # => [[:subscription_created, subscription], ...]
671
+ ```
672
+
673
+ `app_store_transaction`, `app_store_renewal_info` and `google_subscription` build the payloads alone, to pass to `Pay::AppStore::Subscription.sync` or to stub `Tillbell::GooglePlay.subscription`.
674
+
636
675
  ## Security
637
676
 
638
677
  - The purchase endpoint inherits from your `ApplicationController`, so your authentication and CSRF protection apply. It never trusts an owner or account id sent by the client.
@@ -8,11 +8,20 @@ module Tillbell
8
8
  @template = template
9
9
  end
10
10
 
11
- # A radio button for one Google Play base plan, wrapped in a label with the block's
12
- # content. Pass +replacing+ (the current Pay::GooglePlay::Subscription) to make it a
13
- # plan change; +replacement_mode+ is Google's proration mode, e.g.
14
- # "CHARGE_PRORATED_PRICE", and is passed through untouched.
15
- def plan_option(product_id:, base_plan_id: nil, checked: false, replacing: nil, replacement_mode: nil, **html_options, &block)
11
+ # A radio button for one product, wrapped in a label with the block's content: a Google
12
+ # Play +product_id+ and +base_plan_id+, an App Store +product_id+, or a +plan+ of
13
+ # +Tillbell.plans+ (a name or a plan), whose ids are those of the store of the app showing
14
+ # the page (see +Tillbell.store+; in a browser, those of the store that sells it, Google
15
+ # Play first). A +plan+ the store of the app does not sell renders nothing. Pass +replacing+ (the current
16
+ # Pay::GooglePlay::Subscription) to make it a plan change; +replacement_mode+ is Google's
17
+ # proration mode, e.g. "CHARGE_PRORATED_PRICE", and is passed through untouched.
18
+ def plan_option(product_id: nil, base_plan_id: nil, plan: nil, checked: false, replacing: nil, replacement_mode: nil, **html_options, &block)
19
+ if plan
20
+ plan = find_plan(plan)
21
+ product_id, base_plan_id = plan.product_for(store || (plan.product_id ? :google_play : :app_store)).values_at(:product_id, :base_plan_id)
22
+ return "".html_safe if product_id.blank?
23
+ end
24
+ raise ArgumentError, "plan_option needs a product_id or a plan" if product_id.blank?
16
25
  raise ArgumentError, "a plan change needs a replacement_mode" if replacing && replacement_mode.blank?
17
26
 
18
27
  radio = tag.input(
@@ -26,15 +35,25 @@ module Tillbell
26
35
  tag.label(**html_options) { radio + @template.capture(&block) }
27
36
  end
28
37
 
29
- # The plan option for moving from the Google Play subscription +from+ to the plan +to+ of
30
- # +Tillbell.plans+ (a name or a plan), checked, with the replacement mode Google needs:
31
- # prorated for an upgrade, deferred to the next renewal for a downgrade (see
32
- # +Tillbell.replacement_mode+). Use it in a paywall that offers this one plan.
38
+ # The plan option for moving from the store subscription +from+ to the plan +to+ of
39
+ # +Tillbell.plans+ (a name or a plan), checked. On Google Play it carries the replacement
40
+ # mode Google needs: prorated for an upgrade, deferred to the next renewal for a downgrade
41
+ # (see +Tillbell.replacement_mode+). On the App Store it is the target product alone: Apple
42
+ # replaces the subscription of the same group by itself. Use it in a paywall that offers
43
+ # this one plan, in the app of the store +from+ was bought in (see +Tillbell.store+): the
44
+ # other store cannot change it.
33
45
  def plan_change(to:, from:, **html_options, &block)
34
- raise ArgumentError, "plan_change needs the current Google Play subscription (from:)" if from.nil?
46
+ raise ArgumentError, "plan_change needs the current store subscription (from:)" if from.nil?
47
+
48
+ target = find_plan(to)
49
+ if from.app_store?
50
+ raise ArgumentError, "#{to.inspect} is the current plan" if from.plan == target
51
+ raise ArgumentError, "#{to.inspect} has no App Store product" if target.app_store_product_id.blank?
52
+
53
+ return plan_option(**target.product_for(:app_store), checked: true, **html_options, &block)
54
+ end
35
55
 
36
56
  current = from.plan || raise(ArgumentError, "the current subscription (#{from.processor_plan}:#{from.base_plan_id}) is not in Tillbell.plans")
37
- target = to.is_a?(Tillbell::Plan) ? to : Tillbell.plan(to) || raise(ArgumentError, "#{to.inspect} is not in Tillbell.plans")
38
57
  plan_option(product_id: target.product_id, base_plan_id: target.base_plan_id, checked: true, replacing: from,
39
58
  replacement_mode: Tillbell.replacement_mode(from: current, to: target), **html_options, &block)
40
59
  end
@@ -72,6 +91,16 @@ module Tillbell
72
91
  end
73
92
 
74
93
  private
94
+ def find_plan(plan)
95
+ plan.is_a?(Tillbell::Plan) ? plan : Tillbell.plan(plan) || raise(ArgumentError, "#{plan.inspect} is not in Tillbell.plans")
96
+ end
97
+
98
+ # The store of the app showing the page; Google Play ids in a browser, where the paywall
99
+ # never connects anyway.
100
+ def store
101
+ Tillbell.store(@template.request.user_agent)
102
+ end
103
+
75
104
  def button(text, action, **html_options)
76
105
  tag.button(text, type: "button", disabled: true,
77
106
  **with_data(html_options, tillbell_target: "action", action: "tillbell##{action}"))
@@ -13,6 +13,16 @@ module Tillbell
13
13
  Tillbell.native?(request.user_agent)
14
14
  end
15
15
 
16
+ # The store of the native app showing the page (+:app_store+, +:google_play+) or nil in a
17
+ # browser. Same check as +Tillbell.store+.
18
+ #
19
+ # <% unless tillbell_store == :app_store %>
20
+ # <%= link_to "Subscribe on the web", checkout_path %>
21
+ # <% end %>
22
+ def tillbell_store
23
+ Tillbell.store(request.user_agent)
24
+ end
25
+
16
26
  # Renders an unstyled paywall driven by the +tillbell+ Stimulus controller, which
17
27
  # talks to the +tillbell+ Hotwire Native bridge component.
18
28
  #
@@ -109,6 +109,7 @@ module Pay
109
109
  events = [ event_for_changes ]
110
110
  if persisted? && !revoked?
111
111
  events << :plan_changed if processor_plan_changed?
112
+ events << :subscription_reactivated if reactivated?
112
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
113
114
  # The store accessor's +_was+ answers nil for a value that did not change.
114
115
  was_retrying = billing_retry_changed? ? billing_retry_was : billing_retry
@@ -123,11 +124,50 @@ module Pay
123
124
  revoked_at.present?
124
125
  end
125
126
 
126
- # True for a purchase made with a sandbox Apple Account (Xcode, TestFlight, App Review),
127
- # which costs nothing. Tillbell accepts them so App Review and testers can buy; check this
128
- # to keep them out of revenue reports, or to refuse them.
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.
129
130
  def sandbox?
130
- environment == "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
131
171
  end
132
172
 
133
173
  # The App Store has no base plans: each duration is its own product.
@@ -137,7 +177,7 @@ module Pay
137
177
 
138
178
  # The plan of +Tillbell.plans+ whose +product_id+ is this App Store product, or nil.
139
179
  def plan
140
- Tillbell.plan(product_id: processor_plan)
180
+ Tillbell.plan(app_store_product_id: processor_plan)
141
181
  end
142
182
 
143
183
  # The App Store has no pause.
@@ -202,6 +242,12 @@ module Pay
202
242
  end
203
243
 
204
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
+
205
251
  # Pay status from what Apple last said, at the time of the sync. Apple notifies every
206
252
  # change (renewal, expiry, billing retry, refund), so the status stays current as long
207
253
  # as App Store Server Notifications reach the app.
@@ -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)
@@ -23,6 +23,13 @@ Tillbell.configure do |config|
23
23
  # (version 2) in App Store Connect.
24
24
  # config.apple.bundle_id = "com.example.app"
25
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
+
26
33
  # Who is buying. Evaluated in the controller and the view of the paywall.
27
34
  # config.current_owner = -> { current_user }
28
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,6 +28,7 @@ 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
 
@@ -29,14 +38,19 @@ export default class extends BridgeComponent {
29
38
  const products = this.planTargets.map((plan) => this.#productOf(plan))
30
39
 
31
40
  this.send("products", { products }, ({ data }) => {
32
- 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)
33
46
 
34
47
  this.planTargets.forEach((plan) => {
35
48
  const { productId, basePlanId } = this.#productOf(plan)
36
49
  const product = data.products.find((p) => p.productId === productId && (p.basePlanId ?? null) === basePlanId)
37
50
  const price = plan.closest("label")?.querySelector("[data-tillbell-target~='price']")
38
51
 
39
- 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 : ""
40
54
  plan.disabled = !product
41
55
  })
42
56
  this.#setBusy(false)
@@ -141,6 +155,43 @@ export default class extends BridgeComponent {
141
155
  this.actionTargets.forEach((element) => element.disabled = busy)
142
156
  }
143
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
+
144
195
  #productOf(plan) {
145
196
  return { productId: plan.dataset.productId, basePlanId: plan.dataset.basePlanId ?? null }
146
197
  }
@@ -46,6 +46,10 @@ module Tillbell
46
46
  # subscriptions. Same page as the +manage+ message of the iOS component.
47
47
  MANAGE_URL = "https://apps.apple.com/account/subscriptions".freeze
48
48
 
49
+ # The page where a customer asks Apple for a refund: only Apple refunds App Store
50
+ # purchases, the app cannot. Apple then notifies the refund, which revokes the subscription.
51
+ REFUND_URL = "https://reportaproblem.apple.com".freeze
52
+
49
53
  class << self
50
54
  # The certificates a chain must end at. Only specs change it.
51
55
  attr_writer :root_certificates
@@ -66,8 +70,13 @@ module Tillbell
66
70
  # Verifies a signed transaction (+VerificationResult.jwsRepresentation+ in StoreKit 2)
67
71
  # and returns its payload. Raises +Tillbell::Error+ unless Apple signed it, for this app
68
72
  # (+config.apple.bundle_id+), and it is an auto-renewable subscription.
73
+ #
74
+ # With +config.apple.allow_xcode_transactions+, in development and test, a transaction
75
+ # Xcode signed for StoreKit Testing is accepted without checking its signature, as
76
+ # Apple's own server libraries do for the Xcode environment. Notifications never come from
77
+ # Xcode and are always fully verified.
69
78
  def verify_transaction!(jws)
70
- transaction = decode!(jws)
79
+ transaction = xcode_transaction(jws) || decode!(jws)
71
80
  raise Error, "The transaction belongs to another app (#{transaction["bundleId"]})" unless transaction["bundleId"] == bundle_id
72
81
  raise Error, "The transaction is not an auto-renewable subscription" unless transaction["type"] == AUTO_RENEWABLE
73
82
 
@@ -136,6 +145,18 @@ module Tillbell
136
145
  end
137
146
 
138
147
  private
148
+ # The payload of +jws+ when it is an Xcode StoreKit Testing transaction that the
149
+ # configuration allows, otherwise nil. Never in production or staging: without Apple's
150
+ # signature, anyone could forge one.
151
+ def xcode_transaction(jws)
152
+ return unless Tillbell.apple.allow_xcode_transactions && Rails.env.local?
153
+
154
+ payload, = JWT.decode(jws, nil, false)
155
+ payload if payload["environment"] == "Xcode"
156
+ rescue JWT::DecodeError
157
+ nil
158
+ end
159
+
139
160
  # The chain must be valid when Apple signed the data, not only today: a transaction
140
161
  # signed a year ago, restored now, may carry a leaf certificate that has since expired.
141
162
  def verify_chain!(leaf, intermediate, root, at:)
@@ -27,7 +27,8 @@ module Tillbell
27
27
  # any, +online+ lists what the Play Console has.
28
28
  def initialize(online: false, plans: Tillbell.plans)
29
29
  @online = online
30
- @plans = Array(plans).map { |plan| normalize(plan) }
30
+ # App Store plans have nothing to check with Google.
31
+ @plans = Array(plans).map { |plan| normalize(plan) }.select { |plan| plan[:product_id].present? }
31
32
  @results = []
32
33
  end
33
34
 
@@ -8,6 +8,9 @@ module Tillbell
8
8
  class Engine < ::Rails::Engine
9
9
  isolate_namespace Tillbell
10
10
 
11
+ # Display names of the stores, by Pay processor.
12
+ STORE_NAMES = { "google_play" => "Google Play", "app_store" => "App Store" }.freeze
13
+
11
14
  # Real-time developer notifications are verified, stored and queued by Pay (see
12
15
  # Tillbell::NotificationsController). Once Pay's job processes one, Tillbell re-reads
13
16
  # the subscription from Google.
@@ -30,6 +33,12 @@ module Tillbell
30
33
  def app_store?
31
34
  processor == "app_store"
32
35
  end
36
+
37
+ # True for a customer of an app store (Google Play or the App Store), whose
38
+ # subscriptions are managed in the store rather than by the app.
39
+ def store?
40
+ google_play? || app_store?
41
+ end
33
42
  end
34
43
 
35
44
  ActiveSupport.on_load(:pay_subscription) do
@@ -66,6 +75,35 @@ module Tillbell
66
75
  def app_store?
67
76
  customer.processor == "app_store"
68
77
  end
78
+
79
+ # True for a subscription bought in an app store (Google Play or the App Store). The
80
+ # customer manages it in the store (+manage_url+): the server can neither change its
81
+ # plan nor, for the App Store, stop it.
82
+ def store?
83
+ customer.store?
84
+ end
85
+
86
+ # The name of the store the subscription was bought in, "Google Play" or "App Store",
87
+ # for admin pages and internal alerts; nil for any other processor. Brand names, so
88
+ # they are not translated.
89
+ def store_name
90
+ STORE_NAMES[customer.processor]
91
+ end
92
+
93
+ # True when the subscription gives access and will renew by itself: +grants_access?+,
94
+ # and not canceled with an end date still to come (Pay's +on_grace_period?+). Use it to
95
+ # warn a customer who is about to close their account or switch plans while a renewal
96
+ # is planned.
97
+ def renewing?
98
+ grants_access? && !on_grace_period?
99
+ end
100
+
101
+ # True for a test purchase that costs nothing. Always false here; store subscriptions
102
+ # answer from what the store says (see Pay::AppStore::Subscription#sandbox? and
103
+ # Pay::GooglePlay::Subscription#sandbox?).
104
+ def sandbox?
105
+ false
106
+ end
69
107
  end
70
108
  end
71
109
 
@@ -25,6 +25,36 @@ module Tillbell
25
25
  google_play_subscription&.on_hold? || false
26
26
  end
27
27
 
28
+ # The most relevant subscription bought in an app store (Google Play or the App Store), or
29
+ # nil: the most recent one that is active or paused, otherwise the most recent one.
30
+ def store_subscription
31
+ subscriptions = store_subscriptions
32
+ subscriptions.active_or_paused.first || subscriptions.first
33
+ end
34
+
35
+ # True when the store subscription (see +store_subscription+) is on hold: the payment failed
36
+ # after the store's grace period and access is suspended while the store retries. The
37
+ # customer fixes it in the store (+manage_url+); subscribing again elsewhere would bill
38
+ # twice if the retry succeeds.
39
+ def store_on_hold?
40
+ store_subscription&.on_hold? || false
41
+ end
42
+
43
+ # The most recent store subscription the store still counts as the customer's, with or
44
+ # without access (see +owned?+), or nil. Buying it again would be refused by the store, and
45
+ # buying another way (a web checkout) would bill twice: send the customer to its
46
+ # +manage_url+ instead.
47
+ def owned_store_subscription
48
+ store_subscriptions.find(&:owned?)
49
+ end
50
+
51
+ # The App Store subscriptions that will still renew: only the customer can stop them, in
52
+ # the App Store, so +cancel_billing_subscriptions!+ leaves them unchanged. Show their
53
+ # +manage_url+ before closing the account.
54
+ def subscriptions_to_cancel_in_store
55
+ billing_subscriptions.select { |subscription| subscription.app_store? && subscription.ends_at.nil? }
56
+ end
57
+
28
58
  # The subscription to show and to decide access from, whatever its processor: the one
29
59
  # that renews, then one that is canceled but still running, then one whose payment is
30
60
  # being retried or that is paused; the most recent breaks a tie. Nil without any.
@@ -52,10 +82,18 @@ module Tillbell
52
82
  end
53
83
 
54
84
  private
85
+ # Subscriptions of the owner's store customers, the most recent first.
86
+ def store_subscriptions
87
+ pay_subscriptions.merge(Pay::Customer.active).where(pay_customers: { processor: %w[google_play app_store] }).order(created_at: :desc)
88
+ end
89
+
90
+ # An App Store subscription that went stale (see Pay::AppStore::Subscription#stale?) is
91
+ # still "active" but must not hide one that grants access.
55
92
  def subscription_standing(subscription)
56
- if subscription.active? && !subscription.on_grace_period? then 0
57
- elsif subscription.active? then 1
58
- elsif subscription.billing? then 2
93
+ active = subscription.active? && !subscription.try(:stale?)
94
+ if active && !subscription.on_grace_period? then 0
95
+ elsif active then 1
96
+ elsif subscription.billing? && !subscription.try(:stale?) then 2
59
97
  else 3
60
98
  end
61
99
  end
@@ -0,0 +1,98 @@
1
+ module Tillbell
2
+ # Builds store subscriptions in a host app's tests, without Apple's signature or a call to
3
+ # Google: what the stores send is built here, then saved by the same code as a real purchase.
4
+ #
5
+ # # spec/rails_helper.rb
6
+ # require "tillbell/test_helpers"
7
+ # RSpec.configure { |config| config.include Tillbell::TestHelpers }
8
+ #
9
+ # create_app_store_subscription(user, product_id: "app.family.monthly")
10
+ # create_google_play_subscription(user, state: "SUBSCRIPTION_STATE_ON_HOLD")
11
+ #
12
+ # Not loaded by +require "tillbell"+: test code only.
13
+ module TestHelpers
14
+ # Records an App Store subscription of +owner+ from +app_store_transaction+ (whose options
15
+ # it takes) and, when given, +renewal_info+ (see +app_store_renewal_info+). Returns the
16
+ # Pay::AppStore::Subscription, and emits the Tillbell events a real purchase would.
17
+ def create_app_store_subscription(owner, renewal_info: nil, **transaction)
18
+ Pay::AppStore::Subscription.sync(app_store_transaction(account_id: tillbell_account_id(owner), **transaction), renewal_info)
19
+ end
20
+
21
+ # Records a Google Play subscription of +owner+ under +purchase_token+ from
22
+ # +google_subscription+ (whose options it takes). Returns the Pay::GooglePlay::Subscription,
23
+ # and emits the Tillbell events a real purchase would.
24
+ def create_google_play_subscription(owner, purchase_token: SecureRandom.hex(16), **response)
25
+ Pay::GooglePlay::Subscription.sync(purchase_token, object: google_subscription(account_id: tillbell_account_id(owner), **response))
26
+ end
27
+
28
+ # The account id the paywall sends for +owner+: Google Play's +obfuscatedAccountId+ and
29
+ # the App Store's +appAccountToken+.
30
+ def tillbell_account_id(owner)
31
+ Pay::GooglePlay::Customer.for(owner).processor_id
32
+ end
33
+
34
+ # A decoded App Store transaction (JWSTransaction) of an auto-renewable subscription, with
35
+ # Apple's keys. +environment+ is "Production", "Sandbox" or "Xcode".
36
+ def app_store_transaction(account_id:, product_id: "premium.monthly", original_transaction_id: "2000000000000001",
37
+ transaction_id: original_transaction_id, purchased_at: Time.current, expires_at: 1.month.from_now,
38
+ revoked_at: nil, environment: "Production", price: nil, currency: nil,
39
+ bundle_id: Tillbell.apple.bundle_id, type: Tillbell::AppStore::AUTO_RENEWABLE)
40
+ {
41
+ "transactionId" => transaction_id, "originalTransactionId" => original_transaction_id, "bundleId" => bundle_id,
42
+ "productId" => product_id, "type" => type, "appAccountToken" => account_id, "environment" => environment,
43
+ "purchaseDate" => apple_time(purchased_at), "expiresDate" => apple_time(expires_at),
44
+ "revocationDate" => apple_time(revoked_at), "signedDate" => apple_time(Time.current),
45
+ "price" => price && (BigDecimal(price.to_s) * 1000).to_i, "currency" => currency
46
+ }.compact
47
+ end
48
+
49
+ # A decoded App Store renewal information (JWSRenewalInfo), as notifications carry it.
50
+ def app_store_renewal_info(product_id: "premium.monthly", auto_renew: true, billing_retry: false, grace_period_ends_at: nil)
51
+ {
52
+ "autoRenewProductId" => product_id, "autoRenewStatus" => auto_renew ? 1 : 0, "isInBillingRetryPeriod" => billing_retry,
53
+ "gracePeriodExpiresDate" => apple_time(grace_period_ends_at), "signedDate" => apple_time(Time.current)
54
+ }.compact
55
+ end
56
+
57
+ # A Google Play Developer API +purchases.subscriptionsv2.get+ response, in the shape
58
+ # Tillbell::GooglePlay.subscription returns (snake_case symbol keys). +test_purchase+ makes
59
+ # it a license tester's purchase.
60
+ def google_subscription(account_id:, state: "SUBSCRIPTION_STATE_ACTIVE", product_id: "premium", base_plan_id: "monthly",
61
+ expiry_time: 1.month.from_now, auto_renewing: true, acknowledged: true, linked_purchase_token: nil,
62
+ recurring_price: nil, deferred_product_id: nil, line_items: nil, test_purchase: false)
63
+ {
64
+ subscription_state: state,
65
+ acknowledgement_state: acknowledged ? "ACKNOWLEDGEMENT_STATE_ACKNOWLEDGED" : "ACKNOWLEDGEMENT_STATE_PENDING",
66
+ external_account_identifiers: { obfuscated_external_account_id: account_id },
67
+ linked_purchase_token: linked_purchase_token,
68
+ test_purchase: ({} if test_purchase),
69
+ line_items: line_items || [
70
+ {
71
+ product_id: product_id,
72
+ expiry_time: expiry_time.utc.iso8601,
73
+ offer_details: { base_plan_id: base_plan_id },
74
+ auto_renewing_plan: { auto_renew_enabled: auto_renewing, recurring_price: recurring_price }.compact,
75
+ deferred_item_replacement: deferred_product_id && { product_id: deferred_product_id }
76
+ }.compact
77
+ ]
78
+ }.compact
79
+ end
80
+
81
+ # Records every Tillbell event emitted while the block runs, as +[name, payload]+ pairs.
82
+ def tillbell_events
83
+ events = []
84
+ subscriber = ActiveSupport::Notifications.subscribe(/\Apay\.tillbell\./) do |name, *, payload|
85
+ events << [ name.delete_prefix("pay.tillbell.").to_sym, payload ]
86
+ end
87
+ yield
88
+ events
89
+ ensure
90
+ ActiveSupport::Notifications.unsubscribe(subscriber)
91
+ end
92
+
93
+ # A time as Apple sends it: milliseconds since the epoch.
94
+ def apple_time(time)
95
+ time && (time.to_f * 1000).to_i
96
+ end
97
+ end
98
+ end
@@ -1,3 +1,3 @@
1
1
  module Tillbell
2
- VERSION = "0.6.0"
2
+ VERSION = "0.7.0"
3
3
  end
data/lib/tillbell.rb CHANGED
@@ -28,13 +28,25 @@ module Tillbell
28
28
  # The events Tillbell emits, in the order a subscription usually goes through them.
29
29
  # +subscription_updated+ fires for any change; +subscription_renewed+, +payment_failed+,
30
30
  # +payment_recovered+ and +plan_changed+ say which one happened.
31
+ # +subscription_reactivated+ follows a +subscription_canceled+ the customer took back
32
+ # before the end of the period.
31
33
  EVENTS = %i[subscription_created subscription_updated subscription_renewed payment_failed payment_recovered plan_changed
32
- subscription_canceled subscription_expired subscription_revoked purchase_rejected].freeze
34
+ subscription_canceled subscription_reactivated subscription_expired subscription_revoked purchase_rejected].freeze
33
35
 
34
- # A plan the app sells: a Google Play product and its base plan, under a name of your own.
35
- Plan = Data.define(:name, :product_id, :base_plan_id) do
36
- def initialize(name:, product_id:, base_plan_id: nil)
37
- super(name: name.to_sym, product_id: product_id, base_plan_id: base_plan_id)
36
+ # A plan the app sells, under a name of your own: a Google Play product and its base plan,
37
+ # and the App Store product of the same plan. The App Store product id defaults to the Google
38
+ # Play one; an app sold on one store only leaves the other's id out.
39
+ Plan = Data.define(:name, :product_id, :base_plan_id, :app_store_product_id) do
40
+ def initialize(name:, product_id: nil, base_plan_id: nil, app_store_product_id: product_id)
41
+ raise ArgumentError, "plan #{name.inspect} needs a product_id or an app_store_product_id" if product_id.blank? && app_store_product_id.blank?
42
+
43
+ super(name: name.to_sym, product_id: product_id, base_plan_id: base_plan_id, app_store_product_id: app_store_product_id)
44
+ end
45
+
46
+ # The ids the app of +store+ (+:app_store+ or +:google_play+) buys this plan with, as the
47
+ # +product_id+ and +base_plan_id+ of a paywall option. The App Store has no base plans.
48
+ def product_for(store)
49
+ store == :app_store ? { product_id: app_store_product_id, base_plan_id: nil } : { product_id: product_id, base_plan_id: base_plan_id }
38
50
  end
39
51
  end
40
52
 
@@ -50,6 +62,14 @@ module Tillbell
50
62
  #
51
63
  # [bundle_id] Bundle identifier of the iOS app, e.g. "com.example.app". Transactions and
52
64
  # notifications signed for another app are refused.
65
+ # [allow_xcode_transactions] Accept the transactions Xcode signs locally for StoreKit
66
+ # Testing (a +.storekit+ configuration file), in the development
67
+ # and test environments only. See
68
+ # +Tillbell::AppStore.verify_transaction!+.
69
+ # [stale_after] How long after the end of its period an App Store subscription that no
70
+ # notification renewed or ended keeps giving access, e.g. +16.days+ (set it at
71
+ # least to the billing grace period of your subscriptions). Nil, the default,
72
+ # trusts the last state Apple notified forever.
53
73
  mattr_accessor :apple, default: ActiveSupport::OrderedOptions.new
54
74
 
55
75
  # Returns the Pay owner (usually a User) the current request acts for, or nil.
@@ -70,11 +90,11 @@ module Tillbell
70
90
  #
71
91
  # config.plans = [
72
92
  # { name: :solo, product_id: "app_solo", base_plan_id: "monthly" },
73
- # { name: :family, product_id: "app_family", base_plan_id: "monthly" }
93
+ # { name: :family, product_id: "app_family", base_plan_id: "monthly", app_store_product_id: "app.family.monthly" }
74
94
  # ]
75
95
  #
76
- # +tillbell:check+ checks them with Google, and +Pay::GooglePlay::Subscription#plan+ finds
77
- # the one a subscription is on.
96
+ # +tillbell:check+ checks the Google Play ones with Google, and +plan+ on a store subscription
97
+ # finds the one it is on.
78
98
  mattr_reader :plans, default: [].freeze
79
99
 
80
100
  # What Hotwire Native writes in the user agent for the bridge components the app
@@ -82,7 +102,27 @@ module Tillbell
82
102
  # list for the paywall to work.
83
103
  NATIVE_USER_AGENT = /bridge-components: \[(?:[^\]]*\s)?tillbell[\s\]]/
84
104
 
105
+ # What Hotwire Native writes in the user agent of each platform, and the store its in-app
106
+ # purchases go through.
107
+ NATIVE_STORES = {
108
+ /\b(?:Hotwire|Turbo) Native iOS\b/ => :app_store,
109
+ /\b(?:Hotwire|Turbo) Native Android\b/ => :google_play
110
+ }.freeze
111
+
85
112
  class << self
113
+ # The store in-app purchases go through in the Hotwire Native app +user_agent+ comes from:
114
+ # +:app_store+ (iOS), +:google_play+ (Android), or nil in a browser. Unlike +native?+, it
115
+ # does not need the +tillbell+ component, so it also answers for app versions that cannot
116
+ # buy yet. Use it for the store rules that apply to the whole app, e.g. the App Store
117
+ # forbids linking to another way to pay:
118
+ #
119
+ # Tillbell.store(request.user_agent) == :app_store
120
+ #
121
+ # Like +native?+, it only picks what to show: a forged user agent gains nothing.
122
+ def store(user_agent)
123
+ NATIVE_STORES.find { |pattern, _store| pattern.match?(user_agent.to_s) }&.last
124
+ end
125
+
86
126
  # True when +user_agent+ comes from a native app that registered the +tillbell+ bridge
87
127
  # component (Android today, iOS later), so a Google Play purchase can start from the
88
128
  # page. Use it to choose between the paywall and another way to pay, e.g. a web checkout:
@@ -97,20 +137,32 @@ module Tillbell
97
137
  end
98
138
 
99
139
  # Sets the catalog of +plans+ from hashes with +name+, +product_id+ and optionally
100
- # +base_plan_id+ (or from +Tillbell::Plan+ objects).
140
+ # +base_plan_id+ and +app_store_product_id+ (or from +Tillbell::Plan+ objects).
141
+ #
142
+ # A Google Play product with several base plans is several plans, while each App Store
143
+ # product is one duration: such plans do not default their App Store product id to the
144
+ # shared Google Play one. Give them their own +app_store_product_id+.
101
145
  def plans=(list)
102
- @@plans = list.map do |plan|
103
- next plan if plan.is_a?(Plan)
104
- raise ArgumentError, "a plan is a hash with :name, :product_id and :base_plan_id, got #{plan.inspect}" unless plan.respond_to?(:to_h) && !plan.nil?
146
+ built = list.map do |plan|
147
+ next [ plan, false ] if plan.is_a?(Plan)
148
+ raise ArgumentError, "a plan is a hash with :name and :product_id or :app_store_product_id, got #{plan.inspect}" unless plan.respond_to?(:to_h) && !plan.nil?
105
149
 
106
- Plan.new(**plan.to_h.symbolize_keys)
150
+ attributes = plan.to_h.symbolize_keys
151
+ [ Plan.new(**attributes), !attributes.key?(:app_store_product_id) ]
152
+ end
153
+ shared = built.filter_map { |plan, _defaulted| plan.app_store_product_id }.tally.select { |_id, count| count > 1 }.keys
154
+ @@plans = built.map do |plan, defaulted|
155
+ defaulted && shared.include?(plan.app_store_product_id) ? plan.with(app_store_product_id: nil) : plan
107
156
  end.freeze
108
157
  end
109
158
 
110
- # Finds a plan of +plans+ by +name+ (a symbol or string) or by Google ids. With a
111
- # +base_plan_id+ that no plan has, falls back to the product's plan when it has only one.
112
- def plan(name = nil, product_id: nil, base_plan_id: nil)
159
+ # Finds a plan of +plans+ by +name+ (a symbol or string), by App Store product id (nil when
160
+ # several plans share it), or by Google ids. With a +base_plan_id+ that no plan has, falls
161
+ # back to the product's plan when it has only one.
162
+ def plan(name = nil, product_id: nil, base_plan_id: nil, app_store_product_id: nil)
113
163
  return plans.find { |plan| plan.name == name.to_sym } if name
164
+ return plans.select { |plan| plan.app_store_product_id == app_store_product_id }.then { |matches| matches.first if matches.one? } if app_store_product_id
165
+ return if product_id.blank?
114
166
 
115
167
  matches = plans.select { |plan| plan.product_id == product_id }
116
168
  matches.find { |plan| plan.base_plan_id == base_plan_id } || (matches.first if matches.one?)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: tillbell
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.0
4
+ version: 0.7.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - pmakerhq
@@ -144,6 +144,7 @@ files:
144
144
  - lib/tillbell/engine.rb
145
145
  - lib/tillbell/google_play.rb
146
146
  - lib/tillbell/owner.rb
147
+ - lib/tillbell/test_helpers.rb
147
148
  - lib/tillbell/version.rb
148
149
  homepage: https://github.com/pmakerhq/tillbell-rails
149
150
  licenses: