spree_stripe 1.8.2 → 6.0.0.beta1

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.
Files changed (100) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +21 -0
  3. data/README.md +41 -104
  4. data/Rakefile +7 -16
  5. data/app/jobs/spree_stripe/base_job.rb +1 -1
  6. data/app/jobs/spree_stripe/create_webhook_endpoint_job.rb +17 -2
  7. data/app/models/spree/payment_sessions/stripe.rb +45 -11
  8. data/app/models/spree_stripe/gateway/connect.rb +327 -0
  9. data/app/models/spree_stripe/gateway/payment_sessions.rb +225 -112
  10. data/app/models/spree_stripe/gateway/payment_setup_sessions.rb +15 -9
  11. data/app/models/spree_stripe/gateway/webhooks.rb +107 -0
  12. data/app/models/spree_stripe/gateway.rb +197 -244
  13. data/app/models/spree_stripe/payment_sources/ideal.rb +1 -1
  14. data/app/models/spree_stripe/payment_sources/przelewy24.rb +1 -1
  15. data/app/models/spree_stripe/payout_provider.rb +348 -0
  16. data/app/presenters/spree_stripe/customer_presenter.rb +7 -6
  17. data/app/presenters/spree_stripe/statement_descriptor_suffix_presenter.rb +11 -10
  18. data/app/services/spree_stripe/create_gateway_webhooks.rb +57 -33
  19. data/app/services/spree_stripe/create_payment.rb +46 -31
  20. data/app/services/spree_stripe/create_source.rb +22 -22
  21. data/app/services/spree_stripe/update_customer.rb +5 -4
  22. data/app/subscribers/spree_stripe/customer_updated_subscriber.rb +18 -0
  23. data/config/initializers/stripe.rb +1 -13
  24. data/config/locales/en.yml +4 -1
  25. data/lib/generators/spree_stripe/install/install_generator.rb +12 -12
  26. data/lib/spree_stripe/engine.rb +7 -38
  27. data/lib/spree_stripe/factories.rb +1 -3
  28. data/lib/spree_stripe/testing_support/factories/gateway_factory.rb +10 -9
  29. data/lib/spree_stripe/testing_support/factories/payment_session_factory.rb +50 -0
  30. data/lib/spree_stripe.rb +7 -8
  31. data/lib/tasks/migrate_webhook_keys.rake +128 -0
  32. metadata +29 -168
  33. data/app/assets/config/spree_stripe_manifest.js +0 -4
  34. data/app/assets/images/payment_icons/banktransfer.svg +0 -3
  35. data/app/assets/images/payment_icons/link.svg +0 -1
  36. data/app/assets/images/payment_icons/sepadebit.svg +0 -22
  37. data/app/controllers/spree_stripe/apple_pay_domain_verification_controller.rb +0 -11
  38. data/app/controllers/spree_stripe/confirm_payments_controller.rb +0 -52
  39. data/app/controllers/spree_stripe/store_controller_decorator.rb +0 -11
  40. data/app/controllers/stripe_event/webhook_controller_decorator.rb +0 -21
  41. data/app/helpers/spree_stripe/base_helper.rb +0 -42
  42. data/app/helpers/spree_stripe/checkout_helper_decorator.rb +0 -17
  43. data/app/javascript/spree_stripe/application.js +0 -18
  44. data/app/javascript/spree_stripe/controllers/stripe_button_controller.js +0 -431
  45. data/app/javascript/spree_stripe/controllers/stripe_controller.js +0 -234
  46. data/app/jobs/spree_stripe/attach_customer_to_credit_card_job.rb +0 -18
  47. data/app/jobs/spree_stripe/complete_order_from_session_job.rb +0 -12
  48. data/app/jobs/spree_stripe/create_tax_transaction_job.rb +0 -10
  49. data/app/jobs/spree_stripe/register_domain_job.rb +0 -20
  50. data/app/jobs/spree_stripe/update_customer_job.rb +0 -10
  51. data/app/models/spree_stripe/base.rb +0 -6
  52. data/app/models/spree_stripe/calculators/stripe_tax.rb +0 -96
  53. data/app/models/spree_stripe/credit_card_decorator.rb +0 -49
  54. data/app/models/spree_stripe/custom_domain_decorator.rb +0 -20
  55. data/app/models/spree_stripe/gateway/payment_intents.rb +0 -149
  56. data/app/models/spree_stripe/gateway_customer_decorator.rb +0 -9
  57. data/app/models/spree_stripe/order_decorator.rb +0 -9
  58. data/app/models/spree_stripe/payment_decorator.rb +0 -46
  59. data/app/models/spree_stripe/payment_method_decorator.rb +0 -18
  60. data/app/models/spree_stripe/payment_methods_webhook_key.rb +0 -8
  61. data/app/models/spree_stripe/payment_source_decorator.rb +0 -9
  62. data/app/models/spree_stripe/shipment_decorator.rb +0 -21
  63. data/app/models/spree_stripe/store_decorator.rb +0 -26
  64. data/app/models/spree_stripe/user_decorator.rb +0 -21
  65. data/app/models/spree_stripe/webhook_key.rb +0 -14
  66. data/app/presenters/spree_stripe/payment_intent_presenter.rb +0 -101
  67. data/app/presenters/spree_stripe/tax_presenter.rb +0 -63
  68. data/app/services/spree_stripe/complete_order.rb +0 -105
  69. data/app/services/spree_stripe/create_payment_session.rb +0 -18
  70. data/app/services/spree_stripe/register_domain.rb +0 -22
  71. data/app/services/spree_stripe/webhook_handlers/base.rb +0 -19
  72. data/app/services/spree_stripe/webhook_handlers/payment_intent_amount_capturable_updated.rb +0 -13
  73. data/app/services/spree_stripe/webhook_handlers/payment_intent_payment_failed.rb +0 -16
  74. data/app/services/spree_stripe/webhook_handlers/payment_intent_succeeded.rb +0 -11
  75. data/app/services/spree_stripe/webhook_handlers/setup_intent_succeeded.rb +0 -34
  76. data/app/subscribers/spree_stripe/order_completed_subscriber.rb +0 -14
  77. data/app/views/spree/admin/payment_methods/configuration_guides/_spree_stripe.html.erb +0 -0
  78. data/app/views/spree/admin/payment_methods/custom_form_fields/_spree_stripe.html.erb +0 -47
  79. data/app/views/spree/admin/payment_methods/descriptions/_spree_stripe.html.erb +0 -15
  80. data/app/views/spree/checkout/payment/_spree_stripe.html.erb +0 -66
  81. data/app/views/spree_stripe/_head.html.erb +0 -2
  82. data/app/views/spree_stripe/_quick_checkout.html.erb +0 -34
  83. data/config/i18n-tasks.yml +0 -173
  84. data/config/importmap.rb +0 -8
  85. data/config/initializers/spree.rb +0 -9
  86. data/config/routes.rb +0 -11
  87. data/db/migrate/20250310152812_setup_spree_stripe_models.rb +0 -24
  88. data/db/migrate/20260610120000_add_fingerprint_to_spree_credit_cards.rb +0 -52
  89. data/lib/spree_stripe/configuration.rb +0 -11
  90. data/lib/spree_stripe/testing_support/factories/after_pay_payment_source_factory.rb +0 -6
  91. data/lib/spree_stripe/testing_support/factories/alipay_payment_source_factory.rb +0 -6
  92. data/lib/spree_stripe/testing_support/factories/ideal_payment_source_factory.rb +0 -6
  93. data/lib/spree_stripe/testing_support/factories/klarna_payment_source_factory.rb +0 -6
  94. data/lib/spree_stripe/testing_support/factories/link_payment_source_factory.rb +0 -6
  95. data/lib/spree_stripe/testing_support/factories/przelewy24_payment_source_factory.rb +0 -6
  96. data/lib/spree_stripe/testing_support/factories/sepa_debit_payment_source_factory.rb +0 -6
  97. data/lib/spree_stripe/testing_support/factories/stripe_payment_session_factory.rb +0 -33
  98. data/lib/spree_stripe/testing_support/factories/webhook_key_factory.rb +0 -23
  99. data/lib/spree_stripe/version.rb +0 -7
  100. data/vendor/javascript/@stripe--stripe-js--dist--pure.esm.js.js +0 -4
@@ -0,0 +1,348 @@
1
+ module SpreeStripe
2
+ # Pays sellers through Stripe Connect.
3
+ #
4
+ # The marketplace charges the customer on its own account, then moves each
5
+ # seller's share to their connected account as the goods go out. Two things
6
+ # make that work and are worth naming:
7
+ #
8
+ # **The transfer names the charge that funds it.** Stripe's `source_transaction`
9
+ # ties a transfer to a specific charge, so the money moves as soon as that
10
+ # charge settles rather than waiting for the platform's own balance to cover
11
+ # it — a marketplace should not have to float its sellers.
12
+ #
13
+ # **Settlement is Stripe's own schedule.** Once money is on a connected
14
+ # account, Stripe pays it out to the seller's bank on the schedule configured
15
+ # for that account. So {#pay!} does not send anything: it records what Stripe
16
+ # is going to do, and a webhook confirms when it did.
17
+ #
18
+ # Every call carries an idempotency key derived from the ledger row, so a
19
+ # retry finds the movement it already made instead of making a second. That
20
+ # holds only while Stripe keeps the record, which is a day — so a call whose
21
+ # answer was lost is reported as ambiguous rather than failed, and core
22
+ # holds the settlement instead of retrying it later on a key that has since
23
+ # expired.
24
+ class PayoutProvider < Spree::PayoutProvider::Base
25
+ # Stripe is looking at the account, and there is nothing the seller can do
26
+ # about it — different words and no button, rather than an invitation to
27
+ # go round the same flow again.
28
+ PENDING_REASONS = %w[under_review requirements.pending_verification platform_paused].freeze
29
+
30
+ # Failures that leave the answer with Stripe rather than in the response,
31
+ # so core must not assume the money stayed put.
32
+ #
33
+ # A dropped connection or a timeout may have arrived all the same. An
34
+ # `APIError` is Stripe's own 5xx, which says nothing about whether the
35
+ # request was processed before it broke. An `IdempotencyError` means the
36
+ # key is already held against different parameters, so *something* was
37
+ # recorded under it.
38
+ #
39
+ # `Stripe::APIError` is spelled with a capitalised initialism; there is no
40
+ # `Stripe::ApiError`, and naming one in a rescue raises NameError at the
41
+ # moment the rescue is needed.
42
+ AMBIGUOUS_ERRORS = [
43
+ Stripe::APIConnectionError,
44
+ Stripe::APIError,
45
+ Stripe::IdempotencyError
46
+ ].freeze
47
+
48
+ def self.display_name
49
+ 'Stripe Connect'
50
+ end
51
+
52
+ # Matches the Stripe gateway's own integration key, so a seller's Connect
53
+ # account is filed under the same name the rest of the gem uses.
54
+ def self.reference_system
55
+ 'stripe'
56
+ end
57
+
58
+ # A seller must hold a connected account before anything can be sent to
59
+ # them, so core will not credit one who does not.
60
+ def self.requires_payout_account?
61
+ true
62
+ end
63
+
64
+ def self.available_for_store?(store)
65
+ gateway_for(store).present?
66
+ end
67
+
68
+ # The store's Stripe gateway — the account that charges customers, and so
69
+ # the account that pays sellers.
70
+ #
71
+ # @return [SpreeStripe::Gateway, nil]
72
+ def self.gateway_for(store)
73
+ store.payment_methods.active.find { |method| method.is_a?(SpreeStripe::Gateway) }
74
+ end
75
+
76
+ # Stripe's own hosted onboarding, where the seller gives Stripe their
77
+ # identity and bank details directly — so the marketplace never handles
78
+ # them and inherits Stripe's checks rather than building its own.
79
+ def onboarding_url(seller, refresh_url:, return_url:)
80
+ gateway_for(seller.store).create_connect_account_link(
81
+ seller: seller,
82
+ refresh_url: refresh_url,
83
+ return_url: return_url
84
+ )
85
+ rescue Stripe::StripeError => e
86
+ # Core knows nothing about Stripe's exceptions, and a seller asking to
87
+ # set up their payouts should be told what went wrong rather than shown
88
+ # a crash. The provider contract speaks GatewayError.
89
+ raise Spree::Core::GatewayError, e.message
90
+ end
91
+
92
+ # Asked of Stripe rather than read from `payouts_enabled_at`.
93
+ #
94
+ # That column is a cache of what a webhook last told us, and a webhook is
95
+ # a thing that can fail to arrive — an endpoint not yet registered, a
96
+ # delivery dropped, a local tunnel that was not running. A seller who has
97
+ # finished onboarding then sits looking at a checklist that says they have
98
+ # not, while Stripe has been ready to pay them for hours.
99
+ #
100
+ # The account is fetched once per instance either way, since answering why
101
+ # a row is incomplete needs it too.
102
+ def onboarded?(seller)
103
+ account = retrieve_account(seller)
104
+ return seller.payouts_enabled? if account.nil?
105
+
106
+ # What Stripe says, written down. The stamp is a cache of a webhook that
107
+ # can fail to arrive in either direction — a seller left looking at an
108
+ # unfinished checklist they have finished, or one still counted payable
109
+ # after Stripe withdrew it. Recording the answer keeps the workflows
110
+ # that gate money on the column honest without their asking.
111
+ stamp = account.payouts_enabled ? (seller.payouts_enabled_at || Time.current) : nil
112
+
113
+ if seller.payouts_enabled_at != stamp
114
+ became_payable = stamp.present?
115
+ seller.update!(payouts_enabled_at: stamp)
116
+ # Whatever they earned while we believed they could not be paid. The
117
+ # webhook normally does this; noticing here covers the case where it
118
+ # never arrived, which is otherwise money sitting pending forever.
119
+ Spree::SellerTransfers::ExecutePendingJob.perform_later(seller.id) if became_payable
120
+ end
121
+
122
+ account.payouts_enabled
123
+ end
124
+
125
+ # Which of the three things is true, read off the account itself.
126
+ #
127
+ # Stripe's `disabled_reason` is the account-level answer, and its values
128
+ # divide cleanly: some mean the seller must do something, some mean Stripe
129
+ # is looking and nobody can hurry it, and some mean Stripe has said no.
130
+ # The per-field requirement list is deliberately not read — Stripe's own
131
+ # guidance for Express is to send the seller back to hosted onboarding
132
+ # rather than enumerate what it wants, since that flow already knows.
133
+ def onboarding_state(seller)
134
+ account = retrieve_account(seller)
135
+ return nil if account.nil? || account.payouts_enabled
136
+
137
+ reason = account.requirements&.disabled_reason.to_s
138
+ return :rejected if reason.start_with?('rejected.') || reason == 'listed'
139
+ return :pending if PENDING_REASONS.include?(reason)
140
+
141
+ :action
142
+ end
143
+
144
+ # Stripe writes these itself, in English, and says so — shown as detail
145
+ # beside translated copy, never instead of it. Only the failures have one:
146
+ # a field simply not provided yet has no error and nothing to say.
147
+ def onboarding_message(seller)
148
+ account = retrieve_account(seller)
149
+ return nil if account.nil?
150
+
151
+ Array(account.requirements&.errors).filter_map { |error| error[:reason] }.first
152
+ end
153
+
154
+ # Moves one seller's earning to their connected account.
155
+ def transfer!(seller_transfer)
156
+ # Nothing to move. A seller whose commission met their sale earns zero,
157
+ # which is a true ledger row and an amount Stripe refuses — asking it to
158
+ # would park the row and have the retry job ask again forever.
159
+ return complete_without_sending(seller_transfer) if minor_units(seller_transfer).zero?
160
+
161
+ seller = seller_transfer.seller
162
+ gateway = gateway_for(seller.store)
163
+ source_charge = source_charge_for(seller_transfer, gateway)
164
+
165
+ transfer = Stripe::Transfer.create(
166
+ {
167
+ amount: minor_units(seller_transfer),
168
+ currency: seller_transfer.currency.downcase,
169
+ destination: seller.payout_account_reference(self.class),
170
+ # Funds the transfer from the customer's own charge, so it settles
171
+ # with that charge rather than out of the platform's balance.
172
+ source_transaction: source_charge,
173
+ # Stripe refuses a second group on a transfer drawn from a charge
174
+ # that already carries one, and the intent is grouped at checkout.
175
+ transfer_group: (transfer_group_for(seller_transfer) if source_charge.blank?),
176
+ metadata: {
177
+ spree_seller_transfer_id: seller_transfer.id,
178
+ spree_order_number: seller_transfer.order.number
179
+ },
180
+ # What the seller's own account received. An account settles in its
181
+ # own currency and Stripe converts on the way in, so the sale's
182
+ # figure is not the payable one.
183
+ expand: ['destination_payment.balance_transaction']
184
+ }.compact,
185
+ gateway.api_options.merge(idempotency_key: idempotency_key(seller_transfer))
186
+ )
187
+
188
+ seller_transfer.update!(
189
+ { status: 'completed', reference: transfer.id }.merge(settlement_of(transfer))
190
+ )
191
+ seller_transfer
192
+ rescue *AMBIGUOUS_ERRORS => e
193
+ # As with a settlement: the transfer may have been made before the answer
194
+ # was lost, so core parks the earning rather than offering it to the
195
+ # retry job, which would send the same money again once Stripe has
196
+ # forgotten the key.
197
+ raise Spree::Core::AmbiguousGatewayError, e.message
198
+ end
199
+
200
+ # Sends a settlement from the seller's connected account to their bank.
201
+ #
202
+ # Spree decides when — connected accounts are created on a manual schedule
203
+ # precisely so Stripe is not also paying out on one of its own. Two clocks
204
+ # on one relationship do not compose: honour both and a monthly seller
205
+ # waits up to two months, honour neither and the operator's setting is a
206
+ # decoration.
207
+ #
208
+ # Made as the connected account rather than as the platform, because the
209
+ # money being moved is the seller's own balance. The payout stays pending
210
+ # until `payout.paid` says it reached the bank — a settlement is a claim
211
+ # about the outside world whoever makes it.
212
+ def pay!(seller_payout)
213
+ seller = seller_payout.seller
214
+ gateway = gateway_for(seller.store)
215
+ account_id = seller.payout_account_reference(self.class)
216
+ raise Spree::Core::GatewayError, 'Seller holds no Stripe account' if account_id.blank?
217
+
218
+ payout = Stripe::Payout.create(
219
+ {
220
+ amount: minor_units(seller_payout),
221
+ currency: seller_payout.currency.downcase,
222
+ metadata: { spree_seller_payout_id: seller_payout.id }
223
+ },
224
+ gateway.api_options.merge(stripe_account: account_id, idempotency_key: idempotency_key(seller_payout))
225
+ )
226
+
227
+ # Stored now rather than waiting for the webhook, so the confirmation
228
+ # matches on Stripe's own id instead of guessing by amount.
229
+ seller_payout.update!(reference: payout.id)
230
+ seller_payout
231
+ rescue *AMBIGUOUS_ERRORS => e
232
+ # Nobody knows whether the money moved. The request may have reached
233
+ # Stripe and created the payout before the answer was lost, so core must
234
+ # not put these earnings back on the pile — the idempotency key stops a
235
+ # retry only while Stripe keeps the record, which is a day, and sweeps
236
+ # run on a merchant's schedule rather than inside one.
237
+ raise Spree::Core::AmbiguousGatewayError, e.message
238
+ end
239
+
240
+ # What the seller's account can send today, in the currency asked for.
241
+ #
242
+ # A transfer is credited on fulfilment but funded by the customer's charge,
243
+ # so the money reaches the seller's balance only when that charge settles.
244
+ # Asking Stripe is the documented way to know the difference; a payout for
245
+ # more than the available balance is refused outright.
246
+ #
247
+ # Zero when the account holds nothing in this currency — including a
248
+ # cross-border seller whose account settles in its own currency and can
249
+ # therefore never pay out what the ledger denominated the sale in.
250
+ #
251
+ # @return [BigDecimal]
252
+ def available_payout(seller, currency)
253
+ gateway = gateway_for(seller.store)
254
+ account_id = seller.payout_account_reference(self.class)
255
+ raise Spree::Core::GatewayError, 'Seller holds no Stripe account' if account_id.blank?
256
+
257
+ balance = Stripe::Balance.retrieve({}, gateway.api_options.merge(stripe_account: account_id))
258
+ wanted = currency.to_s.downcase
259
+ minor = balance.available.select { |entry| entry.currency == wanted }.sum(&:amount)
260
+
261
+ Spree::Money::Rounding.from_minor_units(minor, currency)
262
+ rescue *AMBIGUOUS_ERRORS => e
263
+ # The sweep must not read silence as "nothing to send" and settle a
264
+ # smaller batch than the seller is owed, nor as "no limit" and ask for
265
+ # everything again. Neither is knowable, so nothing is paid this period.
266
+ raise Spree::Core::AmbiguousGatewayError, e.message
267
+ end
268
+
269
+ # Pulls a seller's money back after a refund.
270
+ #
271
+ # Ledger-only in open source: the row is written either way, so the books
272
+ # stay correct, but reversing the Stripe transfer — and netting a negative
273
+ # balance against future earnings — is where a marketplace needs the money
274
+ # operations that Enterprise provides.
275
+ def reverse!(seller_transfer)
276
+ seller_transfer.update!(status: 'completed')
277
+ seller_transfer
278
+ end
279
+
280
+ private
281
+
282
+ # What landed on the seller's account, read off the balance transaction of
283
+ # the payment the transfer created there. Empty when Stripe did not expand
284
+ # it, which leaves the ledger reading the earned figures rather than
285
+ # inventing a settlement.
286
+ #
287
+ # @return [Hash]
288
+ def settlement_of(transfer)
289
+ balance_transaction = transfer.try(:destination_payment).try(:balance_transaction)
290
+ return {} if balance_transaction.blank? || balance_transaction.try(:currency).blank?
291
+
292
+ {
293
+ settled_amount: Spree::Money::Rounding.from_minor_units(balance_transaction.amount,
294
+ balance_transaction.currency),
295
+ settled_currency: balance_transaction.currency.upcase
296
+ }
297
+ end
298
+
299
+ def complete_without_sending(seller_transfer)
300
+ seller_transfer.update!(status: 'completed')
301
+ seller_transfer
302
+ end
303
+
304
+ # Nil rather than raising: a checklist row asking why it is incomplete
305
+ # must not take the page down because Stripe is unreachable.
306
+ def retrieve_account(seller)
307
+ account_id = seller.payout_account_reference(self.class)
308
+ return nil if account_id.blank?
309
+
310
+ @retrieved_accounts ||= {}
311
+ @retrieved_accounts[account_id] ||= Stripe::Account.retrieve(
312
+ account_id, gateway_for(seller.store).api_options
313
+ )
314
+ rescue Stripe::StripeError => e
315
+ Rails.error.report(e, handled: true, context: { seller_id: seller.id }, source: 'spree_stripe')
316
+ nil
317
+ end
318
+
319
+ def gateway_for(store)
320
+ self.class.gateway_for(store) ||
321
+ raise(Spree::Core::GatewayError, 'No active Stripe payment method on this store')
322
+ end
323
+
324
+ def minor_units(record)
325
+ Spree::Money::Rounding.to_minor_units(record.amount.abs, record.currency)
326
+ end
327
+
328
+ # Ties transfers paid from the platform balance to the checkout they
329
+ # settle — a split checkout's sellers share their group's number.
330
+ def transfer_group_for(seller_transfer)
331
+ seller_transfer.order.order_group&.number || seller_transfer.order.number
332
+ end
333
+
334
+ # The charge that paid for this order, so Stripe can fund the transfer from
335
+ # it. Nil when the order was not paid by card — a store-credit sale has no
336
+ # charge to draw on, and Stripe then funds from the platform balance.
337
+ # Stripe funds a transfer from a *charge*, and `response_code` holds the
338
+ # payment intent rather than the charge it produced — sending that would
339
+ # fail every card-funded transfer on an id Stripe cannot use. The charge
340
+ # is recorded on the payment when its session completes.
341
+ def source_charge_for(seller_transfer, gateway)
342
+ payment = seller_transfer.order.settlement_payments.valid.completed.
343
+ find { |candidate| candidate.payment_method_id == gateway.id }
344
+
345
+ payment&.metadata&.dig('stripe_charge_id')
346
+ end
347
+ end
348
+ end
@@ -6,12 +6,12 @@ module SpreeStripe
6
6
  @address = address
7
7
  end
8
8
 
9
+ # @return [Hash]
9
10
  def call
10
11
  hash = {}
11
12
  hash[:address] = address_payload if address.present?
12
13
  hash[:email] = email if email.present?
13
14
  hash[:name] = name if name.present?
14
-
15
15
  hash
16
16
  end
17
17
 
@@ -19,16 +19,17 @@ module SpreeStripe
19
19
 
20
20
  attr_reader :email, :name, :address
21
21
 
22
+ # ISO codes, matching the intent's shipping payload — Stripe expects
23
+ # ISO 3166-1 alpha-2 for country, and full names degrade Stripe-side
24
+ # location resolution (tax, risk rules).
22
25
  def address_payload
23
- return {} unless address
24
-
25
26
  {
26
27
  city: address.city,
27
28
  line1: address.address1,
28
29
  line2: address.address2,
29
- postal_code: address.zipcode,
30
- country: address.country_name,
31
- state: address.state_name_text
30
+ postal_code: address.postal_code,
31
+ country: address.country_code,
32
+ state: address.state_code.presence || address.state_name_text
32
33
  }
33
34
  end
34
35
  end
@@ -1,17 +1,20 @@
1
1
  module SpreeStripe
2
+ # Builds the suffix shown on the customer's bank statement. Stripe rejects a
3
+ # suffix with no letters, so a purely numeric order number gets an "O#" prefix.
2
4
  class StatementDescriptorSuffixPresenter
3
5
  STATEMENT_DESCRIPTOR_MAX_CHARS = 10
4
6
  STATEMENT_DESCRIPTOR_NOT_ALLOWED_CHARS = /[<>'"*\\]/.freeze
5
- STATEMENT_PREFIX = 'O#'
7
+ STATEMENT_PREFIX = 'O#'.freeze
6
8
 
7
9
  def initialize(order_description:)
8
10
  @order_description = order_description.to_s
9
11
  end
10
12
 
13
+ # @return [String, nil]
11
14
  def call
12
15
  return if stripped_order_description.blank?
13
16
 
14
- if stripped_order_description.count("A-Z") > 0
17
+ if stripped_order_description.count('A-Z').positive?
15
18
  stripped_order_description
16
19
  else
17
20
  "#{STATEMENT_PREFIX}#{stripped_order_description}"[0...STATEMENT_DESCRIPTOR_MAX_CHARS].strip
@@ -23,13 +26,11 @@ module SpreeStripe
23
26
  attr_reader :order_description
24
27
 
25
28
  def stripped_order_description
26
- @stripped_order_description ||= begin
27
- I18n.transliterate(order_description)
28
- .gsub(STATEMENT_DESCRIPTOR_NOT_ALLOWED_CHARS, '')
29
- .strip
30
- .upcase[0...STATEMENT_DESCRIPTOR_MAX_CHARS]
31
- .strip
32
- end
29
+ @stripped_order_description ||= I18n.transliterate(order_description).
30
+ gsub(STATEMENT_DESCRIPTOR_NOT_ALLOWED_CHARS, '').
31
+ strip.
32
+ upcase[0...STATEMENT_DESCRIPTOR_MAX_CHARS].
33
+ strip
33
34
  end
34
35
  end
35
- end
36
+ end
@@ -1,55 +1,79 @@
1
1
  module SpreeStripe
2
+ # Registers a webhook endpoint with Stripe and stores the signing secret on
3
+ # the payment method.
4
+ #
5
+ # A marketplace registers two: one for its own payment events, one for the
6
+ # events originating inside its sellers' connected accounts. Stripe scopes
7
+ # those separately and signs each with its own secret, so which endpoint is
8
+ # being registered decides the URL, the events, and the preference the secret
9
+ # lands in.
2
10
  class CreateGatewayWebhooks
3
- def call(payment_method:, events: SpreeStripe::Config[:supported_webhook_events], connect: false)
4
- webhook_list = Stripe::WebhookEndpoint.list({}, { api_key: payment_method.preferred_secret_key })
5
- webhook = find_webhook(payment_method, webhook_list[:data], events)
11
+ # @param payment_method [SpreeStripe::Gateway]
12
+ # @param connect [Boolean] true registers the connected-accounts endpoint
13
+ # @return [Stripe::WebhookEndpoint, nil]
14
+ def call(payment_method:, events: nil, connect: false)
15
+ events ||= connect ? SpreeStripe::Gateway::Connect::CONNECT_EVENTS : SpreeStripe::Gateway::Webhooks::SUPPORTED_EVENTS
16
+ webhook_url = connect ? payment_method.connect_webhook_url : payment_method.webhook_url
17
+ return if webhook_url.blank?
6
18
 
7
- ensure_webhook(payment_method, webhook, connect, events)
19
+ api_options = { api_key: payment_method.preferred_secret_key }
20
+ # Asked for in full rather than taking Stripe's default page of ten: an
21
+ # account holds at most sixteen endpoints, so one call sees them all, and
22
+ # a marketplace registers two per gateway. Missing our own is not a
23
+ # harmless miss — Stripe does not treat the URL as unique, so the caller
24
+ # would create a second endpoint beside it and every event would arrive
25
+ # twice, half of them signed with a secret we do not hold.
26
+ existing = find_webhook(
27
+ Stripe::WebhookEndpoint.list({ limit: 100 }, api_options)[:data],
28
+ webhook_url,
29
+ events
30
+ )
31
+
32
+ # Stripe only returns the signing secret when the endpoint is created, so a
33
+ # pre-existing endpoint whose secret we do not hold has to be replaced.
34
+ if existing.present? && stored_endpoint_id(payment_method, connect) == existing[:id] &&
35
+ stored_secret(payment_method, connect).present?
36
+ return existing
37
+ end
38
+
39
+ Stripe::WebhookEndpoint.delete(existing[:id], {}, api_options) if existing.present?
40
+
41
+ create_webhook_endpoint(payment_method, webhook_url, events, connect, api_options)
8
42
  end
9
43
 
10
44
  private
11
45
 
12
- def find_webhook(payment_method, webhooks_data, enabled_events)
13
- webhook_url = payment_method.webhook_url
14
-
46
+ def find_webhook(webhooks_data, webhook_url, enabled_events)
15
47
  webhooks_data.find do |webhook|
16
48
  webhook[:url] == webhook_url && webhook[:enabled_events].sort == enabled_events.sort
17
49
  end
18
50
  end
19
51
 
20
- def ensure_webhook(payment_method, stripe_webhook, connect, events)
21
- if stripe_webhook.nil?
22
- create_webhook_endpoint(payment_method, connect, events)
23
- else
24
- webhook_key = WebhookKey.find_by(stripe_id: stripe_webhook[:id])
52
+ def stored_endpoint_id(payment_method, connect)
53
+ connect ? payment_method.preferred_connect_webhook_endpoint_id : payment_method.preferred_webhook_endpoint_id
54
+ end
25
55
 
26
- if webhook_key.present?
27
- webhook_key.payment_methods << payment_method if webhook_key.payment_methods.exclude?(payment_method)
28
- else
29
- create_webhook_endpoint(payment_method, connect, events)
30
- end
56
+ def stored_secret(payment_method, connect)
57
+ if connect
58
+ payment_method.preferred_connect_webhook_signing_secret
59
+ else
60
+ payment_method.preferred_webhook_signing_secret
31
61
  end
32
62
  end
33
63
 
34
- def create_webhook_endpoint(payment_method, connect, events)
35
- params = build_webhook_params(payment_method, connect, events)
36
- stripe_webhook = Stripe::WebhookEndpoint.create(params, { api_key: payment_method.preferred_secret_key })
37
-
38
- SpreeStripe::WebhookKey.create!(
39
- stripe_id: stripe_webhook[:id],
40
- signing_secret: stripe_webhook[:secret],
41
- payment_methods: [payment_method]
64
+ def create_webhook_endpoint(payment_method, webhook_url, events, connect, api_options)
65
+ stripe_webhook = Stripe::WebhookEndpoint.create(
66
+ { url: webhook_url, enabled_events: events, connect: connect },
67
+ api_options
42
68
  )
43
69
 
44
- Rails.cache.delete('stripe_webhook_signing_keys')
45
- end
70
+ prefix = connect ? 'preferred_connect_webhook' : 'preferred_webhook'
71
+ payment_method.update!(
72
+ :"#{prefix}_endpoint_id" => stripe_webhook[:id],
73
+ :"#{prefix}_signing_secret" => stripe_webhook[:secret]
74
+ )
46
75
 
47
- def build_webhook_params(payment_method, connect, events)
48
- {
49
- url: payment_method.webhook_url,
50
- enabled_events: events,
51
- connect: connect
52
- }
76
+ stripe_webhook
53
77
  end
54
78
  end
55
79
  end
@@ -1,52 +1,67 @@
1
1
  module SpreeStripe
2
+ # @deprecated Unused since 6.0 and removed in 7.0. Core's
3
+ # Spree::PaymentSession#find_or_create_payment! creates the payment now;
4
+ # this gem only supplies the source, through
5
+ # Spree::PaymentSessions::Stripe#payment_source_for_settlement.
6
+ #
7
+ # It diverged from core in three ways that this consolidation fixed: it
8
+ # never set skip_source_requirement (so a session with no charge raised
9
+ # "Source can't be blank"), it keyed idempotency on the amount as well as
10
+ # the intent (so an amount change minted a second payment), and it did not
11
+ # rescue RecordNotUnique (so the webhook/return race could crash).
2
12
  class CreatePayment
3
- def initialize(order:, payment_intent:, gateway: nil, tax_transaction: nil, amount: nil)
4
- @order = order
5
- @gateway = gateway || order.store.stripe_gateway
6
- @payment_intent = payment_intent
7
- @tax_transaction = tax_transaction
8
- @amount = amount || order.total_minus_store_credits
13
+ # @param owner [Spree::Cart, Spree::Order]
14
+ # @param payment_session [Spree::PaymentSessions::Stripe]
15
+ # @param gateway [SpreeStripe::Gateway] the session's payment method
16
+ def initialize(owner:, payment_session:, gateway:, amount: nil)
17
+ @owner = owner
18
+ @gateway = gateway
19
+ @payment_session = payment_session
20
+ @amount = amount || owner.total_minus_store_credits
9
21
  end
10
22
 
23
+ # @return [Spree::Payment]
11
24
  def call
12
- stripe_charge = payment_intent.stripe_charge
25
+ stripe_charge = payment_session.stripe_charge
26
+ source = build_source(stripe_charge)
13
27
 
28
+ # A retried job must not produce a second payment for the same intent.
29
+ payment = owner.payments.find_or_initialize_by(
30
+ payment_method_id: gateway.id,
31
+ response_code: payment_session.stripe_id,
32
+ amount: amount
33
+ )
34
+
35
+ payment.source = source if source.present?
36
+ payment.metadata['stripe_charge_id'] = stripe_charge.id if stripe_charge.present?
37
+ payment.save!
38
+ payment
39
+ end
40
+
41
+ private
42
+
43
+ attr_reader :owner, :gateway, :payment_session, :amount
44
+
45
+ def build_source(stripe_charge)
14
46
  if stripe_charge.present?
15
- source = SpreeStripe::CreateSource.new(
16
- order: order,
47
+ SpreeStripe::CreateSource.new(
48
+ owner: owner,
17
49
  stripe_payment_method_details: stripe_charge.payment_method_details,
18
50
  stripe_payment_method_id: stripe_charge.payment_method,
19
51
  stripe_billing_details: stripe_charge.billing_details,
20
52
  gateway: gateway
21
53
  ).call
22
- elsif payment_intent.charge_not_required?
23
- stripe_payment_intent = payment_intent.stripe_payment_intent
24
- source = SpreeStripe::CreateSource.new(
25
- order: order,
54
+ elsif payment_session.charge_not_required?
55
+ stripe_payment_intent = payment_session.stripe_payment_intent
56
+
57
+ SpreeStripe::CreateSource.new(
58
+ owner: owner,
26
59
  stripe_payment_method_details: stripe_payment_intent.payment_method,
27
60
  stripe_payment_method_id: stripe_payment_intent.payment_method.id,
28
61
  stripe_billing_details: nil,
29
62
  gateway: gateway
30
63
  ).call
31
64
  end
32
-
33
- # sometimes a job is re-tried and creates a double payment record so we need to avoid it!
34
- payment = order.payments.find_or_initialize_by(
35
- payment_method_id: gateway.id,
36
- response_code: payment_intent.stripe_id,
37
- amount: amount
38
- )
39
-
40
- payment.source = source if source.present?
41
- payment.stripe_tax_transaction_id = tax_transaction
42
- payment.stripe_charge_id = stripe_charge&.id
43
-
44
- payment.save!
45
- payment
46
65
  end
47
-
48
- private
49
-
50
- attr_reader :order, :gateway, :payment_intent, :tax_transaction, :source, :amount
51
66
  end
52
67
  end