tillbell 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 40023bb1bf7c5e6140bea7065efc6477edc7e38a0f0936ddbb1d9f36cea664f1
4
- data.tar.gz: 23fcd6c419b6cbbcd98fe18fe23bfc0d1dc1f551c1bf2fcb0aff13a1c9d4b6c9
3
+ metadata.gz: 5e48af929e57af662aa986988dad244c74992aedd713752cc294f543dc38a79f
4
+ data.tar.gz: 5ab9aa177391f2751ac182e8b83fa8f9451bdc9897b9b4a14e6d120aadbd3ae1
5
5
  SHA512:
6
- metadata.gz: '096b0bf3173c8fec91188e04d1b0ccec039b063334609019d7be2695dca8046493fbbd14f5531981c497f9a2510c8a84790c3df934e0c265b4d434be870f4901'
7
- data.tar.gz: 7ae176e370fbdceefd46e35d004b5f3b44a85e80c93d5e2225a0b758ccf36cf9fcd5d4ad8ab8cd6e75d63463663104637fce2068d9814ac3e58315efc984e905
6
+ metadata.gz: 779b1e2584e9ed3ffc2a3590c182311ef61aacc076f5622e175418c8527becc79972d78cb4b7171f3623c839331c940fdfd0d150c8450c924a3106523163e98c
7
+ data.tar.gz: '03690b505f174b11c90a0737168823334dcc9d2f3c7d9b09d5543d79d73909f70b39e1ec35b825939af80918f304a979f89061b74c797e79f5f4b5eefe75864d'
data/CHANGELOG.md CHANGED
@@ -6,6 +6,27 @@ All notable changes to this project are documented in this file. The format foll
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.8.0] - 2026-11-24
10
+
11
+ ### Upgrading
12
+
13
+ - App Store purchases now create Pay charges, sandbox ones included (TestFlight and App Review
14
+ buy on your production server). If your app sums `Pay::Charge` for revenue, leave them out:
15
+ `Pay::Charge.where.not(id: Pay::AppStore::Charge.sandbox)`.
16
+
17
+ ### Added
18
+
19
+ - App Store payments are Pay charges: each paid transaction (the first purchase and every
20
+ renewal) is saved as a `Pay::AppStore::Charge`, with what the customer paid in the
21
+ storefront's currency, so revenue reports that sum Pay charges count the App Store. Refunds,
22
+ prorated ones included, set `amount_refunded`; a reversed refund resets it. `sandbox?` and the
23
+ `sandbox` scope tell sandbox and Xcode charges apart. `refund!` raises `Tillbell::Error`: only
24
+ Apple refunds App Store purchases.
25
+ - `Tillbell::AppStore.transaction_history`, a client of the App Store Server API's "Get
26
+ Transaction History", configured with `config.apple.issuer_id`, `key_id` and `private_key`.
27
+ - `bin/rails tillbell:app_store:backfill_charges` saves the charges of App Store payments made
28
+ before this version, or whose notification never arrived. Idempotent.
29
+
9
30
  ## [0.7.0] - 2026-11-14
10
31
 
11
32
  ### Added
data/README.md CHANGED
@@ -207,6 +207,10 @@ The values marked "credentials" below come from Google: the [Google Play setup](
207
207
  | `current_owner` | `-> { current_user }` | Returns who is buying. Evaluated in the controller and in the view, so any helper available there works (`Current.user`, `current_account`, ...). |
208
208
  | `parent_controller` | `"ApplicationController"` | Controller the purchase endpoint inherits from, to reuse your authentication, CSRF protection and error handling. |
209
209
  | `plans` | `[]` | The plans you sell, lowest first: `[{ name: :solo, product_id: "app_solo", base_plan_id: "monthly" }, ...]`. Add `app_store_product_id:` when the App Store product has another id than the Google Play one, or when several plans share a Google Play product (each App Store product is one duration, so they get no default); an App Store-only plan has no `product_id`. `tillbell:check` verifies the Google Play ones, `subscription.plan` finds the one a subscription is on, and `Tillbell.replacement_mode` and `paywall.plan_change` use their order to tell an upgrade from a downgrade. |
210
+ | `apple.bundle_id` | (required for the App Store) | Bundle identifier of the iOS app. Transactions and notifications signed for another app are refused. |
211
+ | `apple.allow_xcode_transactions` | `nil` | Accept Xcode StoreKit Testing transactions, unsigned by Apple, in the development and test environments only. |
212
+ | `apple.stale_after` | `nil` | An App Store subscription that no notification renewed stops giving access (`grants_access?` false, `stale?` true) this long after the end of its period. Set it at least to your billing grace period, e.g. `16.days`. `nil` trusts the last state Apple notified forever. |
213
+ | `apple.issuer_id`, `apple.key_id`, `apple.private_key` | `nil` | An In-App Purchase key of App Store Connect, only needed to call the App Store Server API (`tillbell:app_store:backfill_charges`). See [App Store setup](#app-store-setup). |
210
214
  | `subscription_name` | `->(product_id:, base_plan_id:) { Pay.default_product_name }` | Pay subscription `name` of a Google Play product, as used by `subscribed?(name:)`. |
211
215
 
212
216
  ## The paywall
@@ -643,6 +647,18 @@ The iOS app ([tillbell-ios](https://github.com/pmakerhq/tillbell-ios)) talks to
643
647
 
644
648
  6. **Decide what happens if notifications stop.** A renewing subscription only moves on when Apple notifies the renewal. If notifications stop reaching your server, the last state stays, access included. `config.apple.stale_after = 16.days` (at least your billing grace period) makes `grants_access?` false that long after the end of a period no notification renewed; `stale?` tells such subscriptions.
645
649
 
650
+ 7. **Backfill past payments (optional).** Tillbell records each App Store payment as a Pay charge (see below) from the moment it is installed. To also record the payments made before, or those whose notification never arrived, create an In-App Purchase key in App Store Connect (*Users and Access* › *Integrations* › *In-App Purchase*), set it, then run the backfill. It reads each subscription's transaction history from the App Store Server API and can run again safely:
651
+
652
+ ```ruby
653
+ config.apple.issuer_id = Rails.application.credentials.dig(:tillbell, :apple_issuer_id)
654
+ config.apple.key_id = Rails.application.credentials.dig(:tillbell, :apple_key_id)
655
+ config.apple.private_key = Rails.application.credentials.dig(:tillbell, :apple_private_key) # the .p8 file's content
656
+ ```
657
+
658
+ ```sh
659
+ bin/rails tillbell:app_store:backfill_charges
660
+ ```
661
+
646
662
  How App Store subscriptions differ:
647
663
 
648
664
  - `processor_id` is the `originalTransactionId`, which stays the same across renewals and plan changes.
@@ -650,6 +666,7 @@ How App Store subscriptions differ:
650
666
  - Statuses: `active` (including Apple's billing grace period), `past_due` in billing retry after the grace period (no access, see `grants_access?`), `canceled` once expired or refunded.
651
667
  - Sandbox purchases (TestFlight, App Review) are accepted, so App Review can buy against your production server (Xcode StoreKit Testing ones only in development, see above); `sandbox?` tells them apart, for example to keep them out of revenue reports.
652
668
  - `price_amount` and `price_currency` give what Apple charged for the last transaction (an introductory offer included), as for Google Play.
669
+ - Every paid transaction, the first purchase and each renewal, is a `Pay::AppStore::Charge`: `amount` is the price the customer paid, before Apple's commission, in the smallest unit of `currency` (lowercase, `"eur"`), like a Stripe charge, so revenue reports that sum Pay charges count the App Store too. It is the App Store Connect price of the storefront, so it includes tax where the storefront's prices do (not in the United States or Canada, for example). Its `created_at` is when Apple charged. A refund sets `amount_refunded` (the prorated part for a prorated refund), back to zero if Apple reverses it; a payload signed before the last one changes nothing, so a late notification never undoes a refund. Free trials, family-shared transactions and transactions without a price are not charges. Charges of sandbox and Xcode purchases are recorded too: leave them out of revenue with `charge.sandbox?`, or in SQL with `Pay::Charge.where.not(id: Pay::AppStore::Charge.sandbox)`. An upgrade's prorated refund of the previous product is not in Apple's data, so the upgraded transaction keeps its full amount. `sync!` raises: Apple's notifications and the backfill below update these charges.
653
670
  - Family-shared subscriptions are not recorded: they belong to the family member who bought them.
654
671
  - Only the customer can cancel an App Store subscription, in the App Store: `cancel` and `cancel_now!` leave it unchanged (they never raise, so deleting an owner still works). Send the customer to `manage_url` before closing their account (`owner.subscriptions_to_cancel_in_store` lists them). Only Apple refunds, at `Tillbell::AppStore::REFUND_URL`.
655
672
  - `replacement?` and `replaced?` are always false: a plan change keeps the same `originalTransactionId`.
@@ -0,0 +1,141 @@
1
+ module Pay
2
+ module AppStore
3
+ # A payment the App Store took for a subscription, stored as a Pay charge: the first
4
+ # purchase and every renewal are each a transaction, and each paid transaction is one charge.
5
+ # Revenue reports that sum Pay charges then count the App Store next to Stripe.
6
+ #
7
+ # [processor_id] The +transactionId+, unique per payment.
8
+ # [amount] The price the customer paid, in the smallest unit of +currency+ (cents), like
9
+ # Stripe charges: the App Store Connect price of the storefront, before Apple's
10
+ # commission, tax included where the storefront's prices include it (not in the
11
+ # United States or Canada, for example).
12
+ # [currency] Lowercase ISO 4217 code of the storefront's currency ("eur").
13
+ # [amount_refunded] The part of +amount+ Apple refunded, zero when a refund is reversed.
14
+ # [created_at] When Apple charged the customer (+purchaseDate+).
15
+ # [object] The signed transaction payload, for debugging.
16
+ #
17
+ # +data+ holds +environment+ ("Production", "Sandbox" or "Xcode"), +product_id+ and
18
+ # +signed_date_ms+, when Apple signed the payload the charge was last updated from.
19
+ #
20
+ # Sandbox purchases are recorded too, as their subscriptions are: leave them out of revenue
21
+ # with +sandbox?+, or in SQL with the +sandbox+ scope.
22
+ class Charge < Pay::Charge
23
+ store_accessor :data, :environment, :product_id, :signed_date_ms
24
+
25
+ # Environments of purchases that cost nothing: TestFlight and App Review (Sandbox) and
26
+ # Xcode StoreKit Testing.
27
+ SANDBOX_ENVIRONMENTS = %w[Sandbox Xcode].freeze
28
+
29
+ # The +revocationPercentage+ of a full refund: Apple gives percentages in thousandths.
30
+ FULL_REVOCATION = 100_000
31
+
32
+ # Revocations that give money back. A Family Sharing or group assignment revocation only
33
+ # removes someone's access to a purchase another person paid for.
34
+ REFUNDS = %w[REFUND_FULL REFUND_PRORATED].freeze
35
+
36
+ # Charges of sandbox and Xcode purchases. +where.not+ on this scope leaves them out.
37
+ scope :sandbox, -> { where("#{environment_sql} IN (?)", SANDBOX_ENVIRONMENTS) }
38
+
39
+ class << self
40
+ # SQL reading +data.environment+ as text, in the JSON syntax of the database: PostgreSQL,
41
+ # SQLite, or MySQL and MariaDB (Pay supports all of them).
42
+ def environment_sql
43
+ with_connection do |connection|
44
+ column = "#{connection.quote_table_name(table_name)}.#{connection.quote_column_name("data")}"
45
+ case connection.adapter_name
46
+ when /postg/i then "#{column}->>'environment'"
47
+ when /sqlite/i then "json_extract(#{column}, '$.environment')"
48
+ else "JSON_UNQUOTE(JSON_EXTRACT(#{column}, '$.environment'))"
49
+ end
50
+ end
51
+ end
52
+
53
+ # Saves the charge of a verified transaction (see Tillbell::AppStore.verify_transaction!)
54
+ # of +subscription+, or updates its refund. Idempotent: a transaction is one charge,
55
+ # however many times a restore, a notification or a backfill brings it, and a payload
56
+ # signed before the one the charge was last updated from changes nothing, so a late or
57
+ # replayed purchase never undoes a refund. Call it holding the subscription's row lock,
58
+ # as Pay::AppStore::Subscription.sync does, so two callers never insert the same
59
+ # transaction at once.
60
+ #
61
+ # Returns the charge, or nil when nothing was paid (a free trial), for a Family Sharing
62
+ # transaction (only the buyer's own transaction is a payment), for a transaction of
63
+ # another customer (several accounts can share an Apple Account, so one
64
+ # +originalTransactionId+ can be on two customers' subscriptions), and when the
65
+ # transaction has no price in a currency Pay knows.
66
+ #
67
+ # ponytail: the prorated refund Apple gives on an upgrade is not in the transaction data,
68
+ # so the upgraded transaction keeps its full amount.
69
+ def sync(transaction, subscription)
70
+ return if transaction["inAppOwnershipType"] == "FAMILY_SHARED"
71
+ return unless transaction["appAccountToken"].to_s.downcase == subscription.customer.processor_id
72
+
73
+ # Without a price, or a free trial: nothing was paid.
74
+ return if transaction["price"].to_i.zero?
75
+
76
+ amount = amount_from(transaction)
77
+ if amount.nil?
78
+ Rails.logger.warn "[Tillbell] No charge for App Store transaction #{transaction["transactionId"]}: unknown currency #{transaction["currency"].inspect}"
79
+ return
80
+ end
81
+ return if amount.zero?
82
+
83
+ charge = find_or_initialize_by(customer_id: subscription.customer_id, processor_id: transaction["transactionId"].to_s)
84
+ return charge if transaction["signedDate"].to_i < charge.signed_date_ms.to_i
85
+
86
+ charge.update!(
87
+ subscription: subscription,
88
+ amount: amount,
89
+ currency: transaction["currency"].downcase,
90
+ amount_refunded: refunded(amount, transaction),
91
+ created_at: Tillbell::AppStore.time(transaction["purchaseDate"]),
92
+ environment: transaction["environment"],
93
+ product_id: transaction["productId"],
94
+ signed_date_ms: transaction["signedDate"].to_i,
95
+ object: transaction
96
+ )
97
+ charge
98
+ end
99
+
100
+ private
101
+ # The price in the smallest unit of its currency, nil for a currency Pay does not know.
102
+ # Apple sends it in thousandths of the currency unit (14990 for 14.99 euros), whatever
103
+ # the currency's own decimals.
104
+ def amount_from(transaction)
105
+ subunits = Pay::Currency.all.dig(transaction["currency"].to_s.downcase, "subunit_to_unit")
106
+ (BigDecimal(transaction["price"].to_s) * subunits / 1000).round.to_i if subunits
107
+ end
108
+
109
+ # A refund without +revocationType+ is a full one, as before Apple added prorated
110
+ # refunds, except on a transaction the customer upgraded from: its revocation is the
111
+ # upgrade, not a refund. A reversed refund removes the revocation fields.
112
+ def refunded(amount, transaction)
113
+ return 0 if transaction["revocationDate"].nil?
114
+
115
+ type = transaction["revocationType"]
116
+ return 0 if type.present? ? !REFUNDS.include?(type) : transaction["isUpgraded"] == true
117
+
118
+ percentage = transaction["revocationPercentage"] || FULL_REVOCATION
119
+ (BigDecimal(amount) * percentage / FULL_REVOCATION).round.to_i
120
+ end
121
+ end
122
+
123
+ # True for a sandbox or Xcode purchase, which costs nothing: leave it out of revenue.
124
+ def sandbox?
125
+ SANDBOX_ENVIRONMENTS.include?(environment)
126
+ end
127
+
128
+ # Only Apple refunds App Store purchases: send the customer to
129
+ # +Tillbell::AppStore::REFUND_URL+. Apple then notifies the refund, which updates the charge.
130
+ def refund!(*, **)
131
+ raise Tillbell::Error, "Only Apple refunds App Store purchases; the customer asks at #{Tillbell::AppStore::REFUND_URL}"
132
+ end
133
+
134
+ # Pay re-reads a charge from its processor by id; App Store charges are only updated from
135
+ # Apple's signed transactions (see +sync+), which a transaction id alone cannot fetch.
136
+ def sync!(**)
137
+ raise Tillbell::Error, "App Store charges are updated from Apple's notifications, or with tillbell:app_store:backfill_charges"
138
+ end
139
+ end
140
+ end
141
+ end
@@ -7,6 +7,7 @@ module Pay
7
7
  # +appAccountToken+. Apple returns it in every signed transaction, which is how Tillbell
8
8
  # knows which owner a transaction belongs to.
9
9
  class Customer < Pay::Customer
10
+ has_many :charges, dependent: :destroy, class_name: "Pay::AppStore::Charge"
10
11
  has_many :subscriptions, dependent: :destroy, class_name: "Pay::AppStore::Subscription"
11
12
 
12
13
  # Returns the App Store customer of +owner+, creating it on first use.
@@ -42,7 +42,9 @@ module Pay
42
42
 
43
43
  private
44
44
  # Applies the transaction under a row lock, so a purchase request and a notification
45
- # for the same subscription serialize and only one of them emits each event.
45
+ # for the same subscription serialize and only one of them emits each event. The
46
+ # transaction's charge is saved under the same lock, even when the transaction is older
47
+ # than the one the subscription has: a refund notification carries the refunded one.
46
48
  def save_from_apple(pay_customer, transaction, renewal_info)
47
49
  attempts = 0
48
50
  begin
@@ -51,6 +53,7 @@ module Pay
51
53
  subscription.apply(transaction, renewal_info)
52
54
  events = subscription.events_for_changes
53
55
  subscription.save!
56
+ Pay::AppStore::Charge.sync(transaction, subscription)
54
57
  [ subscription, events ]
55
58
  end
56
59
  rescue ActiveRecord::RecordNotUnique
@@ -30,6 +30,12 @@ Tillbell.configure do |config|
30
30
  # Stop giving access that long after the end of a period no App Store notification renewed.
31
31
  # config.apple.stale_after = 16.days
32
32
 
33
+ # In-App Purchase key of App Store Connect, only for bin/rails tillbell:app_store:backfill_charges,
34
+ # which records the App Store payments made before Tillbell recorded them.
35
+ # config.apple.issuer_id = Rails.application.credentials.dig(:tillbell, :apple_issuer_id)
36
+ # config.apple.key_id = Rails.application.credentials.dig(:tillbell, :apple_key_id)
37
+ # config.apple.private_key = Rails.application.credentials.dig(:tillbell, :apple_private_key)
38
+
33
39
  # Who is buying. Evaluated in the controller and the view of the paywall.
34
40
  # config.current_owner = -> { current_user }
35
41
 
@@ -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
@@ -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,
@@ -50,6 +55,13 @@ module Tillbell
50
55
  # purchases, the app cannot. Apple then notifies the refund, which revokes the subscription.
51
56
  REFUND_URL = "https://reportaproblem.apple.com".freeze
52
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
+
53
65
  class << self
54
66
  # The certificates a chain must end at. Only specs change it.
55
67
  attr_writer :root_certificates
@@ -111,6 +123,48 @@ module Tillbell
111
123
  Pay::AppStore::Subscription.sync(transaction, renewal_info)
112
124
  end
113
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
+
114
168
  # The bundle identifier of the iOS app, from +config.apple.bundle_id+. Raises
115
169
  # +Tillbell::Error+ when it is not set.
116
170
  def bundle_id
@@ -145,6 +199,42 @@ module Tillbell
145
199
  end
146
200
 
147
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
+
148
238
  # The payload of +jws+ when it is an Xcode StoreKit Testing transaction that the
149
239
  # configuration allows, otherwise nil. Never in production or staging: without Apple's
150
240
  # signature, anyone could forge one.
@@ -1,3 +1,3 @@
1
1
  module Tillbell
2
- VERSION = "0.7.0"
2
+ VERSION = "0.8.0"
3
3
  end
data/lib/tillbell.rb CHANGED
@@ -70,6 +70,11 @@ module Tillbell
70
70
  # notification renewed or ended keeps giving access, e.g. +16.days+ (set it at
71
71
  # least to the billing grace period of your subscriptions). Nil, the default,
72
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.
73
78
  mattr_accessor :apple, default: ActiveSupport::OrderedOptions.new
74
79
 
75
80
  # Returns the Pay owner (usually a User) the current request acts for, or nil.
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.7.0
4
+ version: 0.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - pmakerhq
@@ -101,6 +101,7 @@ files:
101
101
  - app/helpers/tillbell/paywall_builder.rb
102
102
  - app/helpers/tillbell/paywall_helper.rb
103
103
  - app/jobs/tillbell/sync_job.rb
104
+ - app/models/pay/app_store/charge.rb
104
105
  - app/models/pay/app_store/customer.rb
105
106
  - app/models/pay/app_store/subscription.rb
106
107
  - app/models/pay/google_play/customer.rb