tillbell 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,178 @@
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
+ # The page where a customer asks Apple for a refund: only Apple refunds App Store
50
+ # purchases, the app cannot. Apple then notifies the refund, which revokes the subscription.
51
+ REFUND_URL = "https://reportaproblem.apple.com".freeze
52
+
53
+ class << self
54
+ # The certificates a chain must end at. Only specs change it.
55
+ attr_writer :root_certificates
56
+
57
+ def root_certificates
58
+ @root_certificates || [ ROOT_CERTIFICATE ]
59
+ end
60
+
61
+ # True when +token+ looks like a JWS from the App Store rather than a Google Play purchase
62
+ # token. It says nothing about its validity: see +verify_transaction!+.
63
+ def jws?(token)
64
+ parts = token.to_s.split(".")
65
+ parts.size == 3 && JSON.parse(Base64.urlsafe_decode64(parts.first)).key?("x5c")
66
+ rescue ArgumentError, JSON::ParserError, NoMethodError
67
+ false
68
+ end
69
+
70
+ # Verifies a signed transaction (+VerificationResult.jwsRepresentation+ in StoreKit 2)
71
+ # and returns its payload. Raises +Tillbell::Error+ unless Apple signed it, for this app
72
+ # (+config.apple.bundle_id+), and it is an auto-renewable subscription.
73
+ #
74
+ # With +config.apple.allow_xcode_transactions+, in development and test, a transaction
75
+ # Xcode signed for StoreKit Testing is accepted without checking its signature, as
76
+ # Apple's own server libraries do for the Xcode environment. Notifications never come from
77
+ # Xcode and are always fully verified.
78
+ def verify_transaction!(jws)
79
+ transaction = xcode_transaction(jws) || decode!(jws)
80
+ raise Error, "The transaction belongs to another app (#{transaction["bundleId"]})" unless transaction["bundleId"] == bundle_id
81
+ raise Error, "The transaction is not an auto-renewable subscription" unless transaction["type"] == AUTO_RENEWABLE
82
+
83
+ transaction
84
+ end
85
+
86
+ # Verifies the +signedPayload+ of an App Store Server Notification and returns its
87
+ # payload. Raises +Tillbell::Error+ unless Apple signed it for this app.
88
+ def verify_notification!(signed_payload)
89
+ notification = decode!(signed_payload)
90
+ # Most notifications describe one transaction under "data"; a summary of a mass
91
+ # extension and an external purchase notification put the app under their own key.
92
+ app = %w[data summary externalPurchaseToken].filter_map { |key| notification.dig(key, "bundleId") }.first
93
+ raise Error, "The notification belongs to another app" unless app == bundle_id
94
+
95
+ notification
96
+ end
97
+
98
+ # Handles a verified notification: re-reads the transaction and renewal information it
99
+ # carries and updates the subscription. Notifications without a transaction (a test
100
+ # notification, a summary of a mass extension) and those about other in-app purchases of
101
+ # the app change nothing.
102
+ def handle_notification(notification)
103
+ data = notification["data"] || {}
104
+ return if data["signedTransactionInfo"].blank?
105
+
106
+ transaction = decode!(data["signedTransactionInfo"])
107
+ return unless transaction["type"] == AUTO_RENEWABLE
108
+
109
+ transaction = verify_transaction!(data["signedTransactionInfo"])
110
+ renewal_info = data["signedRenewalInfo"].presence&.then { |jws| decode!(jws) }
111
+ Pay::AppStore::Subscription.sync(transaction, renewal_info)
112
+ end
113
+
114
+ # The bundle identifier of the iOS app, from +config.apple.bundle_id+. Raises
115
+ # +Tillbell::Error+ when it is not set.
116
+ def bundle_id
117
+ Tillbell.apple.bundle_id.presence || raise(Error, "Tillbell.apple.bundle_id is not set")
118
+ end
119
+
120
+ # Verifies the signature and certificate chain of any App Store JWS and returns its
121
+ # payload, without looking at what it contains.
122
+ #
123
+ # ponytail: no revocation check (OCSP) of the chain; Apple's own library makes it optional.
124
+ def decode!(jws)
125
+ header = JSON.parse(Base64.urlsafe_decode64(jws.to_s.split(".").first.to_s))
126
+ raise Error, "Unexpected JWS algorithm #{header["alg"].inspect}" unless header["alg"] == "ES256"
127
+
128
+ leaf, intermediate, root = certificates = Array(header["x5c"]).map { |der| OpenSSL::X509::Certificate.new(Base64.strict_decode64(der)) }
129
+ raise Error, "The JWS does not carry a three-certificate chain" unless certificates.size == 3
130
+ raise Error, "The certificate chain does not end at Apple's root" unless root_certificates.any? { |trusted| trusted.to_der == root.to_der }
131
+ raise Error, "The certificates were not issued to sign App Store data" unless extension?(leaf, LEAF_OID) && extension?(intermediate, INTERMEDIATE_OID)
132
+
133
+ payload, = JWT.decode(jws, leaf.public_key, true, algorithm: "ES256")
134
+ verify_chain!(leaf, intermediate, root, at: signed_at(payload))
135
+ payload
136
+ # NoMethodError: a header that is not a JSON object, or an x5c that does not hold strings,
137
+ # posted by anyone to the public notification endpoint.
138
+ rescue JWT::DecodeError, OpenSSL::X509::CertificateError, ArgumentError, JSON::ParserError, TypeError, NoMethodError => error
139
+ raise Error, "Invalid App Store signature: #{error.message}"
140
+ end
141
+
142
+ # Milliseconds since the epoch, as Apple sends every date, to a time.
143
+ def time(milliseconds)
144
+ Time.zone.at(milliseconds / 1000.0) if milliseconds.present?
145
+ end
146
+
147
+ private
148
+ # The payload of +jws+ when it is an Xcode StoreKit Testing transaction that the
149
+ # configuration allows, otherwise nil. Never in production or staging: without Apple's
150
+ # signature, anyone could forge one.
151
+ def xcode_transaction(jws)
152
+ return unless Tillbell.apple.allow_xcode_transactions && Rails.env.local?
153
+
154
+ payload, = JWT.decode(jws, nil, false)
155
+ payload if payload["environment"] == "Xcode"
156
+ rescue JWT::DecodeError
157
+ nil
158
+ end
159
+
160
+ # The chain must be valid when Apple signed the data, not only today: a transaction
161
+ # signed a year ago, restored now, may carry a leaf certificate that has since expired.
162
+ def verify_chain!(leaf, intermediate, root, at:)
163
+ store = OpenSSL::X509::Store.new
164
+ store.add_cert(root)
165
+ store.time = at
166
+ raise Error, "Untrusted certificate chain: #{store.error_string}" unless store.verify(leaf, [ intermediate ])
167
+ end
168
+
169
+ def signed_at(payload)
170
+ time(payload["signedDate"]) || Time.current
171
+ end
172
+
173
+ def extension?(certificate, oid)
174
+ certificate.extensions.any? { |extension| extension.oid == oid }
175
+ end
176
+ end
177
+ end
178
+ end
@@ -27,7 +27,8 @@ module Tillbell
27
27
  # any, +online+ lists what the Play Console has.
28
28
  def initialize(online: false, plans: Tillbell.plans)
29
29
  @online = online
30
- @plans = Array(plans).map { |plan| normalize(plan) }
30
+ # App Store plans have nothing to check with Google.
31
+ @plans = Array(plans).map { |plan| normalize(plan) }.select { |plan| plan[:product_id].present? }
31
32
  @results = []
32
33
  end
33
34
 
@@ -8,22 +8,37 @@ module Tillbell
8
8
  class Engine < ::Rails::Engine
9
9
  isolate_namespace Tillbell
10
10
 
11
+ # Display names of the stores, by Pay processor.
12
+ STORE_NAMES = { "google_play" => "Google Play", "app_store" => "App Store" }.freeze
13
+
11
14
  # Real-time developer notifications are verified, stored and queued by Pay (see
12
15
  # Tillbell::NotificationsController). Once Pay's job processes one, Tillbell re-reads
13
16
  # the subscription from Google.
14
17
  initializer "tillbell.notifications" do
15
18
  Pay::Webhooks.delegator.subscribe "google_play", ->(event) { Tillbell::GooglePlay.handle_notification(event) }
19
+ Pay::Webhooks.delegator.subscribe "app_store", ->(event) { Tillbell::AppStore.handle_notification(event) }
16
20
  end
17
21
 
18
22
  # Pay defines +stripe?+, +paddle_billing?+ and the matching scopes for its own
19
- # processors only; this adds the same pair for Google Play.
23
+ # processors only; this adds the same pair for Google Play and the App Store.
20
24
  initializer "tillbell.processor_helpers" do
21
25
  ActiveSupport.on_load(:pay_customer) do
22
26
  scope :google_play, -> { where(processor: "google_play") }
27
+ scope :app_store, -> { where(processor: "app_store") }
23
28
 
24
29
  def google_play?
25
30
  processor == "google_play"
26
31
  end
32
+
33
+ def app_store?
34
+ processor == "app_store"
35
+ end
36
+
37
+ # True for a customer of an app store (Google Play or the App Store), whose
38
+ # subscriptions are managed in the store rather than by the app.
39
+ def store?
40
+ google_play? || app_store?
41
+ end
27
42
  end
28
43
 
29
44
  ActiveSupport.on_load(:pay_subscription) do
@@ -38,21 +53,57 @@ module Tillbell
38
53
 
39
54
  # True when the subscription should give access to what it pays for: it bills
40
55
  # (+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 Google Play: a
42
- # subscription on hold (past_due) comes after Google's grace period, and Google requires
43
- # access to be suspended until the payment succeeds. Combine it with
56
+ # customer can still reach the page where they fix it, except on the stores: a Google Play
57
+ # subscription on hold, or an App Store one in billing retry, is past_due after the
58
+ # store's grace period, and the store requires access to be suspended until the payment
59
+ # succeeds. Combine it with
44
60
  # +Tillbell::Owner#current_subscription+ to decide what an owner may use.
45
61
  def grants_access?
46
- billing? && !paused? && !(google_play? && past_due?)
62
+ billing? && !paused? && !((google_play? || app_store?) && past_due?)
47
63
  end
48
64
 
49
65
  scope :google_play, -> { joins(:customer).where(pay_customers: { processor: "google_play" }) }
66
+ scope :app_store, -> { joins(:customer).where(pay_customers: { processor: "app_store" }) }
50
67
 
51
68
  # True for a subscription bought with Google Play, whatever the owner's default
52
69
  # processor is.
53
70
  def google_play?
54
71
  customer.processor == "google_play"
55
72
  end
73
+
74
+ # True for a subscription bought with the App Store.
75
+ def app_store?
76
+ customer.processor == "app_store"
77
+ end
78
+
79
+ # True for a subscription bought in an app store (Google Play or the App Store). The
80
+ # customer manages it in the store (+manage_url+): the server can neither change its
81
+ # plan nor, for the App Store, stop it.
82
+ def store?
83
+ customer.store?
84
+ end
85
+
86
+ # The name of the store the subscription was bought in, "Google Play" or "App Store",
87
+ # for admin pages and internal alerts; nil for any other processor. Brand names, so
88
+ # they are not translated.
89
+ def store_name
90
+ STORE_NAMES[customer.processor]
91
+ end
92
+
93
+ # True when the subscription gives access and will renew by itself: +grants_access?+,
94
+ # and not canceled with an end date still to come (Pay's +on_grace_period?+). Use it to
95
+ # warn a customer who is about to close their account or switch plans while a renewal
96
+ # is planned.
97
+ def renewing?
98
+ grants_access? && !on_grace_period?
99
+ end
100
+
101
+ # True for a test purchase that costs nothing. Always false here; store subscriptions
102
+ # answer from what the store says (see Pay::AppStore::Subscription#sandbox? and
103
+ # Pay::GooglePlay::Subscription#sandbox?).
104
+ def sandbox?
105
+ false
106
+ end
56
107
  end
57
108
  end
58
109
 
@@ -25,6 +25,36 @@ module Tillbell
25
25
  google_play_subscription&.on_hold? || false
26
26
  end
27
27
 
28
+ # The most relevant subscription bought in an app store (Google Play or the App Store), or
29
+ # nil: the most recent one that is active or paused, otherwise the most recent one.
30
+ def store_subscription
31
+ subscriptions = store_subscriptions
32
+ subscriptions.active_or_paused.first || subscriptions.first
33
+ end
34
+
35
+ # True when the store subscription (see +store_subscription+) is on hold: the payment failed
36
+ # after the store's grace period and access is suspended while the store retries. The
37
+ # customer fixes it in the store (+manage_url+); subscribing again elsewhere would bill
38
+ # twice if the retry succeeds.
39
+ def store_on_hold?
40
+ store_subscription&.on_hold? || false
41
+ end
42
+
43
+ # The most recent store subscription the store still counts as the customer's, with or
44
+ # without access (see +owned?+), or nil. Buying it again would be refused by the store, and
45
+ # buying another way (a web checkout) would bill twice: send the customer to its
46
+ # +manage_url+ instead.
47
+ def owned_store_subscription
48
+ store_subscriptions.find(&:owned?)
49
+ end
50
+
51
+ # The App Store subscriptions that will still renew: only the customer can stop them, in
52
+ # the App Store, so +cancel_billing_subscriptions!+ leaves them unchanged. Show their
53
+ # +manage_url+ before closing the account.
54
+ def subscriptions_to_cancel_in_store
55
+ billing_subscriptions.select { |subscription| subscription.app_store? && subscription.ends_at.nil? }
56
+ end
57
+
28
58
  # The subscription to show and to decide access from, whatever its processor: the one
29
59
  # that renews, then one that is canceled but still running, then one whose payment is
30
60
  # being retried or that is paused; the most recent breaks a tie. Nil without any.
@@ -43,17 +73,27 @@ module Tillbell
43
73
  # Cancels what +billing_subscriptions+ lists, to call before closing or deleting the
44
74
  # account and before changing anything in the database: an error raised afterwards would
45
75
  # 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. Raises +Pay::Error+
76
+ # renewing, the customer keeps access until the end of the paid period. App Store
77
+ # subscriptions cannot be stopped from a server: they are left unchanged, so send the
78
+ # customer to their +manage_url+ before closing the account. Raises +Pay::Error+
47
79
  # (+Tillbell::Error+ for Google Play) when a processor refuses.
48
80
  def cancel_billing_subscriptions!
49
81
  billing_subscriptions.each(&:cancel_now!)
50
82
  end
51
83
 
52
84
  private
85
+ # Subscriptions of the owner's store customers, the most recent first.
86
+ def store_subscriptions
87
+ pay_subscriptions.merge(Pay::Customer.active).where(pay_customers: { processor: %w[google_play app_store] }).order(created_at: :desc)
88
+ end
89
+
90
+ # An App Store subscription that went stale (see Pay::AppStore::Subscription#stale?) is
91
+ # still "active" but must not hide one that grants access.
53
92
  def subscription_standing(subscription)
54
- if subscription.active? && !subscription.on_grace_period? then 0
55
- elsif subscription.active? then 1
56
- elsif subscription.billing? then 2
93
+ active = subscription.active? && !subscription.try(:stale?)
94
+ if active && !subscription.on_grace_period? then 0
95
+ elsif active then 1
96
+ elsif subscription.billing? && !subscription.try(:stale?) then 2
57
97
  else 3
58
98
  end
59
99
  end
@@ -0,0 +1,98 @@
1
+ module Tillbell
2
+ # Builds store subscriptions in a host app's tests, without Apple's signature or a call to
3
+ # Google: what the stores send is built here, then saved by the same code as a real purchase.
4
+ #
5
+ # # spec/rails_helper.rb
6
+ # require "tillbell/test_helpers"
7
+ # RSpec.configure { |config| config.include Tillbell::TestHelpers }
8
+ #
9
+ # create_app_store_subscription(user, product_id: "app.family.monthly")
10
+ # create_google_play_subscription(user, state: "SUBSCRIPTION_STATE_ON_HOLD")
11
+ #
12
+ # Not loaded by +require "tillbell"+: test code only.
13
+ module TestHelpers
14
+ # Records an App Store subscription of +owner+ from +app_store_transaction+ (whose options
15
+ # it takes) and, when given, +renewal_info+ (see +app_store_renewal_info+). Returns the
16
+ # Pay::AppStore::Subscription, and emits the Tillbell events a real purchase would.
17
+ def create_app_store_subscription(owner, renewal_info: nil, **transaction)
18
+ Pay::AppStore::Subscription.sync(app_store_transaction(account_id: tillbell_account_id(owner), **transaction), renewal_info)
19
+ end
20
+
21
+ # Records a Google Play subscription of +owner+ under +purchase_token+ from
22
+ # +google_subscription+ (whose options it takes). Returns the Pay::GooglePlay::Subscription,
23
+ # and emits the Tillbell events a real purchase would.
24
+ def create_google_play_subscription(owner, purchase_token: SecureRandom.hex(16), **response)
25
+ Pay::GooglePlay::Subscription.sync(purchase_token, object: google_subscription(account_id: tillbell_account_id(owner), **response))
26
+ end
27
+
28
+ # The account id the paywall sends for +owner+: Google Play's +obfuscatedAccountId+ and
29
+ # the App Store's +appAccountToken+.
30
+ def tillbell_account_id(owner)
31
+ Pay::GooglePlay::Customer.for(owner).processor_id
32
+ end
33
+
34
+ # A decoded App Store transaction (JWSTransaction) of an auto-renewable subscription, with
35
+ # Apple's keys. +environment+ is "Production", "Sandbox" or "Xcode".
36
+ def app_store_transaction(account_id:, product_id: "premium.monthly", original_transaction_id: "2000000000000001",
37
+ transaction_id: original_transaction_id, purchased_at: Time.current, expires_at: 1.month.from_now,
38
+ revoked_at: nil, environment: "Production", price: nil, currency: nil,
39
+ bundle_id: Tillbell.apple.bundle_id, type: Tillbell::AppStore::AUTO_RENEWABLE)
40
+ {
41
+ "transactionId" => transaction_id, "originalTransactionId" => original_transaction_id, "bundleId" => bundle_id,
42
+ "productId" => product_id, "type" => type, "appAccountToken" => account_id, "environment" => environment,
43
+ "purchaseDate" => apple_time(purchased_at), "expiresDate" => apple_time(expires_at),
44
+ "revocationDate" => apple_time(revoked_at), "signedDate" => apple_time(Time.current),
45
+ "price" => price && (BigDecimal(price.to_s) * 1000).to_i, "currency" => currency
46
+ }.compact
47
+ end
48
+
49
+ # A decoded App Store renewal information (JWSRenewalInfo), as notifications carry it.
50
+ def app_store_renewal_info(product_id: "premium.monthly", auto_renew: true, billing_retry: false, grace_period_ends_at: nil)
51
+ {
52
+ "autoRenewProductId" => product_id, "autoRenewStatus" => auto_renew ? 1 : 0, "isInBillingRetryPeriod" => billing_retry,
53
+ "gracePeriodExpiresDate" => apple_time(grace_period_ends_at), "signedDate" => apple_time(Time.current)
54
+ }.compact
55
+ end
56
+
57
+ # A Google Play Developer API +purchases.subscriptionsv2.get+ response, in the shape
58
+ # Tillbell::GooglePlay.subscription returns (snake_case symbol keys). +test_purchase+ makes
59
+ # it a license tester's purchase.
60
+ def google_subscription(account_id:, state: "SUBSCRIPTION_STATE_ACTIVE", product_id: "premium", base_plan_id: "monthly",
61
+ expiry_time: 1.month.from_now, auto_renewing: true, acknowledged: true, linked_purchase_token: nil,
62
+ recurring_price: nil, deferred_product_id: nil, line_items: nil, test_purchase: false)
63
+ {
64
+ subscription_state: state,
65
+ acknowledgement_state: acknowledged ? "ACKNOWLEDGEMENT_STATE_ACKNOWLEDGED" : "ACKNOWLEDGEMENT_STATE_PENDING",
66
+ external_account_identifiers: { obfuscated_external_account_id: account_id },
67
+ linked_purchase_token: linked_purchase_token,
68
+ test_purchase: ({} if test_purchase),
69
+ line_items: line_items || [
70
+ {
71
+ product_id: product_id,
72
+ expiry_time: expiry_time.utc.iso8601,
73
+ offer_details: { base_plan_id: base_plan_id },
74
+ auto_renewing_plan: { auto_renew_enabled: auto_renewing, recurring_price: recurring_price }.compact,
75
+ deferred_item_replacement: deferred_product_id && { product_id: deferred_product_id }
76
+ }.compact
77
+ ]
78
+ }.compact
79
+ end
80
+
81
+ # Records every Tillbell event emitted while the block runs, as +[name, payload]+ pairs.
82
+ def tillbell_events
83
+ events = []
84
+ subscriber = ActiveSupport::Notifications.subscribe(/\Apay\.tillbell\./) do |name, *, payload|
85
+ events << [ name.delete_prefix("pay.tillbell.").to_sym, payload ]
86
+ end
87
+ yield
88
+ events
89
+ ensure
90
+ ActiveSupport::Notifications.unsubscribe(subscriber)
91
+ end
92
+
93
+ # A time as Apple sends it: milliseconds since the epoch.
94
+ def apple_time(time)
95
+ time && (time.to_f * 1000).to_i
96
+ end
97
+ end
98
+ end
@@ -1,3 +1,3 @@
1
1
  module Tillbell
2
- VERSION = "0.5.1"
2
+ VERSION = "0.7.0"
3
3
  end
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
 
@@ -27,13 +28,25 @@ module Tillbell
27
28
  # The events Tillbell emits, in the order a subscription usually goes through them.
28
29
  # +subscription_updated+ fires for any change; +subscription_renewed+, +payment_failed+,
29
30
  # +payment_recovered+ and +plan_changed+ say which one happened.
31
+ # +subscription_reactivated+ follows a +subscription_canceled+ the customer took back
32
+ # before the end of the period.
30
33
  EVENTS = %i[subscription_created subscription_updated subscription_renewed payment_failed payment_recovered plan_changed
31
- subscription_canceled subscription_expired subscription_revoked purchase_rejected].freeze
34
+ subscription_canceled subscription_reactivated subscription_expired subscription_revoked purchase_rejected].freeze
32
35
 
33
- # A plan the app sells: a Google Play product and its base plan, under a name of your own.
34
- Plan = Data.define(:name, :product_id, :base_plan_id) do
35
- def initialize(name:, product_id:, base_plan_id: nil)
36
- super(name: name.to_sym, product_id: product_id, base_plan_id: base_plan_id)
36
+ # A plan the app sells, under a name of your own: a Google Play product and its base plan,
37
+ # and the App Store product of the same plan. The App Store product id defaults to the Google
38
+ # Play one; an app sold on one store only leaves the other's id out.
39
+ Plan = Data.define(:name, :product_id, :base_plan_id, :app_store_product_id) do
40
+ def initialize(name:, product_id: nil, base_plan_id: nil, app_store_product_id: product_id)
41
+ raise ArgumentError, "plan #{name.inspect} needs a product_id or an app_store_product_id" if product_id.blank? && app_store_product_id.blank?
42
+
43
+ super(name: name.to_sym, product_id: product_id, base_plan_id: base_plan_id, app_store_product_id: app_store_product_id)
44
+ end
45
+
46
+ # The ids the app of +store+ (+:app_store+ or +:google_play+) buys this plan with, as the
47
+ # +product_id+ and +base_plan_id+ of a paywall option. The App Store has no base plans.
48
+ def product_for(store)
49
+ store == :app_store ? { product_id: app_store_product_id, base_plan_id: nil } : { product_id: product_id, base_plan_id: base_plan_id }
37
50
  end
38
51
  end
39
52
 
@@ -45,6 +58,20 @@ module Tillbell
45
58
  # [pubsub_audience] Audience of those requests; defaults to the notification endpoint URL.
46
59
  mattr_accessor :google, default: ActiveSupport::OrderedOptions.new
47
60
 
61
+ # App Store settings.
62
+ #
63
+ # [bundle_id] Bundle identifier of the iOS app, e.g. "com.example.app". Transactions and
64
+ # notifications signed for another app are refused.
65
+ # [allow_xcode_transactions] Accept the transactions Xcode signs locally for StoreKit
66
+ # Testing (a +.storekit+ configuration file), in the development
67
+ # and test environments only. See
68
+ # +Tillbell::AppStore.verify_transaction!+.
69
+ # [stale_after] How long after the end of its period an App Store subscription that no
70
+ # notification renewed or ended keeps giving access, e.g. +16.days+ (set it at
71
+ # least to the billing grace period of your subscriptions). Nil, the default,
72
+ # trusts the last state Apple notified forever.
73
+ mattr_accessor :apple, default: ActiveSupport::OrderedOptions.new
74
+
48
75
  # Returns the Pay owner (usually a User) the current request acts for, or nil.
49
76
  # Evaluated with +instance_exec+ in the controller and in the view, so any helper
50
77
  # available there (+current_user+, +Current.user+, ...) can be used.
@@ -63,11 +90,11 @@ module Tillbell
63
90
  #
64
91
  # config.plans = [
65
92
  # { name: :solo, product_id: "app_solo", base_plan_id: "monthly" },
66
- # { name: :family, product_id: "app_family", base_plan_id: "monthly" }
93
+ # { name: :family, product_id: "app_family", base_plan_id: "monthly", app_store_product_id: "app.family.monthly" }
67
94
  # ]
68
95
  #
69
- # +tillbell:check+ checks them with Google, and +Pay::GooglePlay::Subscription#plan+ finds
70
- # the one a subscription is on.
96
+ # +tillbell:check+ checks the Google Play ones with Google, and +plan+ on a store subscription
97
+ # finds the one it is on.
71
98
  mattr_reader :plans, default: [].freeze
72
99
 
73
100
  # What Hotwire Native writes in the user agent for the bridge components the app
@@ -75,7 +102,27 @@ module Tillbell
75
102
  # list for the paywall to work.
76
103
  NATIVE_USER_AGENT = /bridge-components: \[(?:[^\]]*\s)?tillbell[\s\]]/
77
104
 
105
+ # What Hotwire Native writes in the user agent of each platform, and the store its in-app
106
+ # purchases go through.
107
+ NATIVE_STORES = {
108
+ /\b(?:Hotwire|Turbo) Native iOS\b/ => :app_store,
109
+ /\b(?:Hotwire|Turbo) Native Android\b/ => :google_play
110
+ }.freeze
111
+
78
112
  class << self
113
+ # The store in-app purchases go through in the Hotwire Native app +user_agent+ comes from:
114
+ # +:app_store+ (iOS), +:google_play+ (Android), or nil in a browser. Unlike +native?+, it
115
+ # does not need the +tillbell+ component, so it also answers for app versions that cannot
116
+ # buy yet. Use it for the store rules that apply to the whole app, e.g. the App Store
117
+ # forbids linking to another way to pay:
118
+ #
119
+ # Tillbell.store(request.user_agent) == :app_store
120
+ #
121
+ # Like +native?+, it only picks what to show: a forged user agent gains nothing.
122
+ def store(user_agent)
123
+ NATIVE_STORES.find { |pattern, _store| pattern.match?(user_agent.to_s) }&.last
124
+ end
125
+
79
126
  # True when +user_agent+ comes from a native app that registered the +tillbell+ bridge
80
127
  # component (Android today, iOS later), so a Google Play purchase can start from the
81
128
  # page. Use it to choose between the paywall and another way to pay, e.g. a web checkout:
@@ -90,20 +137,32 @@ module Tillbell
90
137
  end
91
138
 
92
139
  # Sets the catalog of +plans+ from hashes with +name+, +product_id+ and optionally
93
- # +base_plan_id+ (or from +Tillbell::Plan+ objects).
140
+ # +base_plan_id+ and +app_store_product_id+ (or from +Tillbell::Plan+ objects).
141
+ #
142
+ # A Google Play product with several base plans is several plans, while each App Store
143
+ # product is one duration: such plans do not default their App Store product id to the
144
+ # shared Google Play one. Give them their own +app_store_product_id+.
94
145
  def plans=(list)
95
- @@plans = list.map do |plan|
96
- next plan if plan.is_a?(Plan)
97
- raise ArgumentError, "a plan is a hash with :name, :product_id and :base_plan_id, got #{plan.inspect}" unless plan.respond_to?(:to_h) && !plan.nil?
146
+ built = list.map do |plan|
147
+ next [ plan, false ] if plan.is_a?(Plan)
148
+ raise ArgumentError, "a plan is a hash with :name and :product_id or :app_store_product_id, got #{plan.inspect}" unless plan.respond_to?(:to_h) && !plan.nil?
98
149
 
99
- Plan.new(**plan.to_h.symbolize_keys)
150
+ attributes = plan.to_h.symbolize_keys
151
+ [ Plan.new(**attributes), !attributes.key?(:app_store_product_id) ]
152
+ end
153
+ shared = built.filter_map { |plan, _defaulted| plan.app_store_product_id }.tally.select { |_id, count| count > 1 }.keys
154
+ @@plans = built.map do |plan, defaulted|
155
+ defaulted && shared.include?(plan.app_store_product_id) ? plan.with(app_store_product_id: nil) : plan
100
156
  end.freeze
101
157
  end
102
158
 
103
- # Finds a plan of +plans+ by +name+ (a symbol or string) or by Google ids. With a
104
- # +base_plan_id+ that no plan has, falls back to the product's plan when it has only one.
105
- def plan(name = nil, product_id: nil, base_plan_id: nil)
159
+ # Finds a plan of +plans+ by +name+ (a symbol or string), by App Store product id (nil when
160
+ # several plans share it), or by Google ids. With a +base_plan_id+ that no plan has, falls
161
+ # back to the product's plan when it has only one.
162
+ def plan(name = nil, product_id: nil, base_plan_id: nil, app_store_product_id: nil)
106
163
  return plans.find { |plan| plan.name == name.to_sym } if name
164
+ return plans.select { |plan| plan.app_store_product_id == app_store_product_id }.then { |matches| matches.first if matches.one? } if app_store_product_id
165
+ return if product_id.blank?
107
166
 
108
167
  matches = plans.select { |plan| plan.product_id == product_id }
109
168
  matches.find { |plan| plan.base_plan_id == base_plan_id } || (matches.first if matches.one?)