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 +4 -4
- data/CHANGELOG.md +59 -0
- data/README.md +70 -14
- data/app/helpers/tillbell/paywall_builder.rb +40 -11
- data/app/helpers/tillbell/paywall_helper.rb +10 -0
- data/app/models/pay/app_store/charge.rb +141 -0
- data/app/models/pay/app_store/customer.rb +1 -0
- data/app/models/pay/app_store/subscription.rb +55 -6
- data/app/models/pay/google_play/subscription.rb +11 -2
- data/lib/generators/tillbell/install/templates/initializer.rb +13 -0
- data/lib/generators/tillbell/install/templates/tillbell_controller.js +56 -5
- data/lib/tasks/tillbell.rake +15 -0
- data/lib/tillbell/app_store.rb +112 -1
- data/lib/tillbell/check.rb +2 -1
- data/lib/tillbell/engine.rb +38 -0
- data/lib/tillbell/owner.rb +41 -3
- data/lib/tillbell/test_helpers.rb +98 -0
- data/lib/tillbell/version.rb +1 -1
- data/lib/tillbell.rb +73 -16
- metadata +3 -1
|
@@ -6,12 +6,20 @@
|
|
|
6
6
|
// "tillbell" bridge component. Everywhere else the paywall keeps its buttons disabled
|
|
7
7
|
// and shows its fallback, so a purchase can never start without the native app.
|
|
8
8
|
//
|
|
9
|
-
// Events dispatched on the paywall element, for your own code to listen to
|
|
10
|
-
//
|
|
11
|
-
//
|
|
9
|
+
// Events dispatched on the paywall element, for your own code to listen to (analytics, for
|
|
10
|
+
// example, without changing this file):
|
|
11
|
+
// tillbell:verified the purchase grants access (detail: the server's answer, with
|
|
12
|
+
// subscription_status). Cancel the event to stay on the page instead of
|
|
13
|
+
// going to the success URL.
|
|
12
14
|
// tillbell:status a status message is shown (detail: { key, message }).
|
|
15
|
+
//
|
|
16
|
+
// The last prices the store gave are kept on the device and shown while it answers again, so
|
|
17
|
+
// the paywall does not open with empty prices. They are only shown: buying waits for the store,
|
|
18
|
+
// whose purchase sheet shows the price actually charged.
|
|
13
19
|
import { BridgeComponent } from "@hotwired/hotwire-native-bridge"
|
|
14
20
|
|
|
21
|
+
const PRICES_KEY = "tillbell:prices"
|
|
22
|
+
|
|
15
23
|
export default class extends BridgeComponent {
|
|
16
24
|
static component = "tillbell"
|
|
17
25
|
static targets = ["plan", "price", "action", "status", "fallback"]
|
|
@@ -20,6 +28,7 @@ export default class extends BridgeComponent {
|
|
|
20
28
|
connect() {
|
|
21
29
|
super.connect()
|
|
22
30
|
this.fallbackTargets.forEach((element) => element.hidden = true)
|
|
31
|
+
this.#showKeptPrices()
|
|
23
32
|
this.loadPrices()
|
|
24
33
|
}
|
|
25
34
|
|
|
@@ -29,14 +38,19 @@ export default class extends BridgeComponent {
|
|
|
29
38
|
const products = this.planTargets.map((plan) => this.#productOf(plan))
|
|
30
39
|
|
|
31
40
|
this.send("products", { products }, ({ data }) => {
|
|
32
|
-
if (data.result !== "ok")
|
|
41
|
+
if (data.result !== "ok") {
|
|
42
|
+
this.#priceTargetsOf().forEach(({ price }) => { if (price) price.textContent = "" })
|
|
43
|
+
return this.#showStatus(data.result === "unavailable" ? "unavailable" : "error")
|
|
44
|
+
}
|
|
45
|
+
this.#keepPrices(data.products)
|
|
33
46
|
|
|
34
47
|
this.planTargets.forEach((plan) => {
|
|
35
48
|
const { productId, basePlanId } = this.#productOf(plan)
|
|
36
49
|
const product = data.products.find((p) => p.productId === productId && (p.basePlanId ?? null) === basePlanId)
|
|
37
50
|
const price = plan.closest("label")?.querySelector("[data-tillbell-target~='price']")
|
|
38
51
|
|
|
39
|
-
|
|
52
|
+
// A product the store no longer offers loses its kept price.
|
|
53
|
+
if (price) price.textContent = product ? product.formattedPrice : ""
|
|
40
54
|
plan.disabled = !product
|
|
41
55
|
})
|
|
42
56
|
this.#setBusy(false)
|
|
@@ -141,6 +155,43 @@ export default class extends BridgeComponent {
|
|
|
141
155
|
this.actionTargets.forEach((element) => element.disabled = busy)
|
|
142
156
|
}
|
|
143
157
|
|
|
158
|
+
#priceTargetsOf() {
|
|
159
|
+
return this.planTargets.map((plan) => ({ plan, price: plan.closest("label")?.querySelector("[data-tillbell-target~='price']") }))
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
#showKeptPrices() {
|
|
163
|
+
const prices = this.#keptPrices()
|
|
164
|
+
this.planTargets.forEach((plan) => {
|
|
165
|
+
const price = plan.closest("label")?.querySelector("[data-tillbell-target~='price']")
|
|
166
|
+
const kept = prices[this.#priceKey(this.#productOf(plan))]
|
|
167
|
+
if (price && typeof kept === "string") price.textContent = kept
|
|
168
|
+
})
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
#keepPrices(products) {
|
|
172
|
+
const prices = this.#keptPrices()
|
|
173
|
+
products.forEach((product) => prices[this.#priceKey(product)] = product.formattedPrice)
|
|
174
|
+
try {
|
|
175
|
+
localStorage.setItem(PRICES_KEY, JSON.stringify(prices))
|
|
176
|
+
} catch {
|
|
177
|
+
// Storage full or blocked: the next paywall waits for the store, as without it.
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Storage can be missing, blocked or hold anything: then no price is kept.
|
|
182
|
+
#keptPrices() {
|
|
183
|
+
try {
|
|
184
|
+
const prices = JSON.parse(localStorage.getItem(PRICES_KEY))
|
|
185
|
+
return prices && typeof prices === "object" ? prices : {}
|
|
186
|
+
} catch {
|
|
187
|
+
return {}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
#priceKey({ productId, basePlanId }) {
|
|
192
|
+
return `${productId}:${basePlanId ?? ""}`
|
|
193
|
+
}
|
|
194
|
+
|
|
144
195
|
#productOf(plan) {
|
|
145
196
|
return { productId: plan.dataset.productId, basePlanId: plan.dataset.basePlanId ?? null }
|
|
146
197
|
}
|
data/lib/tasks/tillbell.rake
CHANGED
|
@@ -14,4 +14,19 @@ namespace :tillbell do
|
|
|
14
14
|
abort "\nSomething will not work: see the README, \"Google Play setup\"." unless check.ok?
|
|
15
15
|
puts "\nEverything is in place."
|
|
16
16
|
end
|
|
17
|
+
|
|
18
|
+
namespace :app_store do
|
|
19
|
+
desc "Save the charges of past App Store payments, read from Apple. Idempotent. Needs config.apple.issuer_id, key_id and private_key."
|
|
20
|
+
task backfill_charges: :environment do
|
|
21
|
+
failures = 0
|
|
22
|
+
Pay::AppStore::Subscription.find_each do |subscription|
|
|
23
|
+
saved = Tillbell::AppStore.backfill_charges(subscription)
|
|
24
|
+
puts "OK #{subscription.token_digest}: #{saved} charge(s)"
|
|
25
|
+
rescue Tillbell::Error => error
|
|
26
|
+
failures += 1
|
|
27
|
+
puts "FAIL #{subscription.token_digest}: #{error.message}"
|
|
28
|
+
end
|
|
29
|
+
abort "\n#{failures} subscription(s) failed; run the task again once fixed." if failures.positive?
|
|
30
|
+
end
|
|
31
|
+
end
|
|
17
32
|
end
|
data/lib/tillbell/app_store.rb
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
require "base64"
|
|
2
|
+
require "erb"
|
|
2
3
|
require "json"
|
|
3
4
|
require "jwt"
|
|
5
|
+
require "net/http"
|
|
4
6
|
require "openssl"
|
|
5
7
|
|
|
6
8
|
module Tillbell
|
|
@@ -11,6 +13,9 @@ module Tillbell
|
|
|
11
13
|
# at once and never has to retry later.
|
|
12
14
|
#
|
|
13
15
|
# Every method returns the decoded payload as a hash with Apple's camelCase string keys.
|
|
16
|
+
#
|
|
17
|
+
# Only the charge backfill calls Apple, through the App Store Server API: see
|
|
18
|
+
# +transaction_history+ and +config.apple.issuer_id+.
|
|
14
19
|
module AppStore
|
|
15
20
|
# Apple Root CA - G3, from https://www.apple.com/certificateauthority/AppleRootCA-G3.cer
|
|
16
21
|
# 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,
|
|
@@ -46,6 +51,17 @@ module Tillbell
|
|
|
46
51
|
# subscriptions. Same page as the +manage+ message of the iOS component.
|
|
47
52
|
MANAGE_URL = "https://apps.apple.com/account/subscriptions".freeze
|
|
48
53
|
|
|
54
|
+
# The page where a customer asks Apple for a refund: only Apple refunds App Store
|
|
55
|
+
# purchases, the app cannot. Apple then notifies the refund, which revokes the subscription.
|
|
56
|
+
REFUND_URL = "https://reportaproblem.apple.com".freeze
|
|
57
|
+
|
|
58
|
+
# App Store Server API hosts, by the +environment+ of the transactions they hold. Xcode
|
|
59
|
+
# StoreKit Testing transactions never reach Apple's servers.
|
|
60
|
+
API_HOSTS = {
|
|
61
|
+
"Production" => "https://api.storekit.apple.com",
|
|
62
|
+
"Sandbox" => "https://api.storekit-sandbox.apple.com"
|
|
63
|
+
}.freeze
|
|
64
|
+
|
|
49
65
|
class << self
|
|
50
66
|
# The certificates a chain must end at. Only specs change it.
|
|
51
67
|
attr_writer :root_certificates
|
|
@@ -66,8 +82,13 @@ module Tillbell
|
|
|
66
82
|
# Verifies a signed transaction (+VerificationResult.jwsRepresentation+ in StoreKit 2)
|
|
67
83
|
# and returns its payload. Raises +Tillbell::Error+ unless Apple signed it, for this app
|
|
68
84
|
# (+config.apple.bundle_id+), and it is an auto-renewable subscription.
|
|
85
|
+
#
|
|
86
|
+
# With +config.apple.allow_xcode_transactions+, in development and test, a transaction
|
|
87
|
+
# Xcode signed for StoreKit Testing is accepted without checking its signature, as
|
|
88
|
+
# Apple's own server libraries do for the Xcode environment. Notifications never come from
|
|
89
|
+
# Xcode and are always fully verified.
|
|
69
90
|
def verify_transaction!(jws)
|
|
70
|
-
transaction = decode!(jws)
|
|
91
|
+
transaction = xcode_transaction(jws) || decode!(jws)
|
|
71
92
|
raise Error, "The transaction belongs to another app (#{transaction["bundleId"]})" unless transaction["bundleId"] == bundle_id
|
|
72
93
|
raise Error, "The transaction is not an auto-renewable subscription" unless transaction["type"] == AUTO_RENEWABLE
|
|
73
94
|
|
|
@@ -102,6 +123,48 @@ module Tillbell
|
|
|
102
123
|
Pay::AppStore::Subscription.sync(transaction, renewal_info)
|
|
103
124
|
end
|
|
104
125
|
|
|
126
|
+
# Yields each auto-renewable subscription transaction of the customer who made
|
|
127
|
+
# +transaction_id+ (any of their transaction ids), verified like a purchase, from the
|
|
128
|
+
# App Store Server API ("Get Transaction History"). Refunded transactions are included,
|
|
129
|
+
# with their revocation fields. Returns an enumerator without a block.
|
|
130
|
+
#
|
|
131
|
+
# Needs an In-App Purchase key: +config.apple.issuer_id+, +key_id+ and +private_key+.
|
|
132
|
+
# Raises +Tillbell::Error+ when Apple refuses the request.
|
|
133
|
+
def transaction_history(transaction_id, environment: "Production")
|
|
134
|
+
return enum_for(:transaction_history, transaction_id, environment: environment) unless block_given?
|
|
135
|
+
|
|
136
|
+
revision = nil
|
|
137
|
+
loop do
|
|
138
|
+
query = { productType: "AUTO_RENEWABLE", sort: "ASCENDING", revision: revision }.compact
|
|
139
|
+
response = api_get(environment, "/inApps/v2/history/#{ERB::Util.url_encode(transaction_id)}", query)
|
|
140
|
+
Array(response["signedTransactions"]).each { |jws| yield verify_transaction!(jws) }
|
|
141
|
+
# A missing or repeated revision would request the same page forever.
|
|
142
|
+
break unless response["hasMore"] && response["revision"].present? && response["revision"] != revision
|
|
143
|
+
|
|
144
|
+
revision = response["revision"]
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
# Saves the charge of every paid transaction of +subscription+ (a
|
|
149
|
+
# Pay::AppStore::Subscription), read from Apple: the charges of purchases made before
|
|
150
|
+
# Tillbell recorded charges, or of notifications that never arrived. Idempotent, so it can
|
|
151
|
+
# run again. Returns the number of paid transactions synced, unchanged ones included.
|
|
152
|
+
def backfill_charges(subscription)
|
|
153
|
+
environment = subscription.environment.presence || "Production"
|
|
154
|
+
return 0 unless API_HOSTS.key?(environment)
|
|
155
|
+
|
|
156
|
+
transaction_history(subscription.processor_id, environment: environment).count do |transaction|
|
|
157
|
+
# The history holds all the customer's purchases in the app, other subscriptions too.
|
|
158
|
+
next false unless transaction["originalTransactionId"] == subscription.processor_id
|
|
159
|
+
|
|
160
|
+
# The same row lock as notifications take (see Pay::AppStore::Subscription.sync), on a
|
|
161
|
+
# fresh copy so the caller's instance is neither reloaded nor required to be clean.
|
|
162
|
+
Pay::AppStore::Subscription.transaction do
|
|
163
|
+
Pay::AppStore::Charge.sync(transaction, Pay::AppStore::Subscription.lock.find(subscription.id)).present?
|
|
164
|
+
end
|
|
165
|
+
end
|
|
166
|
+
end
|
|
167
|
+
|
|
105
168
|
# The bundle identifier of the iOS app, from +config.apple.bundle_id+. Raises
|
|
106
169
|
# +Tillbell::Error+ when it is not set.
|
|
107
170
|
def bundle_id
|
|
@@ -136,6 +199,54 @@ module Tillbell
|
|
|
136
199
|
end
|
|
137
200
|
|
|
138
201
|
private
|
|
202
|
+
# GETs +path+ from the App Store Server API of +environment+ and returns the parsed body.
|
|
203
|
+
# Network failures and unreadable answers raise +Tillbell::Error+ too, so a caller going
|
|
204
|
+
# through many subscriptions can report one and move on.
|
|
205
|
+
#
|
|
206
|
+
# ponytail: no retry on 429 (rate limited); the backfill reports it and can run again.
|
|
207
|
+
def api_get(environment, path, query)
|
|
208
|
+
uri = URI(API_HOSTS.fetch(environment) { raise Error, "No App Store Server API for #{environment.inspect} transactions" } + path)
|
|
209
|
+
uri.query = URI.encode_www_form(query) if query.any?
|
|
210
|
+
request = Net::HTTP::Get.new(uri, "Authorization" => "Bearer #{api_token}")
|
|
211
|
+
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 30) { |http| http.request(request) }
|
|
212
|
+
# Apple's error bodies only hold an errorCode and an errorMessage.
|
|
213
|
+
raise Error, "App Store Server API answered #{response.code}: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
|
|
214
|
+
|
|
215
|
+
body = JSON.parse(response.body)
|
|
216
|
+
raise Error, "App Store Server API answered #{response.code} without a JSON object" unless body.is_a?(Hash)
|
|
217
|
+
|
|
218
|
+
body
|
|
219
|
+
rescue JSON::ParserError, SocketError, SystemCallError, Timeout::Error, IOError, OpenSSL::SSL::SSLError,
|
|
220
|
+
Net::ProtocolError, Net::HTTPBadResponse => error
|
|
221
|
+
raise Error, "App Store Server API request failed: #{error.class}: #{error.message}"
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
# A JSON Web Token for one App Store Server API request, signed with the In-App Purchase
|
|
225
|
+
# key. Apple refuses tokens valid for more than an hour; five minutes cover a request.
|
|
226
|
+
def api_token
|
|
227
|
+
apple = Tillbell.apple
|
|
228
|
+
missing = %i[issuer_id key_id private_key].select { |setting| apple[setting].blank? }
|
|
229
|
+
raise Error, "Set Tillbell.apple.#{missing.join(", ")} to call the App Store Server API" if missing.any?
|
|
230
|
+
|
|
231
|
+
now = Time.now.to_i
|
|
232
|
+
payload = { iss: apple.issuer_id, iat: now, exp: now + 300, aud: "appstoreconnect-v1", bid: bundle_id }
|
|
233
|
+
JWT.encode(payload, OpenSSL::PKey::EC.new(apple.private_key), "ES256", { kid: apple.key_id, typ: "JWT" })
|
|
234
|
+
rescue OpenSSL::PKey::PKeyError, JWT::EncodeError
|
|
235
|
+
raise Error, "Tillbell.apple.private_key is not the content of an In-App Purchase key (.p8)"
|
|
236
|
+
end
|
|
237
|
+
|
|
238
|
+
# The payload of +jws+ when it is an Xcode StoreKit Testing transaction that the
|
|
239
|
+
# configuration allows, otherwise nil. Never in production or staging: without Apple's
|
|
240
|
+
# signature, anyone could forge one.
|
|
241
|
+
def xcode_transaction(jws)
|
|
242
|
+
return unless Tillbell.apple.allow_xcode_transactions && Rails.env.local?
|
|
243
|
+
|
|
244
|
+
payload, = JWT.decode(jws, nil, false)
|
|
245
|
+
payload if payload["environment"] == "Xcode"
|
|
246
|
+
rescue JWT::DecodeError
|
|
247
|
+
nil
|
|
248
|
+
end
|
|
249
|
+
|
|
139
250
|
# The chain must be valid when Apple signed the data, not only today: a transaction
|
|
140
251
|
# signed a year ago, restored now, may carry a leaf certificate that has since expired.
|
|
141
252
|
def verify_chain!(leaf, intermediate, root, at:)
|
data/lib/tillbell/check.rb
CHANGED
|
@@ -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
|
-
|
|
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
|
|
data/lib/tillbell/engine.rb
CHANGED
|
@@ -8,6 +8,9 @@ module Tillbell
|
|
|
8
8
|
class Engine < ::Rails::Engine
|
|
9
9
|
isolate_namespace Tillbell
|
|
10
10
|
|
|
11
|
+
# Display names of the stores, by Pay processor.
|
|
12
|
+
STORE_NAMES = { "google_play" => "Google Play", "app_store" => "App Store" }.freeze
|
|
13
|
+
|
|
11
14
|
# Real-time developer notifications are verified, stored and queued by Pay (see
|
|
12
15
|
# Tillbell::NotificationsController). Once Pay's job processes one, Tillbell re-reads
|
|
13
16
|
# the subscription from Google.
|
|
@@ -30,6 +33,12 @@ module Tillbell
|
|
|
30
33
|
def app_store?
|
|
31
34
|
processor == "app_store"
|
|
32
35
|
end
|
|
36
|
+
|
|
37
|
+
# True for a customer of an app store (Google Play or the App Store), whose
|
|
38
|
+
# subscriptions are managed in the store rather than by the app.
|
|
39
|
+
def store?
|
|
40
|
+
google_play? || app_store?
|
|
41
|
+
end
|
|
33
42
|
end
|
|
34
43
|
|
|
35
44
|
ActiveSupport.on_load(:pay_subscription) do
|
|
@@ -66,6 +75,35 @@ module Tillbell
|
|
|
66
75
|
def app_store?
|
|
67
76
|
customer.processor == "app_store"
|
|
68
77
|
end
|
|
78
|
+
|
|
79
|
+
# True for a subscription bought in an app store (Google Play or the App Store). The
|
|
80
|
+
# customer manages it in the store (+manage_url+): the server can neither change its
|
|
81
|
+
# plan nor, for the App Store, stop it.
|
|
82
|
+
def store?
|
|
83
|
+
customer.store?
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# The name of the store the subscription was bought in, "Google Play" or "App Store",
|
|
87
|
+
# for admin pages and internal alerts; nil for any other processor. Brand names, so
|
|
88
|
+
# they are not translated.
|
|
89
|
+
def store_name
|
|
90
|
+
STORE_NAMES[customer.processor]
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
# True when the subscription gives access and will renew by itself: +grants_access?+,
|
|
94
|
+
# and not canceled with an end date still to come (Pay's +on_grace_period?+). Use it to
|
|
95
|
+
# warn a customer who is about to close their account or switch plans while a renewal
|
|
96
|
+
# is planned.
|
|
97
|
+
def renewing?
|
|
98
|
+
grants_access? && !on_grace_period?
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# True for a test purchase that costs nothing. Always false here; store subscriptions
|
|
102
|
+
# answer from what the store says (see Pay::AppStore::Subscription#sandbox? and
|
|
103
|
+
# Pay::GooglePlay::Subscription#sandbox?).
|
|
104
|
+
def sandbox?
|
|
105
|
+
false
|
|
106
|
+
end
|
|
69
107
|
end
|
|
70
108
|
end
|
|
71
109
|
|
data/lib/tillbell/owner.rb
CHANGED
|
@@ -25,6 +25,36 @@ module Tillbell
|
|
|
25
25
|
google_play_subscription&.on_hold? || false
|
|
26
26
|
end
|
|
27
27
|
|
|
28
|
+
# The most relevant subscription bought in an app store (Google Play or the App Store), or
|
|
29
|
+
# nil: the most recent one that is active or paused, otherwise the most recent one.
|
|
30
|
+
def store_subscription
|
|
31
|
+
subscriptions = store_subscriptions
|
|
32
|
+
subscriptions.active_or_paused.first || subscriptions.first
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# True when the store subscription (see +store_subscription+) is on hold: the payment failed
|
|
36
|
+
# after the store's grace period and access is suspended while the store retries. The
|
|
37
|
+
# customer fixes it in the store (+manage_url+); subscribing again elsewhere would bill
|
|
38
|
+
# twice if the retry succeeds.
|
|
39
|
+
def store_on_hold?
|
|
40
|
+
store_subscription&.on_hold? || false
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# The most recent store subscription the store still counts as the customer's, with or
|
|
44
|
+
# without access (see +owned?+), or nil. Buying it again would be refused by the store, and
|
|
45
|
+
# buying another way (a web checkout) would bill twice: send the customer to its
|
|
46
|
+
# +manage_url+ instead.
|
|
47
|
+
def owned_store_subscription
|
|
48
|
+
store_subscriptions.find(&:owned?)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# The App Store subscriptions that will still renew: only the customer can stop them, in
|
|
52
|
+
# the App Store, so +cancel_billing_subscriptions!+ leaves them unchanged. Show their
|
|
53
|
+
# +manage_url+ before closing the account.
|
|
54
|
+
def subscriptions_to_cancel_in_store
|
|
55
|
+
billing_subscriptions.select { |subscription| subscription.app_store? && subscription.ends_at.nil? }
|
|
56
|
+
end
|
|
57
|
+
|
|
28
58
|
# The subscription to show and to decide access from, whatever its processor: the one
|
|
29
59
|
# that renews, then one that is canceled but still running, then one whose payment is
|
|
30
60
|
# being retried or that is paused; the most recent breaks a tie. Nil without any.
|
|
@@ -52,10 +82,18 @@ module Tillbell
|
|
|
52
82
|
end
|
|
53
83
|
|
|
54
84
|
private
|
|
85
|
+
# Subscriptions of the owner's store customers, the most recent first.
|
|
86
|
+
def store_subscriptions
|
|
87
|
+
pay_subscriptions.merge(Pay::Customer.active).where(pay_customers: { processor: %w[google_play app_store] }).order(created_at: :desc)
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# An App Store subscription that went stale (see Pay::AppStore::Subscription#stale?) is
|
|
91
|
+
# still "active" but must not hide one that grants access.
|
|
55
92
|
def subscription_standing(subscription)
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
elsif
|
|
93
|
+
active = subscription.active? && !subscription.try(:stale?)
|
|
94
|
+
if active && !subscription.on_grace_period? then 0
|
|
95
|
+
elsif active then 1
|
|
96
|
+
elsif subscription.billing? && !subscription.try(:stale?) then 2
|
|
59
97
|
else 3
|
|
60
98
|
end
|
|
61
99
|
end
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
module Tillbell
|
|
2
|
+
# Builds store subscriptions in a host app's tests, without Apple's signature or a call to
|
|
3
|
+
# Google: what the stores send is built here, then saved by the same code as a real purchase.
|
|
4
|
+
#
|
|
5
|
+
# # spec/rails_helper.rb
|
|
6
|
+
# require "tillbell/test_helpers"
|
|
7
|
+
# RSpec.configure { |config| config.include Tillbell::TestHelpers }
|
|
8
|
+
#
|
|
9
|
+
# create_app_store_subscription(user, product_id: "app.family.monthly")
|
|
10
|
+
# create_google_play_subscription(user, state: "SUBSCRIPTION_STATE_ON_HOLD")
|
|
11
|
+
#
|
|
12
|
+
# Not loaded by +require "tillbell"+: test code only.
|
|
13
|
+
module TestHelpers
|
|
14
|
+
# Records an App Store subscription of +owner+ from +app_store_transaction+ (whose options
|
|
15
|
+
# it takes) and, when given, +renewal_info+ (see +app_store_renewal_info+). Returns the
|
|
16
|
+
# Pay::AppStore::Subscription, and emits the Tillbell events a real purchase would.
|
|
17
|
+
def create_app_store_subscription(owner, renewal_info: nil, **transaction)
|
|
18
|
+
Pay::AppStore::Subscription.sync(app_store_transaction(account_id: tillbell_account_id(owner), **transaction), renewal_info)
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
# Records a Google Play subscription of +owner+ under +purchase_token+ from
|
|
22
|
+
# +google_subscription+ (whose options it takes). Returns the Pay::GooglePlay::Subscription,
|
|
23
|
+
# and emits the Tillbell events a real purchase would.
|
|
24
|
+
def create_google_play_subscription(owner, purchase_token: SecureRandom.hex(16), **response)
|
|
25
|
+
Pay::GooglePlay::Subscription.sync(purchase_token, object: google_subscription(account_id: tillbell_account_id(owner), **response))
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# The account id the paywall sends for +owner+: Google Play's +obfuscatedAccountId+ and
|
|
29
|
+
# the App Store's +appAccountToken+.
|
|
30
|
+
def tillbell_account_id(owner)
|
|
31
|
+
Pay::GooglePlay::Customer.for(owner).processor_id
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# A decoded App Store transaction (JWSTransaction) of an auto-renewable subscription, with
|
|
35
|
+
# Apple's keys. +environment+ is "Production", "Sandbox" or "Xcode".
|
|
36
|
+
def app_store_transaction(account_id:, product_id: "premium.monthly", original_transaction_id: "2000000000000001",
|
|
37
|
+
transaction_id: original_transaction_id, purchased_at: Time.current, expires_at: 1.month.from_now,
|
|
38
|
+
revoked_at: nil, environment: "Production", price: nil, currency: nil,
|
|
39
|
+
bundle_id: Tillbell.apple.bundle_id, type: Tillbell::AppStore::AUTO_RENEWABLE)
|
|
40
|
+
{
|
|
41
|
+
"transactionId" => transaction_id, "originalTransactionId" => original_transaction_id, "bundleId" => bundle_id,
|
|
42
|
+
"productId" => product_id, "type" => type, "appAccountToken" => account_id, "environment" => environment,
|
|
43
|
+
"purchaseDate" => apple_time(purchased_at), "expiresDate" => apple_time(expires_at),
|
|
44
|
+
"revocationDate" => apple_time(revoked_at), "signedDate" => apple_time(Time.current),
|
|
45
|
+
"price" => price && (BigDecimal(price.to_s) * 1000).to_i, "currency" => currency
|
|
46
|
+
}.compact
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# A decoded App Store renewal information (JWSRenewalInfo), as notifications carry it.
|
|
50
|
+
def app_store_renewal_info(product_id: "premium.monthly", auto_renew: true, billing_retry: false, grace_period_ends_at: nil)
|
|
51
|
+
{
|
|
52
|
+
"autoRenewProductId" => product_id, "autoRenewStatus" => auto_renew ? 1 : 0, "isInBillingRetryPeriod" => billing_retry,
|
|
53
|
+
"gracePeriodExpiresDate" => apple_time(grace_period_ends_at), "signedDate" => apple_time(Time.current)
|
|
54
|
+
}.compact
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# A Google Play Developer API +purchases.subscriptionsv2.get+ response, in the shape
|
|
58
|
+
# Tillbell::GooglePlay.subscription returns (snake_case symbol keys). +test_purchase+ makes
|
|
59
|
+
# it a license tester's purchase.
|
|
60
|
+
def google_subscription(account_id:, state: "SUBSCRIPTION_STATE_ACTIVE", product_id: "premium", base_plan_id: "monthly",
|
|
61
|
+
expiry_time: 1.month.from_now, auto_renewing: true, acknowledged: true, linked_purchase_token: nil,
|
|
62
|
+
recurring_price: nil, deferred_product_id: nil, line_items: nil, test_purchase: false)
|
|
63
|
+
{
|
|
64
|
+
subscription_state: state,
|
|
65
|
+
acknowledgement_state: acknowledged ? "ACKNOWLEDGEMENT_STATE_ACKNOWLEDGED" : "ACKNOWLEDGEMENT_STATE_PENDING",
|
|
66
|
+
external_account_identifiers: { obfuscated_external_account_id: account_id },
|
|
67
|
+
linked_purchase_token: linked_purchase_token,
|
|
68
|
+
test_purchase: ({} if test_purchase),
|
|
69
|
+
line_items: line_items || [
|
|
70
|
+
{
|
|
71
|
+
product_id: product_id,
|
|
72
|
+
expiry_time: expiry_time.utc.iso8601,
|
|
73
|
+
offer_details: { base_plan_id: base_plan_id },
|
|
74
|
+
auto_renewing_plan: { auto_renew_enabled: auto_renewing, recurring_price: recurring_price }.compact,
|
|
75
|
+
deferred_item_replacement: deferred_product_id && { product_id: deferred_product_id }
|
|
76
|
+
}.compact
|
|
77
|
+
]
|
|
78
|
+
}.compact
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# Records every Tillbell event emitted while the block runs, as +[name, payload]+ pairs.
|
|
82
|
+
def tillbell_events
|
|
83
|
+
events = []
|
|
84
|
+
subscriber = ActiveSupport::Notifications.subscribe(/\Apay\.tillbell\./) do |name, *, payload|
|
|
85
|
+
events << [ name.delete_prefix("pay.tillbell.").to_sym, payload ]
|
|
86
|
+
end
|
|
87
|
+
yield
|
|
88
|
+
events
|
|
89
|
+
ensure
|
|
90
|
+
ActiveSupport::Notifications.unsubscribe(subscriber)
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
# A time as Apple sends it: milliseconds since the epoch.
|
|
94
|
+
def apple_time(time)
|
|
95
|
+
time && (time.to_f * 1000).to_i
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
end
|
data/lib/tillbell/version.rb
CHANGED
data/lib/tillbell.rb
CHANGED
|
@@ -28,13 +28,25 @@ module Tillbell
|
|
|
28
28
|
# The events Tillbell emits, in the order a subscription usually goes through them.
|
|
29
29
|
# +subscription_updated+ fires for any change; +subscription_renewed+, +payment_failed+,
|
|
30
30
|
# +payment_recovered+ and +plan_changed+ say which one happened.
|
|
31
|
+
# +subscription_reactivated+ follows a +subscription_canceled+ the customer took back
|
|
32
|
+
# before the end of the period.
|
|
31
33
|
EVENTS = %i[subscription_created subscription_updated subscription_renewed payment_failed payment_recovered plan_changed
|
|
32
|
-
subscription_canceled subscription_expired subscription_revoked purchase_rejected].freeze
|
|
34
|
+
subscription_canceled subscription_reactivated subscription_expired subscription_revoked purchase_rejected].freeze
|
|
33
35
|
|
|
34
|
-
# A plan the app sells: a Google Play product and its base plan,
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
36
|
+
# A plan the app sells, under a name of your own: a Google Play product and its base plan,
|
|
37
|
+
# and the App Store product of the same plan. The App Store product id defaults to the Google
|
|
38
|
+
# Play one; an app sold on one store only leaves the other's id out.
|
|
39
|
+
Plan = Data.define(:name, :product_id, :base_plan_id, :app_store_product_id) do
|
|
40
|
+
def initialize(name:, product_id: nil, base_plan_id: nil, app_store_product_id: product_id)
|
|
41
|
+
raise ArgumentError, "plan #{name.inspect} needs a product_id or an app_store_product_id" if product_id.blank? && app_store_product_id.blank?
|
|
42
|
+
|
|
43
|
+
super(name: name.to_sym, product_id: product_id, base_plan_id: base_plan_id, app_store_product_id: app_store_product_id)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# The ids the app of +store+ (+:app_store+ or +:google_play+) buys this plan with, as the
|
|
47
|
+
# +product_id+ and +base_plan_id+ of a paywall option. The App Store has no base plans.
|
|
48
|
+
def product_for(store)
|
|
49
|
+
store == :app_store ? { product_id: app_store_product_id, base_plan_id: nil } : { product_id: product_id, base_plan_id: base_plan_id }
|
|
38
50
|
end
|
|
39
51
|
end
|
|
40
52
|
|
|
@@ -50,6 +62,19 @@ module Tillbell
|
|
|
50
62
|
#
|
|
51
63
|
# [bundle_id] Bundle identifier of the iOS app, e.g. "com.example.app". Transactions and
|
|
52
64
|
# notifications signed for another app are refused.
|
|
65
|
+
# [allow_xcode_transactions] Accept the transactions Xcode signs locally for StoreKit
|
|
66
|
+
# Testing (a +.storekit+ configuration file), in the development
|
|
67
|
+
# and test environments only. See
|
|
68
|
+
# +Tillbell::AppStore.verify_transaction!+.
|
|
69
|
+
# [stale_after] How long after the end of its period an App Store subscription that no
|
|
70
|
+
# notification renewed or ended keeps giving access, e.g. +16.days+ (set it at
|
|
71
|
+
# least to the billing grace period of your subscriptions). Nil, the default,
|
|
72
|
+
# trusts the last state Apple notified forever.
|
|
73
|
+
# [issuer_id] Issuer id of the App Store Connect API keys (Users and Access, Integrations,
|
|
74
|
+
# In-App Purchase).
|
|
75
|
+
# [key_id] Id of an In-App Purchase key.
|
|
76
|
+
# [private_key] Content of that key's +.p8+ file. These three are only needed to call the
|
|
77
|
+
# App Store Server API, which +tillbell:app_store:backfill_charges+ does.
|
|
53
78
|
mattr_accessor :apple, default: ActiveSupport::OrderedOptions.new
|
|
54
79
|
|
|
55
80
|
# Returns the Pay owner (usually a User) the current request acts for, or nil.
|
|
@@ -70,11 +95,11 @@ module Tillbell
|
|
|
70
95
|
#
|
|
71
96
|
# config.plans = [
|
|
72
97
|
# { name: :solo, product_id: "app_solo", base_plan_id: "monthly" },
|
|
73
|
-
# { name: :family, product_id: "app_family", base_plan_id: "monthly" }
|
|
98
|
+
# { name: :family, product_id: "app_family", base_plan_id: "monthly", app_store_product_id: "app.family.monthly" }
|
|
74
99
|
# ]
|
|
75
100
|
#
|
|
76
|
-
# +tillbell:check+ checks
|
|
77
|
-
# the one
|
|
101
|
+
# +tillbell:check+ checks the Google Play ones with Google, and +plan+ on a store subscription
|
|
102
|
+
# finds the one it is on.
|
|
78
103
|
mattr_reader :plans, default: [].freeze
|
|
79
104
|
|
|
80
105
|
# What Hotwire Native writes in the user agent for the bridge components the app
|
|
@@ -82,7 +107,27 @@ module Tillbell
|
|
|
82
107
|
# list for the paywall to work.
|
|
83
108
|
NATIVE_USER_AGENT = /bridge-components: \[(?:[^\]]*\s)?tillbell[\s\]]/
|
|
84
109
|
|
|
110
|
+
# What Hotwire Native writes in the user agent of each platform, and the store its in-app
|
|
111
|
+
# purchases go through.
|
|
112
|
+
NATIVE_STORES = {
|
|
113
|
+
/\b(?:Hotwire|Turbo) Native iOS\b/ => :app_store,
|
|
114
|
+
/\b(?:Hotwire|Turbo) Native Android\b/ => :google_play
|
|
115
|
+
}.freeze
|
|
116
|
+
|
|
85
117
|
class << self
|
|
118
|
+
# The store in-app purchases go through in the Hotwire Native app +user_agent+ comes from:
|
|
119
|
+
# +:app_store+ (iOS), +:google_play+ (Android), or nil in a browser. Unlike +native?+, it
|
|
120
|
+
# does not need the +tillbell+ component, so it also answers for app versions that cannot
|
|
121
|
+
# buy yet. Use it for the store rules that apply to the whole app, e.g. the App Store
|
|
122
|
+
# forbids linking to another way to pay:
|
|
123
|
+
#
|
|
124
|
+
# Tillbell.store(request.user_agent) == :app_store
|
|
125
|
+
#
|
|
126
|
+
# Like +native?+, it only picks what to show: a forged user agent gains nothing.
|
|
127
|
+
def store(user_agent)
|
|
128
|
+
NATIVE_STORES.find { |pattern, _store| pattern.match?(user_agent.to_s) }&.last
|
|
129
|
+
end
|
|
130
|
+
|
|
86
131
|
# True when +user_agent+ comes from a native app that registered the +tillbell+ bridge
|
|
87
132
|
# component (Android today, iOS later), so a Google Play purchase can start from the
|
|
88
133
|
# page. Use it to choose between the paywall and another way to pay, e.g. a web checkout:
|
|
@@ -97,20 +142,32 @@ module Tillbell
|
|
|
97
142
|
end
|
|
98
143
|
|
|
99
144
|
# Sets the catalog of +plans+ from hashes with +name+, +product_id+ and optionally
|
|
100
|
-
# +base_plan_id+ (or from +Tillbell::Plan+ objects).
|
|
145
|
+
# +base_plan_id+ and +app_store_product_id+ (or from +Tillbell::Plan+ objects).
|
|
146
|
+
#
|
|
147
|
+
# A Google Play product with several base plans is several plans, while each App Store
|
|
148
|
+
# product is one duration: such plans do not default their App Store product id to the
|
|
149
|
+
# shared Google Play one. Give them their own +app_store_product_id+.
|
|
101
150
|
def plans=(list)
|
|
102
|
-
|
|
103
|
-
next plan if plan.is_a?(Plan)
|
|
104
|
-
raise ArgumentError, "a plan is a hash with :name
|
|
151
|
+
built = list.map do |plan|
|
|
152
|
+
next [ plan, false ] if plan.is_a?(Plan)
|
|
153
|
+
raise ArgumentError, "a plan is a hash with :name and :product_id or :app_store_product_id, got #{plan.inspect}" unless plan.respond_to?(:to_h) && !plan.nil?
|
|
105
154
|
|
|
106
|
-
|
|
155
|
+
attributes = plan.to_h.symbolize_keys
|
|
156
|
+
[ Plan.new(**attributes), !attributes.key?(:app_store_product_id) ]
|
|
157
|
+
end
|
|
158
|
+
shared = built.filter_map { |plan, _defaulted| plan.app_store_product_id }.tally.select { |_id, count| count > 1 }.keys
|
|
159
|
+
@@plans = built.map do |plan, defaulted|
|
|
160
|
+
defaulted && shared.include?(plan.app_store_product_id) ? plan.with(app_store_product_id: nil) : plan
|
|
107
161
|
end.freeze
|
|
108
162
|
end
|
|
109
163
|
|
|
110
|
-
# Finds a plan of +plans+ by +name+ (a symbol or string)
|
|
111
|
-
#
|
|
112
|
-
|
|
164
|
+
# Finds a plan of +plans+ by +name+ (a symbol or string), by App Store product id (nil when
|
|
165
|
+
# several plans share it), or by Google ids. With a +base_plan_id+ that no plan has, falls
|
|
166
|
+
# back to the product's plan when it has only one.
|
|
167
|
+
def plan(name = nil, product_id: nil, base_plan_id: nil, app_store_product_id: nil)
|
|
113
168
|
return plans.find { |plan| plan.name == name.to_sym } if name
|
|
169
|
+
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
|
|
170
|
+
return if product_id.blank?
|
|
114
171
|
|
|
115
172
|
matches = plans.select { |plan| plan.product_id == product_id }
|
|
116
173
|
matches.find { |plan| plan.base_plan_id == base_plan_id } || (matches.first if matches.one?)
|