tillbell 0.5.1 → 0.6.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 +4 -4
- data/CHANGELOG.md +22 -0
- data/README.md +45 -5
- data/app/controllers/tillbell/app_store_notifications_controller.rb +35 -0
- data/app/controllers/tillbell/purchases_controller.rb +27 -5
- data/app/models/pay/app_store/customer.rb +49 -0
- data/app/models/pay/app_store/subscription.rb +227 -0
- data/config/routes.rb +3 -0
- data/contract/examples/purchase.reply.pending_approval.json +4 -0
- data/contract/purchase.reply.json +31 -16
- data/lib/generators/tillbell/install/templates/initializer.rb +6 -1
- data/lib/generators/tillbell/install/templates/tillbell_controller.js +9 -5
- data/lib/tillbell/app_store.rb +157 -0
- data/lib/tillbell/engine.rb +18 -5
- data/lib/tillbell/owner.rb +3 -1
- data/lib/tillbell/version.rb +1 -1
- data/lib/tillbell.rb +7 -0
- metadata +26 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 5a030c9d323ef3704d390da2665576a2954d63276ffefd860c944e3fba36a5b0
|
|
4
|
+
data.tar.gz: 0f8fa7153ca08bc85b4eccd33bb5e287920aa63078ef83348ccf860d26323bf0
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: c01db7a93ad7220b2c8a138f11915cb5f8663e44f7759a5ef34188ac2803c260edd93db84c13ad0b5ee5ee075576cf33c0f31ca55b89d0694fb3c2afe75cb451
|
|
7
|
+
data.tar.gz: 9f99bd6f10ba65428ec5b3d942cafbd718462f0f560e14a72e69d69a8873d887f023991065306f7123588614819f0d883d2ce492c5d6a29304e0a007b3d52467
|
data/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,28 @@ All notable changes to this project are documented in this file. The format foll
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.6.0] - 2026-11-11
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- App Store subscriptions, for the iOS app of [tillbell-ios](https://github.com/pmakerhq/tillbell-ios):
|
|
14
|
+
`Pay::AppStore::Customer` and `Pay::AppStore::Subscription`, set up with
|
|
15
|
+
`config.apple.bundle_id`. `POST /tillbell/purchases` accepts the signed StoreKit 2
|
|
16
|
+
transaction the iOS app sends as its purchase token, verifies Apple's signature without
|
|
17
|
+
calling Apple and checks its `appAccountToken`, the same account id as Google Play.
|
|
18
|
+
- `POST /tillbell/notifications/app_store` receives App Store Server Notifications (version 2),
|
|
19
|
+
verified and processed through Pay like Google Play notifications: renewals, billing retries,
|
|
20
|
+
grace periods, expiries and refunds keep the subscription current.
|
|
21
|
+
- `app_store?` and the `app_store` scope on Pay customers and subscriptions. `grants_access?`
|
|
22
|
+
gives no access to an App Store subscription in billing retry after the grace period.
|
|
23
|
+
|
|
24
|
+
### Changed
|
|
25
|
+
|
|
26
|
+
- Bridge contract: a `pending` purchase reply may come without `purchaseToken`, for an App Store
|
|
27
|
+
purchase waiting for approval (Ask to Buy). The paywall controller then shows the pending
|
|
28
|
+
message. Copy the new `tillbell_controller.js` from the generator template into your app.
|
|
29
|
+
- The bridge contract documents how tillbell-ios maps it to StoreKit 2.
|
|
30
|
+
|
|
9
31
|
## [0.5.1] - 2026-11-11
|
|
10
32
|
|
|
11
33
|
### Changed
|
data/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
**Self-hosted in-app subscriptions for Rails + Hotwire Native apps, built on [Pay](https://github.com/pay-rails/pay).**
|
|
7
7
|
|
|
8
|
-
Your Android app sells subscriptions through Google Play. Your Rails app verifies them, acknowledges them and keeps them in sync. No third-party service sits between the store and your server, and no extra table is added:
|
|
8
|
+
Your Android app sells subscriptions through Google Play, your iOS app through the App Store. Your Rails app verifies them, acknowledges them and keeps them in sync. No third-party service sits between the store and your server, and no extra table is added: store subscriptions are regular `Pay::Subscription` records, right next to your Stripe ones.
|
|
9
9
|
|
|
10
10
|
```ruby
|
|
11
11
|
user.pay_subscriptions.active # Stripe and Google Play together
|
|
@@ -14,7 +14,7 @@ subscription.active? # same rules as for Stripe
|
|
|
14
14
|
```
|
|
15
15
|
|
|
16
16
|
> [!NOTE]
|
|
17
|
-
> **Status: v0.
|
|
17
|
+
> **Status: v0.6.** Google Play is verified with real purchases. App Store support (StoreKit 2, with [tillbell-ios](https://github.com/pmakerhq/tillbell-ios)) is new: it is unit tested but not yet verified with real purchases.
|
|
18
18
|
|
|
19
19
|
## Table of contents
|
|
20
20
|
|
|
@@ -29,6 +29,7 @@ subscription.active? # same rules as for Stripe
|
|
|
29
29
|
- [Subscriptions and statuses](#subscriptions-and-statuses)
|
|
30
30
|
- [Events](#events)
|
|
31
31
|
- [Google Play setup](#google-play-setup)
|
|
32
|
+
- [App Store setup](#app-store-setup)
|
|
32
33
|
- [Security](#security)
|
|
33
34
|
- [Troubleshooting](#troubleshooting)
|
|
34
35
|
- [The Tillbell family](#the-tillbell-family)
|
|
@@ -53,7 +54,7 @@ Assuming a Rails 8 app with a `User` model and Pay installed:
|
|
|
53
54
|
|
|
54
55
|
```sh
|
|
55
56
|
bundle add pay
|
|
56
|
-
bundle add tillbell
|
|
57
|
+
bundle add tillbell
|
|
57
58
|
bin/rails generate tillbell:install
|
|
58
59
|
```
|
|
59
60
|
|
|
@@ -128,6 +129,7 @@ The page and the native app talk through a [Hotwire Native bridge component](htt
|
|
|
128
129
|
| Pay | 12+, installed and migrated |
|
|
129
130
|
| Active Job | A queue backend in production (Solid Queue, Sidekiq, ...) |
|
|
130
131
|
| Android app | Hotwire Native with [tillbell-android](https://github.com/pmakerhq/tillbell-android) |
|
|
132
|
+
| iOS app (optional) | Hotwire Native with [tillbell-ios](https://github.com/pmakerhq/tillbell-ios) |
|
|
131
133
|
|
|
132
134
|
## Installation
|
|
133
135
|
|
|
@@ -593,10 +595,48 @@ The Play Console's success message only means the message reached **your topic**
|
|
|
593
595
|
| The buy button stays disabled | The app does not register the `tillbell` component, or this is a browser | Use the app with [tillbell-android](https://github.com/pmakerhq/tillbell-android) |
|
|
594
596
|
| A purchase works, then Google refunds it after three days | Your server did not acknowledge it: the purchase endpoint failed | Look at your logs for the purchase request; run `bin/rails tillbell:check` |
|
|
595
597
|
|
|
598
|
+
## App Store setup
|
|
599
|
+
|
|
600
|
+
The iOS app ([tillbell-ios](https://github.com/pmakerhq/tillbell-ios)) talks to the same paywall with the same messages. Nothing is needed from Apple to verify a purchase: the iOS app sends the transaction signed by Apple, and Tillbell checks the signature against Apple Root CA - G3, which ships with the gem.
|
|
601
|
+
|
|
602
|
+
1. **Set the bundle id** of the iOS app in `config/initializers/tillbell.rb`. Transactions and notifications signed for another app are refused.
|
|
603
|
+
|
|
604
|
+
```ruby
|
|
605
|
+
config.apple.bundle_id = "com.example.app"
|
|
606
|
+
```
|
|
607
|
+
|
|
608
|
+
2. **Create the subscriptions** in App Store Connect (*Monetization* › *Subscriptions*), in one subscription group, ordered from the highest level to the lowest: the App Store decides from the levels whether a plan change is an upgrade (now) or a downgrade (at the next renewal).
|
|
609
|
+
|
|
610
|
+
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
|
+
|
|
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:
|
|
613
|
+
|
|
614
|
+
```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 %>
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
A plan change needs nothing more on iOS: the App Store replaces the subscription of the same group by itself.
|
|
623
|
+
|
|
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.
|
|
625
|
+
|
|
626
|
+
How App Store subscriptions differ:
|
|
627
|
+
|
|
628
|
+
- `processor_id` is the `originalTransactionId`, which stays the same across renewals and plan changes.
|
|
629
|
+
- 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
|
+
- 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.
|
|
632
|
+
- 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.
|
|
634
|
+
- 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
|
+
|
|
596
636
|
## Security
|
|
597
637
|
|
|
598
638
|
- 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.
|
|
599
|
-
- Every purchase is read back from Google, and
|
|
639
|
+
- Every Google Play purchase is read back from Google, and its `obfuscatedAccountId` must match the signed-in owner's account id. Every App Store transaction and notification must be signed by Apple (a certificate chain to Apple Root CA - G3) for the configured bundle id, and a transaction's `appAccountToken` must match the owner's account id.
|
|
600
640
|
- Notifications must carry an OIDC token signed by Google for the configured service account. Anything else gets a 401.
|
|
601
641
|
- The account id sent to Google is a random UUID, never an e-mail or a database id.
|
|
602
642
|
- Purchase tokens are never logged in full.
|
|
@@ -623,7 +663,7 @@ Problems on Google's side (credentials, permissions, notifications) have their o
|
|
|
623
663
|
|---|---|
|
|
624
664
|
| **tillbell-rails** (this repo) | Rails engine: Pay processor, purchase verification, notifications, paywall helper |
|
|
625
665
|
| [tillbell-android](https://github.com/pmakerhq/tillbell-android) | Hotwire Native bridge component for Google Play Billing |
|
|
626
|
-
| [tillbell-ios](https://github.com/pmakerhq/tillbell-ios) | Hotwire Native bridge component for StoreKit 2
|
|
666
|
+
| [tillbell-ios](https://github.com/pmakerhq/tillbell-ios) | Hotwire Native bridge component for StoreKit 2 |
|
|
627
667
|
|
|
628
668
|
## Getting help
|
|
629
669
|
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
module Tillbell
|
|
2
|
+
# Receives App Store Server Notifications (version 2), the URL set as the "Production
|
|
3
|
+
# Server URL" (and "Sandbox Server URL") in App Store Connect.
|
|
4
|
+
#
|
|
5
|
+
# The endpoint is public, so every notification must carry Apple's signature for this app;
|
|
6
|
+
# anything else gets a 401. Verified notifications are stored and processed by Pay
|
|
7
|
+
# (+Pay::Webhook+ and +Pay::Webhooks::ProcessJob+), like Google Play notifications, and
|
|
8
|
+
# answered with a 200 straight away. A non-2xx answer would make Apple send it again.
|
|
9
|
+
class AppStoreNotificationsController < Pay::Webhooks::BaseController
|
|
10
|
+
private
|
|
11
|
+
def verified_event
|
|
12
|
+
AppStore.verify_notification!(params[:signedPayload])
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# "DID_RENEW" becomes "did_renew".
|
|
16
|
+
def event_type(notification)
|
|
17
|
+
notification["notificationType"].to_s.downcase
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def queue?(notification)
|
|
21
|
+
Rails.logger.info "[Tillbell] App Store notification #{notification["notificationType"]}" \
|
|
22
|
+
"#{" subtype=#{notification["subtype"]}" if notification["subtype"]}"
|
|
23
|
+
notification.dig("data", "signedTransactionInfo").present?
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# Pay derives the processor from the controller name; this one is not named after it.
|
|
27
|
+
def processor
|
|
28
|
+
"app_store"
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def invalid_signature
|
|
32
|
+
head :unauthorized
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
module Tillbell
|
|
2
|
-
# Records a Google Play purchase made in the native app.
|
|
2
|
+
# Records a Google Play or App Store purchase made in the native app.
|
|
3
3
|
#
|
|
4
|
-
# The paywall posts the purchase token here as soon as the
|
|
5
|
-
#
|
|
6
|
-
#
|
|
4
|
+
# The paywall posts the purchase token here as soon as the purchase sheet succeeds, so
|
|
5
|
+
# access is granted without waiting for a notification. The token is never trusted:
|
|
6
|
+
# Tillbell reads a Google Play purchase from Google, verifies Apple's signature of an App
|
|
7
|
+
# Store transaction (the token the iOS app sends), and checks that the purchase was made
|
|
7
8
|
# with the account id of the signed-in owner.
|
|
8
9
|
#
|
|
9
10
|
# Inherits from +Tillbell.parent_controller+ to run the host app's authentication and
|
|
@@ -15,13 +16,16 @@ module Tillbell
|
|
|
15
16
|
# (a pending purchase does not).
|
|
16
17
|
# [verifying] Google could not be reached; the purchase is verified in the background.
|
|
17
18
|
# [rejected] The purchase belongs to another account.
|
|
18
|
-
# [invalid] Google does not know this purchase token
|
|
19
|
+
# [invalid] Google does not know this purchase token, or Apple did not sign this
|
|
20
|
+
# transaction for this app.
|
|
19
21
|
class PurchasesController < Tillbell.parent_controller.constantize
|
|
20
22
|
def create
|
|
21
23
|
owner = instance_exec(&Tillbell.current_owner)
|
|
22
24
|
return head :unauthorized if owner.nil?
|
|
23
25
|
|
|
24
26
|
purchase_token = params.expect(:purchase_token)
|
|
27
|
+
return record_app_store_transaction(owner, purchase_token) if AppStore.jws?(purchase_token)
|
|
28
|
+
|
|
25
29
|
purchase = GooglePlay.subscription(purchase_token)
|
|
26
30
|
|
|
27
31
|
if GooglePlay.account_id(purchase) == Pay::GooglePlay::Customer.for(owner).processor_id
|
|
@@ -40,5 +44,23 @@ module Tillbell
|
|
|
40
44
|
|
|
41
45
|
render json: { status: "invalid" }, status: :unprocessable_content
|
|
42
46
|
end
|
|
47
|
+
|
|
48
|
+
private
|
|
49
|
+
# The signature is checked on the server, without calling Apple, so there is no
|
|
50
|
+
# "verifying" answer for the App Store.
|
|
51
|
+
def record_app_store_transaction(owner, jws)
|
|
52
|
+
transaction = AppStore.verify_transaction!(jws)
|
|
53
|
+
|
|
54
|
+
if transaction["appAccountToken"].to_s.downcase == Pay::GooglePlay::Customer.for(owner).processor_id
|
|
55
|
+
subscription = Pay::AppStore::Subscription.sync(transaction)
|
|
56
|
+
render json: { status: "verified", active: subscription.active?, subscription_status: subscription.status }
|
|
57
|
+
else
|
|
58
|
+
Tillbell.instrument(:purchase_rejected, owner: owner, purchase_token: Tillbell.redact(transaction["originalTransactionId"]))
|
|
59
|
+
render json: { status: "rejected" }, status: :forbidden
|
|
60
|
+
end
|
|
61
|
+
rescue Tillbell::Error => error
|
|
62
|
+
Rails.logger.info "[Tillbell] Refusing an App Store transaction: #{error.message}"
|
|
63
|
+
render json: { status: "invalid" }, status: :unprocessable_content
|
|
64
|
+
end
|
|
43
65
|
end
|
|
44
66
|
end
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
module Pay
|
|
2
|
+
module AppStore
|
|
3
|
+
# The Pay customer behind every App Store purchase of an owner.
|
|
4
|
+
#
|
|
5
|
+
# Its +processor_id+ is the same UUID as the owner's Pay::GooglePlay::Customer: the paywall
|
|
6
|
+
# sends one +obfuscatedAccountId+ to both apps, and the iOS app passes it to StoreKit as the
|
|
7
|
+
# +appAccountToken+. Apple returns it in every signed transaction, which is how Tillbell
|
|
8
|
+
# knows which owner a transaction belongs to.
|
|
9
|
+
class Customer < Pay::Customer
|
|
10
|
+
has_many :subscriptions, dependent: :destroy, class_name: "Pay::AppStore::Subscription"
|
|
11
|
+
|
|
12
|
+
# Returns the App Store customer of +owner+, creating it on first use.
|
|
13
|
+
def self.for(owner)
|
|
14
|
+
owner.add_payment_processor(:app_store, processor_id: Pay::GooglePlay::Customer.for(owner).processor_id)
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
# The App Store customer whose account id is +app_account_token+, or nil when no owner
|
|
18
|
+
# has it. Created on first use for an owner who only had a Google Play customer.
|
|
19
|
+
def self.for_account_id(app_account_token)
|
|
20
|
+
account_id = app_account_token.to_s.downcase
|
|
21
|
+
return if account_id.blank?
|
|
22
|
+
|
|
23
|
+
find_by(processor_id: account_id) || Pay::GooglePlay::Customer.find_by(processor_id: account_id)&.then { |customer| self.for(customer.owner) }
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# App Store customers exist only in this database.
|
|
27
|
+
def api_record
|
|
28
|
+
self
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def update_api_record(**)
|
|
32
|
+
self
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Store purchases always start in the native app, never on the server.
|
|
36
|
+
def subscribe(**)
|
|
37
|
+
raise Tillbell::Error, "App Store subscriptions are purchased in the iOS app, through the Tillbell paywall"
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def charge(*)
|
|
41
|
+
raise Tillbell::Error, "The App Store does not support server-side charges"
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def add_payment_method(*, **)
|
|
45
|
+
raise Tillbell::Error, "The App Store manages payment methods in the customer's Apple Account"
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
end
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
module Pay
|
|
2
|
+
module AppStore
|
|
3
|
+
# An App Store auto-renewable subscription, stored as a Pay subscription.
|
|
4
|
+
#
|
|
5
|
+
# [processor_id] The +originalTransactionId+: it stays the same across renewals and plan
|
|
6
|
+
# changes within the subscription group.
|
|
7
|
+
# [processor_plan] The App Store product id of the latest transaction.
|
|
8
|
+
# [status] A Pay status: "active" (including the billing grace period), "past_due" (Apple
|
|
9
|
+
# retries a failed payment, without access) or "canceled" (expired or refunded).
|
|
10
|
+
# [ends_at] Set once the subscription will not renew, has expired or was refunded.
|
|
11
|
+
# [object] The last signed transaction payload, for debugging.
|
|
12
|
+
#
|
|
13
|
+
# App Store details live in +data+: +environment+ ("Production" or "Sandbox"),
|
|
14
|
+
# +transaction_id+, +purchase_date_ms+, +renewal_signed_ms+, +auto_renewing+,
|
|
15
|
+
# +auto_renew_product_id+, +billing_retry+, +grace_period_ends_at+ and +revoked_at+.
|
|
16
|
+
class Subscription < Pay::Subscription
|
|
17
|
+
store_accessor :data, :environment, :transaction_id, :purchase_date_ms, :renewal_signed_ms, :auto_renewing, :auto_renew_product_id,
|
|
18
|
+
:billing_retry, :grace_period_ends_at, :revoked_at
|
|
19
|
+
|
|
20
|
+
class << self
|
|
21
|
+
# Saves a verified transaction (see Tillbell::AppStore.verify_transaction!) and, when a
|
|
22
|
+
# notification brings it, its renewal information, then emits the matching Tillbell
|
|
23
|
+
# events. A transaction older than the one already saved changes nothing, so restores
|
|
24
|
+
# and notifications can arrive in any order.
|
|
25
|
+
#
|
|
26
|
+
# Returns the subscription, or nil when the transaction was not made through Tillbell
|
|
27
|
+
# (no known +appAccountToken+) or was shared through Family Sharing: the family member's
|
|
28
|
+
# transaction is not the buyer's purchase, and the iOS app never reports it either.
|
|
29
|
+
def sync(transaction, renewal_info = nil)
|
|
30
|
+
return if transaction["inAppOwnershipType"] == "FAMILY_SHARED"
|
|
31
|
+
|
|
32
|
+
pay_customer = Pay::AppStore::Customer.for_account_id(transaction["appAccountToken"])
|
|
33
|
+
if pay_customer.nil?
|
|
34
|
+
Rails.logger.warn "[Tillbell] Ignoring App Store transaction #{transaction["transactionId"]}: unknown account"
|
|
35
|
+
return
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
subscription, events = save_from_apple(pay_customer, transaction, renewal_info)
|
|
39
|
+
events.each { |event| Tillbell.instrument(event, subscription) }
|
|
40
|
+
subscription
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
private
|
|
44
|
+
# Applies the transaction under a row lock, so a purchase request and a notification
|
|
45
|
+
# for the same subscription serialize and only one of them emits each event.
|
|
46
|
+
def save_from_apple(pay_customer, transaction, renewal_info)
|
|
47
|
+
attempts = 0
|
|
48
|
+
begin
|
|
49
|
+
transaction(requires_new: true) do
|
|
50
|
+
subscription = pay_customer.subscriptions.lock.find_or_initialize_by(processor_id: transaction["originalTransactionId"])
|
|
51
|
+
subscription.apply(transaction, renewal_info)
|
|
52
|
+
events = subscription.events_for_changes
|
|
53
|
+
subscription.save!
|
|
54
|
+
[ subscription, events ]
|
|
55
|
+
end
|
|
56
|
+
rescue ActiveRecord::RecordNotUnique
|
|
57
|
+
# Another process inserted the row first; a second attempt finds it and locks it.
|
|
58
|
+
attempts += 1
|
|
59
|
+
attempts == 1 ? retry : raise
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Assigns what +transaction+ and +renewal_info+ (Apple payloads) say, without saving.
|
|
65
|
+
# The renewal information only comes with notifications; without it, the last known
|
|
66
|
+
# renewal state is kept.
|
|
67
|
+
def apply(transaction, renewal_info = nil)
|
|
68
|
+
if new_record? || transaction["purchaseDate"].to_i >= purchase_date_ms.to_i
|
|
69
|
+
assign_attributes(
|
|
70
|
+
name: Tillbell.subscription_name.call(product_id: transaction["productId"], base_plan_id: nil),
|
|
71
|
+
processor_plan: transaction["productId"],
|
|
72
|
+
current_period_end: Tillbell::AppStore.time(transaction["expiresDate"]),
|
|
73
|
+
object: transaction,
|
|
74
|
+
environment: transaction["environment"],
|
|
75
|
+
transaction_id: transaction["transactionId"],
|
|
76
|
+
purchase_date_ms: transaction["purchaseDate"].to_i,
|
|
77
|
+
revoked_at: Tillbell::AppStore.time(transaction["revocationDate"])&.iso8601
|
|
78
|
+
)
|
|
79
|
+
end
|
|
80
|
+
# Renewal information is ordered by its own signing date, so a stale notification processed
|
|
81
|
+
# late (a billing failure after the renewal that fixed it) never brings back old state.
|
|
82
|
+
if renewal_info && renewal_info["signedDate"].to_i >= renewal_signed_ms.to_i
|
|
83
|
+
assign_attributes(
|
|
84
|
+
renewal_signed_ms: renewal_info["signedDate"].to_i,
|
|
85
|
+
auto_renewing: renewal_info["autoRenewStatus"] == 1,
|
|
86
|
+
auto_renew_product_id: renewal_info["autoRenewProductId"],
|
|
87
|
+
billing_retry: renewal_info["isInBillingRetryPeriod"] == true,
|
|
88
|
+
grace_period_ends_at: Tillbell::AppStore.time(renewal_info["gracePeriodExpiresDate"])&.iso8601
|
|
89
|
+
)
|
|
90
|
+
end
|
|
91
|
+
self.auto_renewing = true if auto_renewing.nil?
|
|
92
|
+
assign_status
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
# The Tillbell event that describes the pending changes, or nil when nothing a host app
|
|
96
|
+
# cares about changed. Called before saving. Same rules as for Google Play.
|
|
97
|
+
def event_for_changes
|
|
98
|
+
return :subscription_created if new_record?
|
|
99
|
+
return if (changed - %w[object updated_at]).none?
|
|
100
|
+
return :subscription_revoked if revoked_at_changed? && revoked?
|
|
101
|
+
return :subscription_expired if status_changed? && status == "canceled"
|
|
102
|
+
return :subscription_canceled if ends_at_changed? && ends_at.present? && status == "active"
|
|
103
|
+
|
|
104
|
+
:subscription_updated
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# Every event the pending changes call for, the generic one first. Called before saving.
|
|
108
|
+
def events_for_changes
|
|
109
|
+
events = [ event_for_changes ]
|
|
110
|
+
if persisted? && !revoked?
|
|
111
|
+
events << :plan_changed if processor_plan_changed?
|
|
112
|
+
events << :subscription_renewed if status == "active" && !processor_plan_changed? && current_period_end_changed? && current_period_end_was.present? && current_period_end > current_period_end_was
|
|
113
|
+
# The store accessor's +_was+ answers nil for a value that did not change.
|
|
114
|
+
was_retrying = billing_retry_changed? ? billing_retry_was : billing_retry
|
|
115
|
+
events << :payment_failed if billing_retry && !was_retrying
|
|
116
|
+
events << :payment_recovered if !billing_retry && was_retrying
|
|
117
|
+
end
|
|
118
|
+
events.compact
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# True when Apple refunded the purchase.
|
|
122
|
+
def revoked?
|
|
123
|
+
revoked_at.present?
|
|
124
|
+
end
|
|
125
|
+
|
|
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.
|
|
129
|
+
def sandbox?
|
|
130
|
+
environment == "Sandbox"
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
# The App Store has no base plans: each duration is its own product.
|
|
134
|
+
def base_plan_id
|
|
135
|
+
nil
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# The plan of +Tillbell.plans+ whose +product_id+ is this App Store product, or nil.
|
|
139
|
+
def plan
|
|
140
|
+
Tillbell.plan(product_id: processor_plan)
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# The App Store has no pause.
|
|
144
|
+
def paused?
|
|
145
|
+
false
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
# True while Apple retries a failed payment and the customer keeps access.
|
|
149
|
+
def in_grace_period?
|
|
150
|
+
billing_retry && status == "active"
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# True when the payment failed after the grace period and access is suspended.
|
|
154
|
+
def on_hold?
|
|
155
|
+
status == "past_due"
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# True while the App Store still counts the subscription as the customer's: buying it
|
|
159
|
+
# again would be answered "already subscribed".
|
|
160
|
+
def owned?
|
|
161
|
+
!revoked? && (status == "active" || status == "past_due")
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# The product the customer moves to at the next renewal (a downgrade within the
|
|
165
|
+
# subscription group), or nil.
|
|
166
|
+
def deferred_product_id
|
|
167
|
+
auto_renew_product_id if auto_renew_product_id.present? && auto_renew_product_id != processor_plan
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# True while a plan change waits for the next renewal. See +deferred_product_id+.
|
|
171
|
+
def plan_change_pending?
|
|
172
|
+
deferred_product_id.present?
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
# The App Store page where the customer manages their subscriptions.
|
|
176
|
+
def manage_url
|
|
177
|
+
Tillbell::AppStore::MANAGE_URL
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
# A stable identifier of the subscription that is safe to send to a third party.
|
|
181
|
+
def token_digest
|
|
182
|
+
Digest::SHA256.hexdigest(processor_id).first(16)
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
# Only the customer can stop an App Store subscription, in the App Store: Apple offers no
|
|
186
|
+
# server API for it. This leaves the subscription unchanged instead of raising, so
|
|
187
|
+
# deleting an owner (Pay calls +cancel_now!+) never fails on it. Tell the customer to
|
|
188
|
+
# cancel it in the App Store (+manage_url+) before deleting their account.
|
|
189
|
+
def cancel(**)
|
|
190
|
+
Rails.logger.warn "[Tillbell] App Store subscription #{token_digest} can only be canceled by the customer, in the App Store"
|
|
191
|
+
self
|
|
192
|
+
end
|
|
193
|
+
|
|
194
|
+
def cancel_now!(**)
|
|
195
|
+
cancel
|
|
196
|
+
end
|
|
197
|
+
|
|
198
|
+
%i[swap pause resume change_quantity].each do |method_name|
|
|
199
|
+
define_method(method_name) do |*, **|
|
|
200
|
+
raise Tillbell::Error, "App Store subscriptions cannot #{method_name} from the server; use the app or the App Store"
|
|
201
|
+
end
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
private
|
|
205
|
+
# Pay status from what Apple last said, at the time of the sync. Apple notifies every
|
|
206
|
+
# change (renewal, expiry, billing retry, refund), so the status stays current as long
|
|
207
|
+
# as App Store Server Notifications reach the app.
|
|
208
|
+
def assign_status
|
|
209
|
+
expires_at = current_period_end
|
|
210
|
+
grace_ends_at = grace_period_ends_at.present? ? Time.zone.parse(grace_period_ends_at) : nil
|
|
211
|
+
|
|
212
|
+
self.status, self.ends_at =
|
|
213
|
+
if revoked?
|
|
214
|
+
[ "canceled", Time.zone.parse(revoked_at) ]
|
|
215
|
+
elsif expires_at.nil? || expires_at.future?
|
|
216
|
+
[ "active", (expires_at unless auto_renewing) ]
|
|
217
|
+
elsif billing_retry && grace_ends_at&.future?
|
|
218
|
+
[ "active", nil ]
|
|
219
|
+
elsif billing_retry
|
|
220
|
+
[ "past_due", nil ]
|
|
221
|
+
else
|
|
222
|
+
[ "canceled", expires_at ]
|
|
223
|
+
end
|
|
224
|
+
end
|
|
225
|
+
end
|
|
226
|
+
end
|
|
227
|
+
end
|
data/config/routes.rb
CHANGED
|
@@ -4,4 +4,7 @@ Tillbell::Engine.routes.draw do
|
|
|
4
4
|
|
|
5
5
|
# Pub/Sub push endpoint for Google Play real-time developer notifications.
|
|
6
6
|
post "notifications/google_play", to: "notifications#create", as: :google_play_notifications
|
|
7
|
+
|
|
8
|
+
# App Store Server Notifications (version 2), set as the server URL in App Store Connect.
|
|
9
|
+
post "notifications/app_store", to: "app_store_notifications#create", as: :app_store_notifications
|
|
7
10
|
end
|
|
@@ -18,37 +18,52 @@
|
|
|
18
18
|
"unavailable",
|
|
19
19
|
"error"
|
|
20
20
|
],
|
|
21
|
-
"description": "purchased: Purchase.PurchaseState.PURCHASED. pending: PurchaseState.PENDING (e.g. cash payment). canceled: USER_CANCELED. already_owned: ITEM_ALREADY_OWNED. unavailable: BILLING_UNAVAILABLE, SERVICE_UNAVAILABLE or FEATURE_NOT_SUPPORTED. error: anything else."
|
|
21
|
+
"description": "purchased: Purchase.PurchaseState.PURCHASED, or a verified StoreKit transaction. pending: PurchaseState.PENDING (e.g. cash payment), or a StoreKit purchase waiting for approval (Ask to Buy), which has no purchaseToken yet. canceled: USER_CANCELED. already_owned: ITEM_ALREADY_OWNED, or a current App Store entitlement. unavailable: BILLING_UNAVAILABLE, SERVICE_UNAVAILABLE or FEATURE_NOT_SUPPORTED. error: anything else."
|
|
22
22
|
},
|
|
23
23
|
"productId": {
|
|
24
24
|
"type": "string",
|
|
25
25
|
"minLength": 1,
|
|
26
|
-
"description": "Google Play product id (subscription id)."
|
|
26
|
+
"description": "Google Play product id (subscription id), or App Store product identifier."
|
|
27
27
|
},
|
|
28
28
|
"purchaseToken": {
|
|
29
29
|
"type": "string",
|
|
30
30
|
"minLength": 1,
|
|
31
|
-
"description": "Purchase.getPurchaseToken()."
|
|
31
|
+
"description": "Purchase.getPurchaseToken(), or the signed StoreKit transaction (VerificationResult.jwsRepresentation)."
|
|
32
32
|
},
|
|
33
33
|
"message": {
|
|
34
34
|
"type": "string",
|
|
35
35
|
"description": "Developer-facing detail, never shown to the customer."
|
|
36
36
|
}
|
|
37
37
|
},
|
|
38
|
-
"
|
|
39
|
-
|
|
40
|
-
"
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
|
|
38
|
+
"allOf": [
|
|
39
|
+
{
|
|
40
|
+
"if": {
|
|
41
|
+
"properties": {
|
|
42
|
+
"result": {
|
|
43
|
+
"const": "purchased"
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
"then": {
|
|
48
|
+
"required": [
|
|
49
|
+
"productId",
|
|
50
|
+
"purchaseToken"
|
|
51
|
+
]
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"if": {
|
|
56
|
+
"properties": {
|
|
57
|
+
"result": {
|
|
58
|
+
"const": "pending"
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
"then": {
|
|
63
|
+
"required": [
|
|
64
|
+
"productId"
|
|
44
65
|
]
|
|
45
66
|
}
|
|
46
67
|
}
|
|
47
|
-
|
|
48
|
-
"then": {
|
|
49
|
-
"required": [
|
|
50
|
-
"productId",
|
|
51
|
-
"purchaseToken"
|
|
52
|
-
]
|
|
53
|
-
}
|
|
68
|
+
]
|
|
54
69
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Tillbell: Google Play subscriptions stored as Pay subscriptions.
|
|
1
|
+
# Tillbell: Google Play and App Store subscriptions stored as Pay subscriptions.
|
|
2
2
|
# See https://github.com/pmakerhq/tillbell-rails#configuration
|
|
3
3
|
#
|
|
4
4
|
# The two values below come from Google: the README's "Google Play setup" has the credentials
|
|
@@ -18,6 +18,11 @@ Tillbell.configure do |config|
|
|
|
18
18
|
# Audience of the Pub/Sub OIDC token, if it is not the notification endpoint URL.
|
|
19
19
|
# config.google.pubsub_audience = "https://example.com/tillbell/notifications/google_play"
|
|
20
20
|
|
|
21
|
+
# Bundle identifier of the iOS app, to accept App Store purchases (tillbell-ios). Set the
|
|
22
|
+
# App Store Server Notifications URL to https://<your host>/tillbell/notifications/app_store
|
|
23
|
+
# (version 2) in App Store Connect.
|
|
24
|
+
# config.apple.bundle_id = "com.example.app"
|
|
25
|
+
|
|
21
26
|
# Who is buying. Evaluated in the controller and the view of the paywall.
|
|
22
27
|
# config.current_owner = -> { current_user }
|
|
23
28
|
|
|
@@ -23,7 +23,8 @@ export default class extends BridgeComponent {
|
|
|
23
23
|
this.loadPrices()
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
// Asks Google Play for the localized price of every plan,
|
|
26
|
+
// Asks the store (Google Play or the App Store) for the localized price of every plan,
|
|
27
|
+
// then enables the paywall.
|
|
27
28
|
loadPrices() {
|
|
28
29
|
const products = this.planTargets.map((plan) => this.#productOf(plan))
|
|
29
30
|
|
|
@@ -42,7 +43,7 @@ export default class extends BridgeComponent {
|
|
|
42
43
|
})
|
|
43
44
|
}
|
|
44
45
|
|
|
45
|
-
// Opens the
|
|
46
|
+
// Opens the store's purchase sheet for the checked plan.
|
|
46
47
|
purchase() {
|
|
47
48
|
const plan = this.planTargets.find((plan) => plan.checked && !plan.disabled)
|
|
48
49
|
if (!plan) return
|
|
@@ -55,7 +56,7 @@ export default class extends BridgeComponent {
|
|
|
55
56
|
this.send("purchase", message, ({ data }) => this.#handlePurchase(data))
|
|
56
57
|
}
|
|
57
58
|
|
|
58
|
-
// Records again the purchases
|
|
59
|
+
// Records again the purchases the store knows for this device's account.
|
|
59
60
|
restorePurchases() {
|
|
60
61
|
this.#setBusy(true)
|
|
61
62
|
this.send("restore", {}, async ({ data }) => {
|
|
@@ -68,7 +69,7 @@ export default class extends BridgeComponent {
|
|
|
68
69
|
})
|
|
69
70
|
}
|
|
70
71
|
|
|
71
|
-
// Opens the
|
|
72
|
+
// Opens the store page where the customer manages the subscription.
|
|
72
73
|
manage() {
|
|
73
74
|
const plan = this.planTargets.find((plan) => plan.checked) ?? this.planTargets[0]
|
|
74
75
|
this.send("manage", { productId: plan ? plan.dataset.productId : null })
|
|
@@ -78,6 +79,9 @@ export default class extends BridgeComponent {
|
|
|
78
79
|
switch (result) {
|
|
79
80
|
case "purchased":
|
|
80
81
|
case "pending":
|
|
82
|
+
// An App Store purchase waiting for approval (Ask to Buy) has no token yet: the
|
|
83
|
+
// server records it from Apple's notification once it is approved.
|
|
84
|
+
if (!purchaseToken) return this.#fail("pending")
|
|
81
85
|
return this.#finish(await this.#record(purchaseToken))
|
|
82
86
|
case "already_owned":
|
|
83
87
|
return this.restorePurchases()
|
|
@@ -90,7 +94,7 @@ export default class extends BridgeComponent {
|
|
|
90
94
|
}
|
|
91
95
|
}
|
|
92
96
|
|
|
93
|
-
// Sends the purchase token to Rails, which verifies it with Google.
|
|
97
|
+
// Sends the purchase token to Rails, which verifies it with Google or Apple.
|
|
94
98
|
async #record(purchaseToken) {
|
|
95
99
|
this.#showStatus("verifying")
|
|
96
100
|
try {
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
require "base64"
|
|
2
|
+
require "json"
|
|
3
|
+
require "jwt"
|
|
4
|
+
require "openssl"
|
|
5
|
+
|
|
6
|
+
module Tillbell
|
|
7
|
+
# Verifies what the App Store signs: the transactions StoreKit 2 hands to the iOS app, and the
|
|
8
|
+
# App Store Server Notifications (version 2). Both are JWS (compact JSON Web Signatures)
|
|
9
|
+
# signed with ES256 by a certificate chain that ends at Apple Root CA - G3, given in the
|
|
10
|
+
# +x5c+ header. Verifying needs no key and no call to Apple, so the purchase endpoint answers
|
|
11
|
+
# at once and never has to retry later.
|
|
12
|
+
#
|
|
13
|
+
# Every method returns the decoded payload as a hash with Apple's camelCase string keys.
|
|
14
|
+
module AppStore
|
|
15
|
+
# Apple Root CA - G3, from https://www.apple.com/certificateauthority/AppleRootCA-G3.cer
|
|
16
|
+
# SHA-256 fingerprint 63:34:3A:BF:B8:9A:6A:03:EB:B5:7E:9B:3F:5F:A7:BE:7C:4F:5C:75:6F:30:17:B3:A8:C4:88:C3:65:3E:91:79,
|
|
17
|
+
# valid until 2039.
|
|
18
|
+
ROOT_CERTIFICATE = OpenSSL::X509::Certificate.new(<<~PEM).freeze
|
|
19
|
+
-----BEGIN CERTIFICATE-----
|
|
20
|
+
MIICQzCCAcmgAwIBAgIILcX8iNLFS5UwCgYIKoZIzj0EAwMwZzEbMBkGA1UEAwwS
|
|
21
|
+
QXBwbGUgUm9vdCBDQSAtIEczMSYwJAYDVQQLDB1BcHBsZSBDZXJ0aWZpY2F0aW9u
|
|
22
|
+
IEF1dGhvcml0eTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UEBhMCVVMwHhcN
|
|
23
|
+
MTQwNDMwMTgxOTA2WhcNMzkwNDMwMTgxOTA2WjBnMRswGQYDVQQDDBJBcHBsZSBS
|
|
24
|
+
b290IENBIC0gRzMxJjAkBgNVBAsMHUFwcGxlIENlcnRpZmljYXRpb24gQXV0aG9y
|
|
25
|
+
aXR5MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzB2MBAGByqGSM49
|
|
26
|
+
AgEGBSuBBAAiA2IABJjpLz1AcqTtkyJygRMc3RCV8cWjTnHcFBbZDuWmBSp3ZHtf
|
|
27
|
+
TjjTuxxEtX/1H7YyYl3J6YRbTzBPEVoA/VhYDKX1DyxNB0cTddqXl5dvMVztK517
|
|
28
|
+
IDvYuVTZXpmkOlEKMaNCMEAwHQYDVR0OBBYEFLuw3qFYM4iapIqZ3r6966/ayySr
|
|
29
|
+
MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2gA
|
|
30
|
+
MGUCMQCD6cHEFl4aXTQY2e3v9GwOAEZLuN+yRhHFD/3meoyhpmvOwgPUnPWTxnS4
|
|
31
|
+
at+qIxUCMG1mihDK1A3UT82NQz60imOlM27jbdoXt2QfyFMm+YhidDkLF1vLUagM
|
|
32
|
+
6BgD56KyKA==
|
|
33
|
+
-----END CERTIFICATE-----
|
|
34
|
+
PEM
|
|
35
|
+
|
|
36
|
+
# Extensions Apple puts on the certificates that sign App Store data: the leaf (Mac App
|
|
37
|
+
# Store and iTunes Store receipt signing) and the intermediate (Apple Worldwide Developer
|
|
38
|
+
# Relations). A chain without them was not issued for this purpose.
|
|
39
|
+
LEAF_OID = "1.2.840.113635.100.6.11.1".freeze
|
|
40
|
+
INTERMEDIATE_OID = "1.2.840.113635.100.6.2.1".freeze
|
|
41
|
+
|
|
42
|
+
# +productType+ of an auto-renewable subscription transaction.
|
|
43
|
+
AUTO_RENEWABLE = "Auto-Renewable Subscription".freeze
|
|
44
|
+
|
|
45
|
+
# The page where a customer manages (cancels, changes, resubscribes) their App Store
|
|
46
|
+
# subscriptions. Same page as the +manage+ message of the iOS component.
|
|
47
|
+
MANAGE_URL = "https://apps.apple.com/account/subscriptions".freeze
|
|
48
|
+
|
|
49
|
+
class << self
|
|
50
|
+
# The certificates a chain must end at. Only specs change it.
|
|
51
|
+
attr_writer :root_certificates
|
|
52
|
+
|
|
53
|
+
def root_certificates
|
|
54
|
+
@root_certificates || [ ROOT_CERTIFICATE ]
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# True when +token+ looks like a JWS from the App Store rather than a Google Play purchase
|
|
58
|
+
# token. It says nothing about its validity: see +verify_transaction!+.
|
|
59
|
+
def jws?(token)
|
|
60
|
+
parts = token.to_s.split(".")
|
|
61
|
+
parts.size == 3 && JSON.parse(Base64.urlsafe_decode64(parts.first)).key?("x5c")
|
|
62
|
+
rescue ArgumentError, JSON::ParserError, NoMethodError
|
|
63
|
+
false
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# Verifies a signed transaction (+VerificationResult.jwsRepresentation+ in StoreKit 2)
|
|
67
|
+
# and returns its payload. Raises +Tillbell::Error+ unless Apple signed it, for this app
|
|
68
|
+
# (+config.apple.bundle_id+), and it is an auto-renewable subscription.
|
|
69
|
+
def verify_transaction!(jws)
|
|
70
|
+
transaction = decode!(jws)
|
|
71
|
+
raise Error, "The transaction belongs to another app (#{transaction["bundleId"]})" unless transaction["bundleId"] == bundle_id
|
|
72
|
+
raise Error, "The transaction is not an auto-renewable subscription" unless transaction["type"] == AUTO_RENEWABLE
|
|
73
|
+
|
|
74
|
+
transaction
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# Verifies the +signedPayload+ of an App Store Server Notification and returns its
|
|
78
|
+
# payload. Raises +Tillbell::Error+ unless Apple signed it for this app.
|
|
79
|
+
def verify_notification!(signed_payload)
|
|
80
|
+
notification = decode!(signed_payload)
|
|
81
|
+
# Most notifications describe one transaction under "data"; a summary of a mass
|
|
82
|
+
# extension and an external purchase notification put the app under their own key.
|
|
83
|
+
app = %w[data summary externalPurchaseToken].filter_map { |key| notification.dig(key, "bundleId") }.first
|
|
84
|
+
raise Error, "The notification belongs to another app" unless app == bundle_id
|
|
85
|
+
|
|
86
|
+
notification
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# Handles a verified notification: re-reads the transaction and renewal information it
|
|
90
|
+
# carries and updates the subscription. Notifications without a transaction (a test
|
|
91
|
+
# notification, a summary of a mass extension) and those about other in-app purchases of
|
|
92
|
+
# the app change nothing.
|
|
93
|
+
def handle_notification(notification)
|
|
94
|
+
data = notification["data"] || {}
|
|
95
|
+
return if data["signedTransactionInfo"].blank?
|
|
96
|
+
|
|
97
|
+
transaction = decode!(data["signedTransactionInfo"])
|
|
98
|
+
return unless transaction["type"] == AUTO_RENEWABLE
|
|
99
|
+
|
|
100
|
+
transaction = verify_transaction!(data["signedTransactionInfo"])
|
|
101
|
+
renewal_info = data["signedRenewalInfo"].presence&.then { |jws| decode!(jws) }
|
|
102
|
+
Pay::AppStore::Subscription.sync(transaction, renewal_info)
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
# The bundle identifier of the iOS app, from +config.apple.bundle_id+. Raises
|
|
106
|
+
# +Tillbell::Error+ when it is not set.
|
|
107
|
+
def bundle_id
|
|
108
|
+
Tillbell.apple.bundle_id.presence || raise(Error, "Tillbell.apple.bundle_id is not set")
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
# Verifies the signature and certificate chain of any App Store JWS and returns its
|
|
112
|
+
# payload, without looking at what it contains.
|
|
113
|
+
#
|
|
114
|
+
# ponytail: no revocation check (OCSP) of the chain; Apple's own library makes it optional.
|
|
115
|
+
def decode!(jws)
|
|
116
|
+
header = JSON.parse(Base64.urlsafe_decode64(jws.to_s.split(".").first.to_s))
|
|
117
|
+
raise Error, "Unexpected JWS algorithm #{header["alg"].inspect}" unless header["alg"] == "ES256"
|
|
118
|
+
|
|
119
|
+
leaf, intermediate, root = certificates = Array(header["x5c"]).map { |der| OpenSSL::X509::Certificate.new(Base64.strict_decode64(der)) }
|
|
120
|
+
raise Error, "The JWS does not carry a three-certificate chain" unless certificates.size == 3
|
|
121
|
+
raise Error, "The certificate chain does not end at Apple's root" unless root_certificates.any? { |trusted| trusted.to_der == root.to_der }
|
|
122
|
+
raise Error, "The certificates were not issued to sign App Store data" unless extension?(leaf, LEAF_OID) && extension?(intermediate, INTERMEDIATE_OID)
|
|
123
|
+
|
|
124
|
+
payload, = JWT.decode(jws, leaf.public_key, true, algorithm: "ES256")
|
|
125
|
+
verify_chain!(leaf, intermediate, root, at: signed_at(payload))
|
|
126
|
+
payload
|
|
127
|
+
# NoMethodError: a header that is not a JSON object, or an x5c that does not hold strings,
|
|
128
|
+
# posted by anyone to the public notification endpoint.
|
|
129
|
+
rescue JWT::DecodeError, OpenSSL::X509::CertificateError, ArgumentError, JSON::ParserError, TypeError, NoMethodError => error
|
|
130
|
+
raise Error, "Invalid App Store signature: #{error.message}"
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
# Milliseconds since the epoch, as Apple sends every date, to a time.
|
|
134
|
+
def time(milliseconds)
|
|
135
|
+
Time.zone.at(milliseconds / 1000.0) if milliseconds.present?
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
private
|
|
139
|
+
# The chain must be valid when Apple signed the data, not only today: a transaction
|
|
140
|
+
# signed a year ago, restored now, may carry a leaf certificate that has since expired.
|
|
141
|
+
def verify_chain!(leaf, intermediate, root, at:)
|
|
142
|
+
store = OpenSSL::X509::Store.new
|
|
143
|
+
store.add_cert(root)
|
|
144
|
+
store.time = at
|
|
145
|
+
raise Error, "Untrusted certificate chain: #{store.error_string}" unless store.verify(leaf, [ intermediate ])
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def signed_at(payload)
|
|
149
|
+
time(payload["signedDate"]) || Time.current
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
def extension?(certificate, oid)
|
|
153
|
+
certificate.extensions.any? { |extension| extension.oid == oid }
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
end
|
|
157
|
+
end
|
data/lib/tillbell/engine.rb
CHANGED
|
@@ -13,17 +13,23 @@ module Tillbell
|
|
|
13
13
|
# the subscription from Google.
|
|
14
14
|
initializer "tillbell.notifications" do
|
|
15
15
|
Pay::Webhooks.delegator.subscribe "google_play", ->(event) { Tillbell::GooglePlay.handle_notification(event) }
|
|
16
|
+
Pay::Webhooks.delegator.subscribe "app_store", ->(event) { Tillbell::AppStore.handle_notification(event) }
|
|
16
17
|
end
|
|
17
18
|
|
|
18
19
|
# Pay defines +stripe?+, +paddle_billing?+ and the matching scopes for its own
|
|
19
|
-
# processors only; this adds the same pair for Google Play.
|
|
20
|
+
# processors only; this adds the same pair for Google Play and the App Store.
|
|
20
21
|
initializer "tillbell.processor_helpers" do
|
|
21
22
|
ActiveSupport.on_load(:pay_customer) do
|
|
22
23
|
scope :google_play, -> { where(processor: "google_play") }
|
|
24
|
+
scope :app_store, -> { where(processor: "app_store") }
|
|
23
25
|
|
|
24
26
|
def google_play?
|
|
25
27
|
processor == "google_play"
|
|
26
28
|
end
|
|
29
|
+
|
|
30
|
+
def app_store?
|
|
31
|
+
processor == "app_store"
|
|
32
|
+
end
|
|
27
33
|
end
|
|
28
34
|
|
|
29
35
|
ActiveSupport.on_load(:pay_subscription) do
|
|
@@ -38,21 +44,28 @@ module Tillbell
|
|
|
38
44
|
|
|
39
45
|
# True when the subscription should give access to what it pays for: it bills
|
|
40
46
|
# (+billing?+) and is not paused. A payment the processor retries keeps access, so the
|
|
41
|
-
# customer can still reach the page where they fix it, except on
|
|
42
|
-
# subscription on hold
|
|
43
|
-
# access to be suspended until the payment
|
|
47
|
+
# customer can still reach the page where they fix it, except on the stores: a Google Play
|
|
48
|
+
# subscription on hold, or an App Store one in billing retry, is past_due after the
|
|
49
|
+
# store's grace period, and the store requires access to be suspended until the payment
|
|
50
|
+
# succeeds. Combine it with
|
|
44
51
|
# +Tillbell::Owner#current_subscription+ to decide what an owner may use.
|
|
45
52
|
def grants_access?
|
|
46
|
-
billing? && !paused? && !(google_play? && past_due?)
|
|
53
|
+
billing? && !paused? && !((google_play? || app_store?) && past_due?)
|
|
47
54
|
end
|
|
48
55
|
|
|
49
56
|
scope :google_play, -> { joins(:customer).where(pay_customers: { processor: "google_play" }) }
|
|
57
|
+
scope :app_store, -> { joins(:customer).where(pay_customers: { processor: "app_store" }) }
|
|
50
58
|
|
|
51
59
|
# True for a subscription bought with Google Play, whatever the owner's default
|
|
52
60
|
# processor is.
|
|
53
61
|
def google_play?
|
|
54
62
|
customer.processor == "google_play"
|
|
55
63
|
end
|
|
64
|
+
|
|
65
|
+
# True for a subscription bought with the App Store.
|
|
66
|
+
def app_store?
|
|
67
|
+
customer.processor == "app_store"
|
|
68
|
+
end
|
|
56
69
|
end
|
|
57
70
|
end
|
|
58
71
|
|
data/lib/tillbell/owner.rb
CHANGED
|
@@ -43,7 +43,9 @@ module Tillbell
|
|
|
43
43
|
# Cancels what +billing_subscriptions+ lists, to call before closing or deleting the
|
|
44
44
|
# account and before changing anything in the database: an error raised afterwards would
|
|
45
45
|
# leave a closed account that is still billed. Google Play subscriptions only stop
|
|
46
|
-
# renewing, the customer keeps access until the end of the paid period.
|
|
46
|
+
# renewing, the customer keeps access until the end of the paid period. App Store
|
|
47
|
+
# subscriptions cannot be stopped from a server: they are left unchanged, so send the
|
|
48
|
+
# customer to their +manage_url+ before closing the account. Raises +Pay::Error+
|
|
47
49
|
# (+Tillbell::Error+ for Google Play) when a processor refuses.
|
|
48
50
|
def cancel_billing_subscriptions!
|
|
49
51
|
billing_subscriptions.each(&:cancel_now!)
|
data/lib/tillbell/version.rb
CHANGED
data/lib/tillbell.rb
CHANGED
|
@@ -2,6 +2,7 @@ require "pay"
|
|
|
2
2
|
require "tillbell/version"
|
|
3
3
|
require "tillbell/engine"
|
|
4
4
|
require "tillbell/google_play"
|
|
5
|
+
require "tillbell/app_store"
|
|
5
6
|
require "tillbell/check"
|
|
6
7
|
require "tillbell/owner"
|
|
7
8
|
|
|
@@ -45,6 +46,12 @@ module Tillbell
|
|
|
45
46
|
# [pubsub_audience] Audience of those requests; defaults to the notification endpoint URL.
|
|
46
47
|
mattr_accessor :google, default: ActiveSupport::OrderedOptions.new
|
|
47
48
|
|
|
49
|
+
# App Store settings.
|
|
50
|
+
#
|
|
51
|
+
# [bundle_id] Bundle identifier of the iOS app, e.g. "com.example.app". Transactions and
|
|
52
|
+
# notifications signed for another app are refused.
|
|
53
|
+
mattr_accessor :apple, default: ActiveSupport::OrderedOptions.new
|
|
54
|
+
|
|
48
55
|
# Returns the Pay owner (usually a User) the current request acts for, or nil.
|
|
49
56
|
# Evaluated with +instance_exec+ in the controller and in the view, so any helper
|
|
50
57
|
# available there (+current_user+, +Current.user+, ...) can be used.
|
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.
|
|
4
|
+
version: 0.6.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- pmakerhq
|
|
@@ -65,6 +65,26 @@ dependencies:
|
|
|
65
65
|
- - ">="
|
|
66
66
|
- !ruby/object:Gem::Version
|
|
67
67
|
version: '1.11'
|
|
68
|
+
- !ruby/object:Gem::Dependency
|
|
69
|
+
name: jwt
|
|
70
|
+
requirement: !ruby/object:Gem::Requirement
|
|
71
|
+
requirements:
|
|
72
|
+
- - ">="
|
|
73
|
+
- !ruby/object:Gem::Version
|
|
74
|
+
version: '2.2'
|
|
75
|
+
- - "<"
|
|
76
|
+
- !ruby/object:Gem::Version
|
|
77
|
+
version: '4'
|
|
78
|
+
type: :runtime
|
|
79
|
+
prerelease: false
|
|
80
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
81
|
+
requirements:
|
|
82
|
+
- - ">="
|
|
83
|
+
- !ruby/object:Gem::Version
|
|
84
|
+
version: '2.2'
|
|
85
|
+
- - "<"
|
|
86
|
+
- !ruby/object:Gem::Version
|
|
87
|
+
version: '4'
|
|
68
88
|
description: 'Tillbell adds a Google Play processor to the Pay gem: server-side purchase
|
|
69
89
|
verification, acknowledgment, real-time developer notifications and a paywall that
|
|
70
90
|
talks to a Hotwire Native bridge component.'
|
|
@@ -75,11 +95,14 @@ files:
|
|
|
75
95
|
- CHANGELOG.md
|
|
76
96
|
- MIT-LICENSE
|
|
77
97
|
- README.md
|
|
98
|
+
- app/controllers/tillbell/app_store_notifications_controller.rb
|
|
78
99
|
- app/controllers/tillbell/notifications_controller.rb
|
|
79
100
|
- app/controllers/tillbell/purchases_controller.rb
|
|
80
101
|
- app/helpers/tillbell/paywall_builder.rb
|
|
81
102
|
- app/helpers/tillbell/paywall_helper.rb
|
|
82
103
|
- app/jobs/tillbell/sync_job.rb
|
|
104
|
+
- app/models/pay/app_store/customer.rb
|
|
105
|
+
- app/models/pay/app_store/subscription.rb
|
|
83
106
|
- app/models/pay/google_play/customer.rb
|
|
84
107
|
- app/models/pay/google_play/subscription.rb
|
|
85
108
|
- config/locales/de.yml
|
|
@@ -95,6 +118,7 @@ files:
|
|
|
95
118
|
- contract/examples/purchase.reply.canceled.json
|
|
96
119
|
- contract/examples/purchase.reply.error.json
|
|
97
120
|
- contract/examples/purchase.reply.pending.json
|
|
121
|
+
- contract/examples/purchase.reply.pending_approval.json
|
|
98
122
|
- contract/examples/purchase.reply.purchased.json
|
|
99
123
|
- contract/examples/purchase.reply.unavailable.json
|
|
100
124
|
- contract/examples/purchase.request.json
|
|
@@ -115,6 +139,7 @@ files:
|
|
|
115
139
|
- lib/generators/tillbell/install/templates/tillbell_controller.js
|
|
116
140
|
- lib/tasks/tillbell.rake
|
|
117
141
|
- lib/tillbell.rb
|
|
142
|
+
- lib/tillbell/app_store.rb
|
|
118
143
|
- lib/tillbell/check.rb
|
|
119
144
|
- lib/tillbell/engine.rb
|
|
120
145
|
- lib/tillbell/google_play.rb
|