tillbell 0.6.0 → 0.8.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: 5e48af929e57af662aa986988dad244c74992aedd713752cc294f543dc38a79f
4
+ data.tar.gz: 5ab9aa177391f2751ac182e8b83fa8f9451bdc9897b9b4a14e6d120aadbd3ae1
5
5
  SHA512:
6
- metadata.gz: c01db7a93ad7220b2c8a138f11915cb5f8663e44f7759a5ef34188ac2803c260edd93db84c13ad0b5ee5ee075576cf33c0f31ca55b89d0694fb3c2afe75cb451
7
- data.tar.gz: 9f99bd6f10ba65428ec5b3d942cafbd718462f0f560e14a72e69d69a8873d887f023991065306f7123588614819f0d883d2ce492c5d6a29304e0a007b3d52467
6
+ metadata.gz: 779b1e2584e9ed3ffc2a3590c182311ef61aacc076f5622e175418c8527becc79972d78cb4b7171f3623c839331c940fdfd0d150c8450c924a3106523163e98c
7
+ data.tar.gz: '03690b505f174b11c90a0737168823334dcc9d2f3c7d9b09d5543d79d73909f70b39e1ec35b825939af80918f304a979f89061b74c797e79f5f4b5eefe75864d'
data/CHANGELOG.md CHANGED
@@ -6,6 +6,65 @@ All notable changes to this project are documented in this file. The format foll
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.8.0] - 2026-11-24
10
+
11
+ ### Upgrading
12
+
13
+ - App Store purchases now create Pay charges, sandbox ones included (TestFlight and App Review
14
+ buy on your production server). If your app sums `Pay::Charge` for revenue, leave them out:
15
+ `Pay::Charge.where.not(id: Pay::AppStore::Charge.sandbox)`.
16
+
17
+ ### Added
18
+
19
+ - App Store payments are Pay charges: each paid transaction (the first purchase and every
20
+ renewal) is saved as a `Pay::AppStore::Charge`, with what the customer paid in the
21
+ storefront's currency, so revenue reports that sum Pay charges count the App Store. Refunds,
22
+ prorated ones included, set `amount_refunded`; a reversed refund resets it. `sandbox?` and the
23
+ `sandbox` scope tell sandbox and Xcode charges apart. `refund!` raises `Tillbell::Error`: only
24
+ Apple refunds App Store purchases.
25
+ - `Tillbell::AppStore.transaction_history`, a client of the App Store Server API's "Get
26
+ Transaction History", configured with `config.apple.issuer_id`, `key_id` and `private_key`.
27
+ - `bin/rails tillbell:app_store:backfill_charges` saves the charges of App Store payments made
28
+ before this version, or whose notification never arrived. Idempotent.
29
+
30
+ ## [0.7.0] - 2026-11-14
31
+
32
+ ### Added
33
+
34
+ - Helpers that work for both stores, so an app needs no `is_a?` on the processor classes:
35
+ `store?` and `store_name` ("Google Play", "App Store") on Pay subscriptions (`store?` on
36
+ customers too), `renewing?` (gives access and has no end date) and `sandbox?` (an App Store
37
+ sandbox purchase or a Google Play license tester's; always false for other processors).
38
+ - `Tillbell::Owner#store_subscription`, `#store_on_hold?` and `#owned_store_subscription`, the
39
+ Google Play helpers extended to the App Store, and `#subscriptions_to_cancel_in_store`, the App
40
+ Store subscriptions still renewing that only the customer can stop.
41
+ - `Tillbell.store(user_agent)` and the `tillbell_store` view helper: `:app_store` in the Hotwire
42
+ Native iOS app, `:google_play` in the Android one, nil in a browser.
43
+ - `Pay::AppStore::Subscription#replacement?` and `#replaced?`, always false, and
44
+ `Tillbell::AppStore::REFUND_URL`.
45
+ - `config.apple.allow_xcode_transactions` accepts Xcode StoreKit Testing transactions, unsigned
46
+ by Apple, in the development and test environments only.
47
+ - `config.apple.stale_after`: an App Store subscription stops giving access that long after the
48
+ end of a period no notification renewed (`stale?`).
49
+ - `price_amount` and `price_currency` on App Store subscriptions.
50
+ - `app_store_product_id` on plans (the Google Play `product_id` by default, unless several plans
51
+ share that product; an App Store-only plan has no `product_id`), `paywall.plan_option(plan:)`
52
+ with the ids of the app's store, and `paywall.plan_change` from an App Store subscription.
53
+ - The `subscription_reactivated` event, when a customer takes a cancellation back before the end
54
+ of the period.
55
+ - `require "tillbell/test_helpers"`: `Tillbell::TestHelpers` creates store subscriptions in a
56
+ host app's tests.
57
+ - The paywall controller keeps the last store prices on the device and shows them while the
58
+ store answers. Copy the new `tillbell_controller.js` from the generator template into your app.
59
+ - Bridge contract: the iOS component can be limited to the hosts of the app's pages
60
+ (`allowedHosts` in tillbell-ios); a message from another host gets an `error` reply. On
61
+ Android, Hotwire Native's `originTrustPolicy` already does it.
62
+
63
+ ### Changed
64
+
65
+ - App Store `sandbox?` is also true for Xcode StoreKit Testing purchases.
66
+ - `tillbell:check` skips plans without a Google Play `product_id`.
67
+
9
68
  ## [0.6.0] - 2026-11-11
10
69
 
11
70
  ### Added
data/README.md CHANGED
@@ -206,7 +206,11 @@ 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
+ | `apple.bundle_id` | (required for the App Store) | Bundle identifier of the iOS app. Transactions and notifications signed for another app are refused. |
211
+ | `apple.allow_xcode_transactions` | `nil` | Accept Xcode StoreKit Testing transactions, unsigned by Apple, in the development and test environments only. |
212
+ | `apple.stale_after` | `nil` | An App Store subscription that no notification renewed stops giving access (`grants_access?` false, `stale?` true) this long after the end of its period. Set it at least to your billing grace period, e.g. `16.days`. `nil` trusts the last state Apple notified forever. |
213
+ | `apple.issuer_id`, `apple.key_id`, `apple.private_key` | `nil` | An In-App Purchase key of App Store Connect, only needed to call the App Store Server API (`tillbell:app_store:backfill_charges`). See [App Store setup](#app-store-setup). |
210
214
  | `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
215
 
212
216
  ## The paywall
@@ -232,7 +236,7 @@ The markup is unstyled and every builder method accepts HTML attributes (`class:
232
236
 
233
237
  | Builder method | Renders |
234
238
  |---|---|
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. |
239
+ | `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
240
  | `price(placeholder = "")` | Where the price localized by Google Play is written. Use it inside `plan_option`. |
237
241
  | `submit(text)` | Starts the purchase of the checked plan. |
238
242
  | `restore(text)` | Records again the purchases Google Play knows for the device, e.g. after a reinstall. |
@@ -340,7 +344,7 @@ Tillbell.plan(:family) # by name, or Tillbell.pla
340
344
  Tillbell.replacement_mode(from: :solo, to: :family) # => "CHARGE_PRORATED_PRICE" (upgrade); a downgrade gives "DEFERRED"
341
345
  ```
342
346
 
343
- A plan change from the settings page is then one option in a paywall:
347
+ 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
348
 
345
349
  ```erb
346
350
  <%= tillbell_paywall(success_url: settings_path) do |paywall| %>
@@ -359,6 +363,9 @@ A plan change from the settings page is then one option in a paywall:
359
363
  |---|---|
360
364
  | `google_play_subscription` | The Google Play subscription, whatever the default processor. |
361
365
  | `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. |
366
+ | `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. |
367
+ | `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. |
368
+ | `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
369
  | `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
370
  | `billing_subscriptions` | What still bills or resumes by itself (`subscription.billing?`), Google Play first. |
364
371
  | `cancel_billing_subscriptions!` | Cancels them: call it before closing or deleting an account. |
@@ -371,7 +378,15 @@ def subscribed? = !!current_user.current_subscription&.grants_access?
371
378
 
372
379
  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
380
 
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`).
381
+ 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:
382
+
383
+ | Method | Returns |
384
+ |---|---|
385
+ | `store?`, `store_name` | Whether it was bought in a store, and which one: `"Google Play"`, `"App Store"`, or nil for another processor. |
386
+ | `renewing?` | Gives access and will renew by itself (not canceled with an end date to come). |
387
+ | `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. |
388
+
389
+ `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
390
 
376
391
  `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
392
 
@@ -394,6 +409,7 @@ Tillbell.configure do |config|
394
409
  config.on(:payment_recovered) { |subscription| } # the payment went through after a failure
395
410
  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
411
  config.on(:subscription_canceled) { |subscription| } # will not renew; access until ends_at
412
+ config.on(:subscription_reactivated) { |subscription| } # the customer took a cancellation back before ends_at (also fires subscription_updated)
397
413
  config.on(:subscription_expired) { |subscription| }
398
414
  config.on(:subscription_revoked) { |subscription| } # refunded or charged back
399
415
  config.on(:purchase_rejected) { |details| } # { owner:, purchase_token: } posted by another account
@@ -609,30 +625,70 @@ The iOS app ([tillbell-ios](https://github.com/pmakerhq/tillbell-ios)) talks to
609
625
 
610
626
  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
627
 
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:
628
+ 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:
629
+
630
+ ```ruby
631
+ config.plans = [{ name: :monthly, product_id: "premium", base_plan_id: "monthly", app_store_product_id: "premium.monthly" }]
632
+ ```
613
633
 
614
634
  ```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 %>
635
+ <%= paywall.plan_option(plan: :monthly) { paywall.price } %>
636
+ ```
637
+
638
+ 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.
639
+
640
+ 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:
641
+
642
+ ```ruby
643
+ config.apple.allow_xcode_transactions = Rails.env.development?
620
644
  ```
621
645
 
622
- A plan change needs nothing more on iOS: the App Store replaces the subscription of the same group by itself.
646
+ 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.
623
647
 
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.
648
+ 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.
649
+
650
+ 7. **Backfill past payments (optional).** Tillbell records each App Store payment as a Pay charge (see below) from the moment it is installed. To also record the payments made before, or those whose notification never arrived, create an In-App Purchase key in App Store Connect (*Users and Access* › *Integrations* › *In-App Purchase*), set it, then run the backfill. It reads each subscription's transaction history from the App Store Server API and can run again safely:
651
+
652
+ ```ruby
653
+ config.apple.issuer_id = Rails.application.credentials.dig(:tillbell, :apple_issuer_id)
654
+ config.apple.key_id = Rails.application.credentials.dig(:tillbell, :apple_key_id)
655
+ config.apple.private_key = Rails.application.credentials.dig(:tillbell, :apple_private_key) # the .p8 file's content
656
+ ```
657
+
658
+ ```sh
659
+ bin/rails tillbell:app_store:backfill_charges
660
+ ```
625
661
 
626
662
  How App Store subscriptions differ:
627
663
 
628
664
  - `processor_id` is the `originalTransactionId`, which stays the same across renewals and plan changes.
629
665
  - 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
666
  - 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.
667
+ - 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.
668
+ - `price_amount` and `price_currency` give what Apple charged for the last transaction (an introductory offer included), as for Google Play.
669
+ - Every paid transaction, the first purchase and each renewal, is a `Pay::AppStore::Charge`: `amount` is the price the customer paid, before Apple's commission, in the smallest unit of `currency` (lowercase, `"eur"`), like a Stripe charge, so revenue reports that sum Pay charges count the App Store too. It is the App Store Connect price of the storefront, so it includes tax where the storefront's prices do (not in the United States or Canada, for example). Its `created_at` is when Apple charged. A refund sets `amount_refunded` (the prorated part for a prorated refund), back to zero if Apple reverses it; a payload signed before the last one changes nothing, so a late notification never undoes a refund. Free trials, family-shared transactions and transactions without a price are not charges. Charges of sandbox and Xcode purchases are recorded too: leave them out of revenue with `charge.sandbox?`, or in SQL with `Pay::Charge.where.not(id: Pay::AppStore::Charge.sandbox)`. An upgrade's prorated refund of the previous product is not in Apple's data, so the upgraded transaction keeps its full amount. `sync!` raises: Apple's notifications and the backfill below update these charges.
632
670
  - 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.
671
+ - 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`.
672
+ - `replacement?` and `replaced?` are always false: a plan change keeps the same `originalTransactionId`.
634
673
  - 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
674
 
675
+ ## Testing your app
676
+
677
+ `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:
678
+
679
+ ```ruby
680
+ # spec/rails_helper.rb
681
+ require "tillbell/test_helpers"
682
+ RSpec.configure { |config| config.include Tillbell::TestHelpers }
683
+
684
+ create_app_store_subscription(user, product_id: "premium.monthly", environment: "Sandbox")
685
+ create_app_store_subscription(user, renewal_info: app_store_renewal_info(billing_retry: true), expires_at: 1.hour.ago)
686
+ create_google_play_subscription(user, state: "SUBSCRIPTION_STATE_ON_HOLD")
687
+ tillbell_events { ... } # => [[:subscription_created, subscription], ...]
688
+ ```
689
+
690
+ `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`.
691
+
636
692
  ## Security
637
693
 
638
694
  - 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
  #
@@ -0,0 +1,141 @@
1
+ module Pay
2
+ module AppStore
3
+ # A payment the App Store took for a subscription, stored as a Pay charge: the first
4
+ # purchase and every renewal are each a transaction, and each paid transaction is one charge.
5
+ # Revenue reports that sum Pay charges then count the App Store next to Stripe.
6
+ #
7
+ # [processor_id] The +transactionId+, unique per payment.
8
+ # [amount] The price the customer paid, in the smallest unit of +currency+ (cents), like
9
+ # Stripe charges: the App Store Connect price of the storefront, before Apple's
10
+ # commission, tax included where the storefront's prices include it (not in the
11
+ # United States or Canada, for example).
12
+ # [currency] Lowercase ISO 4217 code of the storefront's currency ("eur").
13
+ # [amount_refunded] The part of +amount+ Apple refunded, zero when a refund is reversed.
14
+ # [created_at] When Apple charged the customer (+purchaseDate+).
15
+ # [object] The signed transaction payload, for debugging.
16
+ #
17
+ # +data+ holds +environment+ ("Production", "Sandbox" or "Xcode"), +product_id+ and
18
+ # +signed_date_ms+, when Apple signed the payload the charge was last updated from.
19
+ #
20
+ # Sandbox purchases are recorded too, as their subscriptions are: leave them out of revenue
21
+ # with +sandbox?+, or in SQL with the +sandbox+ scope.
22
+ class Charge < Pay::Charge
23
+ store_accessor :data, :environment, :product_id, :signed_date_ms
24
+
25
+ # Environments of purchases that cost nothing: TestFlight and App Review (Sandbox) and
26
+ # Xcode StoreKit Testing.
27
+ SANDBOX_ENVIRONMENTS = %w[Sandbox Xcode].freeze
28
+
29
+ # The +revocationPercentage+ of a full refund: Apple gives percentages in thousandths.
30
+ FULL_REVOCATION = 100_000
31
+
32
+ # Revocations that give money back. A Family Sharing or group assignment revocation only
33
+ # removes someone's access to a purchase another person paid for.
34
+ REFUNDS = %w[REFUND_FULL REFUND_PRORATED].freeze
35
+
36
+ # Charges of sandbox and Xcode purchases. +where.not+ on this scope leaves them out.
37
+ scope :sandbox, -> { where("#{environment_sql} IN (?)", SANDBOX_ENVIRONMENTS) }
38
+
39
+ class << self
40
+ # SQL reading +data.environment+ as text, in the JSON syntax of the database: PostgreSQL,
41
+ # SQLite, or MySQL and MariaDB (Pay supports all of them).
42
+ def environment_sql
43
+ with_connection do |connection|
44
+ column = "#{connection.quote_table_name(table_name)}.#{connection.quote_column_name("data")}"
45
+ case connection.adapter_name
46
+ when /postg/i then "#{column}->>'environment'"
47
+ when /sqlite/i then "json_extract(#{column}, '$.environment')"
48
+ else "JSON_UNQUOTE(JSON_EXTRACT(#{column}, '$.environment'))"
49
+ end
50
+ end
51
+ end
52
+
53
+ # Saves the charge of a verified transaction (see Tillbell::AppStore.verify_transaction!)
54
+ # of +subscription+, or updates its refund. Idempotent: a transaction is one charge,
55
+ # however many times a restore, a notification or a backfill brings it, and a payload
56
+ # signed before the one the charge was last updated from changes nothing, so a late or
57
+ # replayed purchase never undoes a refund. Call it holding the subscription's row lock,
58
+ # as Pay::AppStore::Subscription.sync does, so two callers never insert the same
59
+ # transaction at once.
60
+ #
61
+ # Returns the charge, or nil when nothing was paid (a free trial), for a Family Sharing
62
+ # transaction (only the buyer's own transaction is a payment), for a transaction of
63
+ # another customer (several accounts can share an Apple Account, so one
64
+ # +originalTransactionId+ can be on two customers' subscriptions), and when the
65
+ # transaction has no price in a currency Pay knows.
66
+ #
67
+ # ponytail: the prorated refund Apple gives on an upgrade is not in the transaction data,
68
+ # so the upgraded transaction keeps its full amount.
69
+ def sync(transaction, subscription)
70
+ return if transaction["inAppOwnershipType"] == "FAMILY_SHARED"
71
+ return unless transaction["appAccountToken"].to_s.downcase == subscription.customer.processor_id
72
+
73
+ # Without a price, or a free trial: nothing was paid.
74
+ return if transaction["price"].to_i.zero?
75
+
76
+ amount = amount_from(transaction)
77
+ if amount.nil?
78
+ Rails.logger.warn "[Tillbell] No charge for App Store transaction #{transaction["transactionId"]}: unknown currency #{transaction["currency"].inspect}"
79
+ return
80
+ end
81
+ return if amount.zero?
82
+
83
+ charge = find_or_initialize_by(customer_id: subscription.customer_id, processor_id: transaction["transactionId"].to_s)
84
+ return charge if transaction["signedDate"].to_i < charge.signed_date_ms.to_i
85
+
86
+ charge.update!(
87
+ subscription: subscription,
88
+ amount: amount,
89
+ currency: transaction["currency"].downcase,
90
+ amount_refunded: refunded(amount, transaction),
91
+ created_at: Tillbell::AppStore.time(transaction["purchaseDate"]),
92
+ environment: transaction["environment"],
93
+ product_id: transaction["productId"],
94
+ signed_date_ms: transaction["signedDate"].to_i,
95
+ object: transaction
96
+ )
97
+ charge
98
+ end
99
+
100
+ private
101
+ # The price in the smallest unit of its currency, nil for a currency Pay does not know.
102
+ # Apple sends it in thousandths of the currency unit (14990 for 14.99 euros), whatever
103
+ # the currency's own decimals.
104
+ def amount_from(transaction)
105
+ subunits = Pay::Currency.all.dig(transaction["currency"].to_s.downcase, "subunit_to_unit")
106
+ (BigDecimal(transaction["price"].to_s) * subunits / 1000).round.to_i if subunits
107
+ end
108
+
109
+ # A refund without +revocationType+ is a full one, as before Apple added prorated
110
+ # refunds, except on a transaction the customer upgraded from: its revocation is the
111
+ # upgrade, not a refund. A reversed refund removes the revocation fields.
112
+ def refunded(amount, transaction)
113
+ return 0 if transaction["revocationDate"].nil?
114
+
115
+ type = transaction["revocationType"]
116
+ return 0 if type.present? ? !REFUNDS.include?(type) : transaction["isUpgraded"] == true
117
+
118
+ percentage = transaction["revocationPercentage"] || FULL_REVOCATION
119
+ (BigDecimal(amount) * percentage / FULL_REVOCATION).round.to_i
120
+ end
121
+ end
122
+
123
+ # True for a sandbox or Xcode purchase, which costs nothing: leave it out of revenue.
124
+ def sandbox?
125
+ SANDBOX_ENVIRONMENTS.include?(environment)
126
+ end
127
+
128
+ # Only Apple refunds App Store purchases: send the customer to
129
+ # +Tillbell::AppStore::REFUND_URL+. Apple then notifies the refund, which updates the charge.
130
+ def refund!(*, **)
131
+ raise Tillbell::Error, "Only Apple refunds App Store purchases; the customer asks at #{Tillbell::AppStore::REFUND_URL}"
132
+ end
133
+
134
+ # Pay re-reads a charge from its processor by id; App Store charges are only updated from
135
+ # Apple's signed transactions (see +sync+), which a transaction id alone cannot fetch.
136
+ def sync!(**)
137
+ raise Tillbell::Error, "App Store charges are updated from Apple's notifications, or with tillbell:app_store:backfill_charges"
138
+ end
139
+ end
140
+ end
141
+ end
@@ -7,6 +7,7 @@ module Pay
7
7
  # +appAccountToken+. Apple returns it in every signed transaction, which is how Tillbell
8
8
  # knows which owner a transaction belongs to.
9
9
  class Customer < Pay::Customer
10
+ has_many :charges, dependent: :destroy, class_name: "Pay::AppStore::Charge"
10
11
  has_many :subscriptions, dependent: :destroy, class_name: "Pay::AppStore::Subscription"
11
12
 
12
13
  # Returns the App Store customer of +owner+, creating it on first use.
@@ -42,7 +42,9 @@ module Pay
42
42
 
43
43
  private
44
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.
45
+ # for the same subscription serialize and only one of them emits each event. The
46
+ # transaction's charge is saved under the same lock, even when the transaction is older
47
+ # than the one the subscription has: a refund notification carries the refunded one.
46
48
  def save_from_apple(pay_customer, transaction, renewal_info)
47
49
  attempts = 0
48
50
  begin
@@ -51,6 +53,7 @@ module Pay
51
53
  subscription.apply(transaction, renewal_info)
52
54
  events = subscription.events_for_changes
53
55
  subscription.save!
56
+ Pay::AppStore::Charge.sync(transaction, subscription)
54
57
  [ subscription, events ]
55
58
  end
56
59
  rescue ActiveRecord::RecordNotUnique
@@ -109,6 +112,7 @@ module Pay
109
112
  events = [ event_for_changes ]
110
113
  if persisted? && !revoked?
111
114
  events << :plan_changed if processor_plan_changed?
115
+ events << :subscription_reactivated if reactivated?
112
116
  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
117
  # The store accessor's +_was+ answers nil for a value that did not change.
114
118
  was_retrying = billing_retry_changed? ? billing_retry_was : billing_retry
@@ -123,11 +127,50 @@ module Pay
123
127
  revoked_at.present?
124
128
  end
125
129
 
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.
130
+ # True for a purchase made with a sandbox Apple Account (TestFlight, App Review) or in
131
+ # Xcode's StoreKit Testing, which costs nothing. Tillbell accepts them so App Review and
132
+ # testers can buy; check this to keep them out of revenue reports, or to refuse them.
129
133
  def sandbox?
130
- environment == "Sandbox"
134
+ environment == "Sandbox" || environment == "Xcode"
135
+ end
136
+
137
+ # False once the period ended more than +config.apple.stale_after+ ago (see +stale?+).
138
+ def grants_access?
139
+ super && !stale?
140
+ end
141
+
142
+ # True when the period ended more than +config.apple.stale_after+ ago and no notification
143
+ # renewed or ended the subscription since: App Store Server Notifications stopped reaching
144
+ # the app, and the last known state can no longer be trusted. Always false without
145
+ # +stale_after+.
146
+ def stale?
147
+ stale_after = Tillbell.apple.stale_after
148
+ stale_after.present? && current_period_end.present? && current_period_end < stale_after.ago
149
+ end
150
+
151
+ # Price the customer paid for the last transaction, in the units of its currency (a
152
+ # +BigDecimal+: 12.99 euros), or nil when Apple gave none. Apple sends it in thousandths.
153
+ # It is what was charged for that period, an introductory offer included. Meant for
154
+ # analytics and conversion events, like Pay::GooglePlay::Subscription#price_amount.
155
+ def price_amount
156
+ price = object&.dig("price")
157
+ BigDecimal(price.to_s) / 1000 if price
158
+ end
159
+
160
+ # ISO 4217 code of the currency of +price_amount+ ("EUR"), or nil.
161
+ def price_currency
162
+ object&.dig("currency")
163
+ end
164
+
165
+ # The App Store never replaces a subscription with a new purchase: a plan change keeps the
166
+ # same +originalTransactionId+. Defined so code written for both stores can ask.
167
+ def replacement?
168
+ false
169
+ end
170
+
171
+ # See +replacement?+.
172
+ def replaced?
173
+ false
131
174
  end
132
175
 
133
176
  # The App Store has no base plans: each duration is its own product.
@@ -137,7 +180,7 @@ module Pay
137
180
 
138
181
  # The plan of +Tillbell.plans+ whose +product_id+ is this App Store product, or nil.
139
182
  def plan
140
- Tillbell.plan(product_id: processor_plan)
183
+ Tillbell.plan(app_store_product_id: processor_plan)
141
184
  end
142
185
 
143
186
  # The App Store has no pause.
@@ -202,6 +245,12 @@ module Pay
202
245
  end
203
246
 
204
247
  private
248
+ # True when the pending changes take back a cancellation before it took effect: the end
249
+ # date goes away while the subscription stays active (not an expired one bought again).
250
+ def reactivated?
251
+ status == "active" && !status_changed? && ends_at_changed? && ends_at.nil?
252
+ end
253
+
205
254
  # Pay status from what Apple last said, at the time of the sync. Apple notifies every
206
255
  # change (renewal, expiry, billing retry, refund), so the status stays current as long
207
256
  # 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,19 @@ 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
+
33
+ # In-App Purchase key of App Store Connect, only for bin/rails tillbell:app_store:backfill_charges,
34
+ # which records the App Store payments made before Tillbell recorded them.
35
+ # config.apple.issuer_id = Rails.application.credentials.dig(:tillbell, :apple_issuer_id)
36
+ # config.apple.key_id = Rails.application.credentials.dig(:tillbell, :apple_key_id)
37
+ # config.apple.private_key = Rails.application.credentials.dig(:tillbell, :apple_private_key)
38
+
26
39
  # Who is buying. Evaluated in the controller and the view of the paywall.
27
40
  # config.current_owner = -> { current_user }
28
41