spree_adyen 0.11.0 → 6.0.7

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 (159) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +16 -4
  3. data/README.md +9 -51
  4. data/Rakefile +7 -18
  5. data/app/jobs/spree_adyen/base_job.rb +1 -1
  6. data/app/jobs/spree_adyen/configure_job.rb +19 -0
  7. data/app/maintenance_tasks/spree_adyen/maintenance_tasks/migrate_payments.rb +129 -0
  8. data/app/models/spree/payment_sessions/adyen.rb +42 -35
  9. data/app/models/spree/payment_setup_sessions/adyen.rb +1 -25
  10. data/app/models/spree_adyen/amounts.rb +69 -0
  11. data/app/models/spree_adyen/gateway/payment_sessions.rb +228 -98
  12. data/app/models/spree_adyen/gateway/payment_setup_sessions.rb +36 -136
  13. data/app/models/spree_adyen/gateway/webhooks.rb +142 -0
  14. data/app/models/spree_adyen/gateway.rb +275 -399
  15. data/app/models/spree_adyen/payment_sources/ach_direct_debit.rb +1 -13
  16. data/app/models/spree_adyen/payment_sources/affirm.rb +1 -13
  17. data/app/models/spree_adyen/payment_sources/afterpay.rb +1 -13
  18. data/app/models/spree_adyen/payment_sources/alipay.rb +1 -15
  19. data/app/models/spree_adyen/payment_sources/alipay_hk.rb +1 -13
  20. data/app/models/spree_adyen/payment_sources/alma.rb +1 -13
  21. data/app/models/spree_adyen/payment_sources/ancv.rb +1 -13
  22. data/app/models/spree_adyen/payment_sources/atome.rb +1 -13
  23. data/app/models/spree_adyen/payment_sources/bacs.rb +1 -13
  24. data/app/models/spree_adyen/payment_sources/bancontact.rb +1 -15
  25. data/app/models/spree_adyen/payment_sources/bank_transfer.rb +1 -13
  26. data/app/models/spree_adyen/payment_sources/base.rb +9 -1
  27. data/app/models/spree_adyen/payment_sources/benefit.rb +1 -13
  28. data/app/models/spree_adyen/payment_sources/billie.rb +1 -13
  29. data/app/models/spree_adyen/payment_sources/bizum.rb +1 -13
  30. data/app/models/spree_adyen/payment_sources/blik.rb +1 -11
  31. data/app/models/spree_adyen/payment_sources/boleto.rb +1 -13
  32. data/app/models/spree_adyen/payment_sources/card.rb +14 -0
  33. data/app/models/spree_adyen/payment_sources/cash_app_afterpay.rb +1 -13
  34. data/app/models/spree_adyen/payment_sources/cashapp.rb +1 -13
  35. data/app/models/spree_adyen/payment_sources/clearpay.rb +1 -13
  36. data/app/models/spree_adyen/payment_sources/dana.rb +1 -13
  37. data/app/models/spree_adyen/payment_sources/doku.rb +1 -15
  38. data/app/models/spree_adyen/payment_sources/duitnow.rb +1 -13
  39. data/app/models/spree_adyen/payment_sources/eps.rb +1 -15
  40. data/app/models/spree_adyen/payment_sources/fastlane.rb +1 -15
  41. data/app/models/spree_adyen/payment_sources/fpx.rb +1 -15
  42. data/app/models/spree_adyen/payment_sources/gcash.rb +1 -15
  43. data/app/models/spree_adyen/payment_sources/gift_cards.rb +1 -15
  44. data/app/models/spree_adyen/payment_sources/giropay.rb +1 -15
  45. data/app/models/spree_adyen/payment_sources/grabpay.rb +1 -15
  46. data/app/models/spree_adyen/payment_sources/ideal.rb +1 -11
  47. data/app/models/spree_adyen/payment_sources/klarna.rb +1 -28
  48. data/app/models/spree_adyen/payment_sources/oney.rb +1 -9
  49. data/app/models/spree_adyen/payment_sources/online_banking_czech_republic.rb +1 -11
  50. data/app/models/spree_adyen/payment_sources/online_banking_poland.rb +1 -11
  51. data/app/models/spree_adyen/payment_sources/pay_by_bank.rb +1 -11
  52. data/app/models/spree_adyen/payment_sources/paypal.rb +1 -11
  53. data/app/models/spree_adyen/payment_sources/paypo.rb +1 -11
  54. data/app/models/spree_adyen/payment_sources/paysafecard.rb +1 -11
  55. data/app/models/spree_adyen/payment_sources/rate_pay_direct_debit.rb +1 -11
  56. data/app/models/spree_adyen/payment_sources/riverty.rb +1 -11
  57. data/app/models/spree_adyen/payment_sources/samsung_pay.rb +1 -11
  58. data/app/models/spree_adyen/payment_sources/scalapay.rb +1 -9
  59. data/app/models/spree_adyen/payment_sources/sepa_direct_debit.rb +1 -11
  60. data/app/models/spree_adyen/payment_sources/trustly.rb +1 -11
  61. data/app/models/spree_adyen/payment_sources/unknown.rb +1 -15
  62. data/app/models/spree_adyen/payment_sources/wechat_pay.rb +1 -11
  63. data/app/models/spree_adyen/result.rb +155 -0
  64. data/app/models/spree_adyen/variants.rb +230 -0
  65. data/app/presenters/spree_adyen/application_info_presenter.rb +4 -4
  66. data/app/presenters/spree_adyen/session_presenter.rb +153 -0
  67. data/app/services/spree_adyen/configure.rb +121 -0
  68. data/app/subscribers/spree_adyen/capture_held_payments_subscriber.rb +41 -0
  69. data/config/locales/en.yml +21 -6
  70. data/lib/generators/spree_adyen/install/install_generator.rb +12 -12
  71. data/lib/spree_adyen/engine.rb +6 -70
  72. data/lib/spree_adyen/factories.rb +1 -3
  73. data/lib/spree_adyen/testing_support/factories/gateway_factory.rb +10 -17
  74. data/lib/spree_adyen/testing_support/factories/payment_session_factory.rb +18 -34
  75. data/lib/spree_adyen.rb +5 -30
  76. data/lib/tasks/configure_adyen_gateways.rake +39 -0
  77. metadata +35 -177
  78. data/app/assets/config/spree_adyen_manifest.js +0 -5
  79. data/app/controllers/spree_adyen/apple_pay_domain_verification_controller.rb +0 -11
  80. data/app/controllers/spree_adyen/payment_sessions_controller.rb +0 -67
  81. data/app/controllers/spree_adyen/store_controller_decorator.rb +0 -9
  82. data/app/controllers/spree_adyen/webhooks_controller.rb +0 -46
  83. data/app/helpers/spree_adyen/base_helper.rb +0 -18
  84. data/app/javascript/spree_adyen/application.js +0 -17
  85. data/app/javascript/spree_adyen/controllers/checkout_adyen_controller.js +0 -80
  86. data/app/javascript/spree_adyen/controllers/redirect_adyen_controller.js +0 -35
  87. data/app/jobs/spree_adyen/add_allowed_origin_job.rb +0 -24
  88. data/app/jobs/spree_adyen/webhooks/process_authorisation_event_job.rb +0 -10
  89. data/app/jobs/spree_adyen/webhooks/process_cancellation_event_job.rb +0 -10
  90. data/app/jobs/spree_adyen/webhooks/process_capture_event_job.rb +0 -10
  91. data/app/models/spree_adyen/base.rb +0 -6
  92. data/app/models/spree_adyen/custom_domain_decorator.rb +0 -17
  93. data/app/models/spree_adyen/order_decorator.rb +0 -23
  94. data/app/models/spree_adyen/payment_decorator.rb +0 -66
  95. data/app/models/spree_adyen/payment_method_decorator.rb +0 -15
  96. data/app/models/spree_adyen/payment_session.rb +0 -121
  97. data/app/models/spree_adyen/payment_sources/apple_pay.rb +0 -19
  98. data/app/models/spree_adyen/payment_sources/bcmc.rb +0 -17
  99. data/app/models/spree_adyen/payment_sources/bcmc_mobile.rb +0 -17
  100. data/app/models/spree_adyen/payment_sources/ebanking_fi.rb +0 -19
  101. data/app/models/spree_adyen/payment_sources/eft_directdebit_ca.rb +0 -19
  102. data/app/models/spree_adyen/payment_sources/eftpos_australia.rb +0 -19
  103. data/app/models/spree_adyen/payment_sources/elo.rb +0 -19
  104. data/app/models/spree_adyen/payment_sources/givex.rb +0 -19
  105. data/app/models/spree_adyen/payment_sources/gopay_wallet.rb +0 -19
  106. data/app/models/spree_adyen/payment_sources/grabpay_paylater.rb +0 -19
  107. data/app/models/spree_adyen/payment_sources/hipercard.rb +0 -19
  108. data/app/models/spree_adyen/payment_sources/kakaopay.rb +0 -19
  109. data/app/models/spree_adyen/payment_sources/kcp_naverpay.rb +0 -19
  110. data/app/models/spree_adyen/store_decorator.rb +0 -17
  111. data/app/presenters/spree_adyen/address_presenter.rb +0 -21
  112. data/app/presenters/spree_adyen/cancel_payload_presenter.rb +0 -31
  113. data/app/presenters/spree_adyen/capture_payload_presenter.rb +0 -36
  114. data/app/presenters/spree_adyen/checkout_presenter.rb +0 -51
  115. data/app/presenters/spree_adyen/payment_sessions/request_payload_presenter.rb +0 -140
  116. data/app/presenters/spree_adyen/payment_setup_sessions/request_payload_presenter.rb +0 -81
  117. data/app/presenters/spree_adyen/payments/request_payload_presenter.rb +0 -85
  118. data/app/presenters/spree_adyen/refund_payload_presenter.rb +0 -38
  119. data/app/presenters/spree_adyen/webhook_payload_presenter.rb +0 -28
  120. data/app/presenters/spree_adyen/webhooks/credit_card_presenter.rb +0 -43
  121. data/app/services/spree_adyen/gateways/add_allowed_origin.rb +0 -36
  122. data/app/services/spree_adyen/gateways/configuration.rb +0 -41
  123. data/app/services/spree_adyen/gateways/configure.rb +0 -60
  124. data/app/services/spree_adyen/payment_sessions/find_or_create.rb +0 -51
  125. data/app/services/spree_adyen/payment_sessions/process_with_result.rb +0 -49
  126. data/app/services/spree_adyen/payment_setup_sessions/create_source_from_result.rb +0 -71
  127. data/app/services/spree_adyen/payment_setup_sessions/handle_authorisation.rb +0 -48
  128. data/app/services/spree_adyen/webhooks/actions/create_source.rb +0 -112
  129. data/app/services/spree_adyen/webhooks/actions/find_or_create_credit_card.rb +0 -33
  130. data/app/services/spree_adyen/webhooks/event.rb +0 -104
  131. data/app/services/spree_adyen/webhooks/event_processors/authorisation_event_processor.rb +0 -69
  132. data/app/services/spree_adyen/webhooks/event_processors/cancellation_event_processor.rb +0 -49
  133. data/app/services/spree_adyen/webhooks/event_processors/capture_event_processor.rb +0 -48
  134. data/app/services/spree_adyen/webhooks/handle_event.rb +0 -43
  135. data/app/services/spree_adyen/webhooks/standard_hmac_validator.rb +0 -37
  136. data/app/views/layouts/spree_adyen/default.html.erb +0 -14
  137. data/app/views/spree/admin/payment_methods/configuration_guides/_spree_adyen.html.erb +0 -14
  138. data/app/views/spree/admin/payment_methods/custom_form_fields/_spree_adyen.html.erb +0 -18
  139. data/app/views/spree/admin/payment_methods/descriptions/_spree_adyen.html.erb +0 -12
  140. data/app/views/spree/admin/payments/source_forms/_spree_adyen.html.erb +0 -7
  141. data/app/views/spree/checkout/payment/_spree_adyen.html.erb +0 -40
  142. data/app/views/spree_adyen/_drop_in.html.erb +0 -12
  143. data/app/views/spree_adyen/_head.html.erb +0 -2
  144. data/app/views/spree_adyen/payment_sessions/redirect.html.erb +0 -5
  145. data/config/importmap.rb +0 -7
  146. data/config/initializers/spree.rb +0 -34
  147. data/config/initializers/spree_permitted_attributes.rb +0 -5
  148. data/config/routes.rb +0 -35
  149. data/db/migrate/20250630150000_setup_spree_adyen_models.rb +0 -17
  150. data/db/migrate/20250811140113_add_channel_to_adyen_payment_sessions.rb +0 -10
  151. data/db/migrate/20250813152608_add_return_url_to_spree_adyen_payment_sessions.rb +0 -15
  152. data/lib/spree_adyen/configuration.rb +0 -42
  153. data/lib/spree_adyen/testing_support/factories/payment_setup_session_factory.rb +0 -15
  154. data/lib/spree_adyen/version.rb +0 -7
  155. data/lib/spree_api_v2/spree/api/v2/storefront/adyen/base_controller.rb +0 -21
  156. data/lib/spree_api_v2/spree/api/v2/storefront/adyen/payment_sessions_controller.rb +0 -72
  157. data/lib/spree_api_v2/spree_adyen/api/v2/storefront/payment_session_serializer.rb +0 -21
  158. data/vendor/javascript/@adyen--adyen-web.js +0 -4
  159. data/vendor/stylesheets/adyen.css +0 -106
@@ -0,0 +1,153 @@
1
+ module SpreeAdyen
2
+ # The body of POST /sessions: a checkout session for a cart, or a setup
3
+ # session that saves a card without a purchase.
4
+ class SessionPresenter
5
+ CHANNELS = %w[Web iOS Android].freeze
6
+ # Each native platform hides the other's wallet.
7
+ BLOCKED_WALLETS = { 'iOS' => %w[googlepay], 'Android' => %w[applepay] }.freeze
8
+ SESSION_LIFETIME = 1.hour
9
+
10
+ # @param payment_method [SpreeAdyen::Gateway]
11
+ # @param return_url [String] already checked against the store's allowed origins
12
+ # @param owner [Spree::Cart, Spree::Order, nil] the cart paid for; nil for a setup session
13
+ # @param amount [BigDecimal, nil] the session's amount; nil for a setup session
14
+ # @param customer [Spree::Customer, nil] the customer a setup session saves a card for
15
+ # @param channel [String, nil] Web, iOS or Android
16
+ def initialize(payment_method:, return_url:, owner: nil, amount: nil, customer: nil, channel: nil)
17
+ @payment_method = payment_method
18
+ @return_url = return_url
19
+ @owner = owner
20
+ @amount = amount
21
+ @customer = customer || owner&.customer
22
+ @channel = CHANNELS.include?(channel) ? channel : 'Web'
23
+ end
24
+
25
+ # @return [Hash]
26
+ def to_h
27
+ setup? ? setup_session : checkout_session
28
+ end
29
+
30
+ # @return [String] unique per attempt, so every session for a cart is found
31
+ # together in Adyen under the cart's id
32
+ def reference
33
+ @reference ||= if setup?
34
+ "#{customer.prefixed_id}-setup-#{SecureRandom.hex(4)}"
35
+ else
36
+ "#{owner.prefixed_id}-#{previous_sessions_count + 1}"
37
+ end
38
+ end
39
+
40
+ # Capture on dispatch or by staff asks Adyen to hold the money.
41
+ def manual_capture?
42
+ !setup? && !payment_method.capture_at_checkout?
43
+ end
44
+
45
+ attr_reader :channel
46
+
47
+ private
48
+
49
+ attr_reader :payment_method, :return_url, :owner, :amount, :customer
50
+
51
+ def setup?
52
+ owner.nil?
53
+ end
54
+
55
+ def checkout_session
56
+ body = common.merge(
57
+ amount: SpreeAdyen::Amounts.to_adyen_amount(amount, owner.currency),
58
+ reference: reference,
59
+ merchantOrderReference: owner.prefixed_id,
60
+ countryCode: country_code,
61
+ shopperName: shopper_name,
62
+ shopperEmail: owner.email.presence || customer&.email,
63
+ payable: false
64
+ ).compact
65
+ body.merge!(saved_cards(mode: 'askForConsent')) if customer.present?
66
+ body[:additionalData] = { manualCapture: 'true' } if manual_capture?
67
+ items = line_items
68
+ body[:lineItems] = items if items.present?
69
+ body
70
+ end
71
+
72
+ def setup_session
73
+ common.merge(
74
+ amount: { value: 0, currency: store.default_market&.currency.to_s.upcase.presence || 'USD' },
75
+ reference: reference,
76
+ shopperEmail: customer.email,
77
+ countryCode: store.default_market&.default_country&.iso
78
+ ).compact.merge(saved_cards(mode: 'enabled'))
79
+ end
80
+
81
+ def common
82
+ body = {
83
+ merchantAccount: payment_method.preferred_merchant_account,
84
+ returnUrl: return_url,
85
+ channel: channel,
86
+ expiresAt: SESSION_LIFETIME.from_now.iso8601
87
+ }
88
+ body[:blockedPaymentMethods] = BLOCKED_WALLETS[channel] if BLOCKED_WALLETS.key?(channel)
89
+ body.merge(SpreeAdyen::ApplicationInfoPresenter.new.to_h)
90
+ end
91
+
92
+ # Saved under the 5.x shopper reference, so cards saved then still show.
93
+ def saved_cards(mode:)
94
+ {
95
+ shopperReference: "customer_#{customer.id}",
96
+ storePaymentMethodMode: mode,
97
+ recurringProcessingModel: 'CardOnFile',
98
+ shopperInteraction: 'Ecommerce'
99
+ }
100
+ end
101
+
102
+ def store
103
+ payment_method.store
104
+ end
105
+
106
+ def previous_sessions_count
107
+ Spree::PaymentSession.with_deleted.where(payment_method: payment_method).
108
+ where(owner.is_a?(Spree::Cart) ? { cart_id: owner.id } : { order_id: owner.id }).count
109
+ end
110
+
111
+ def address
112
+ owner.bill_address || owner.ship_address
113
+ end
114
+
115
+ def country_code
116
+ address&.country_code.presence || store.default_market&.default_country&.iso
117
+ end
118
+
119
+ def shopper_name
120
+ first_name = address&.firstname.presence || customer&.first_name
121
+ last_name = address&.lastname.presence || customer&.last_name
122
+ return if first_name.blank? && last_name.blank?
123
+
124
+ { firstName: first_name, lastName: last_name }.compact
125
+ end
126
+
127
+ # Buy-now-pay-later methods need lines that add up to the amount. Sent only
128
+ # when they do; otherwise Adyen refuses those methods for this cart rather
129
+ # than for a figure that does not match.
130
+ def line_items
131
+ lines = owner.line_items.includes(variant: :product).map do |line_item|
132
+ { id: line_item.prefixed_id, description: line_item.name, sku: line_item.sku.presence,
133
+ quantity: line_item.quantity, amountIncludingTax: line_item.price }.compact
134
+ end
135
+ discounts = owner.adjustment_total - owner.fee_total - owner.additional_tax_total
136
+ {
137
+ 'delivery' => owner.delivery_total,
138
+ 'fees' => owner.fee_total,
139
+ 'tax' => owner.additional_tax_total,
140
+ 'discount' => discounts,
141
+ 'store_credit' => -owner.total_applied_store_credit
142
+ }.each do |kind, value|
143
+ lines << { id: kind, description: kind.humanize, quantity: 1, amountIncludingTax: value } unless value.zero?
144
+ end
145
+
146
+ lines.each { |line| line[:amountIncludingTax] = SpreeAdyen::Amounts.to_adyen(line[:amountIncludingTax], owner.currency) }
147
+ sum = lines.sum { |line| line[:amountIncludingTax] * line[:quantity] }
148
+ sum == SpreeAdyen::Amounts.to_adyen(amount, owner.currency) ? lines : nil
149
+ rescue SpreeAdyen::Amounts::UnsupportedAmount
150
+ nil
151
+ end
152
+ end
153
+ end
@@ -0,0 +1,121 @@
1
+ module SpreeAdyen
2
+ # Puts a payment method's credential and webhook in the state the gem needs:
3
+ # a client key, the store's allowed origins, and a merchant-level webhook on
4
+ # the method's own URL, signed with a key Spree holds.
5
+ #
6
+ # Safe to run again: everything already in place is found and kept.
7
+ class Configure
8
+ # @param gateway [SpreeAdyen::Gateway]
9
+ def self.call(gateway)
10
+ new(gateway).call
11
+ end
12
+
13
+ def initialize(gateway)
14
+ @gateway = gateway
15
+ end
16
+
17
+ # @return [SpreeAdyen::Gateway]
18
+ def call
19
+ credential = gateway.adyen_call(:read_credential) { |client| client.management.my_api_credential_api.get_api_credential_details }
20
+ client_key = credential['clientKey'].presence || generate_client_key
21
+ add_allowed_origins(credential)
22
+ webhook_id = put_webhook
23
+
24
+ if gateway.preferred_hmac_key.blank? || webhook_id != gateway.preferred_webhook_id
25
+ gateway.preferred_previous_hmac_key = gateway.preferred_hmac_key if gateway.preferred_hmac_key.present?
26
+ gateway.preferred_hmac_key = generate_hmac_key(webhook_id)
27
+ end
28
+ gateway.preferred_client_key = client_key
29
+ gateway.preferred_webhook_id = webhook_id
30
+ gateway.save!
31
+ gateway
32
+ end
33
+
34
+ private
35
+
36
+ attr_reader :gateway
37
+
38
+ def merchant_account
39
+ gateway.preferred_merchant_account
40
+ end
41
+
42
+ # Never replaced: a new key retires the old one after 24 hours, and other
43
+ # stores sharing the credential would stop loading Drop-in.
44
+ def generate_client_key
45
+ gateway.adyen_call(:generate_client_key) { |client| client.management.my_api_credential_api.generate_client_key }['clientKey']
46
+ end
47
+
48
+ # Drop-in loads only on the credential's allowed origins. Loopback ones
49
+ # are left out: Adyen refuses them.
50
+ def add_allowed_origins(credential)
51
+ listed = Array(credential['allowedOrigins']).pluck('domain')
52
+
53
+ gateway.store.allowed_origins.reject(&:loopback?).map(&:origin).each do |origin|
54
+ next if listed.include?(origin)
55
+
56
+ begin
57
+ gateway.adyen_call(:add_allowed_origin) do |client|
58
+ client.management.my_api_credential_api.add_allowed_origin({ domain: origin })
59
+ end
60
+ rescue Spree::Core::GatewayError => e
61
+ raise unless e.message.match?(/already exists/i)
62
+ end
63
+ end
64
+ end
65
+
66
+ # A webhook this method created before, pointing elsewhere (5.x's
67
+ # /adyen/webhooks), is moved in place: it keeps its HMAC key and delivers
68
+ # what Adyen queued for it. Otherwise the merchant's standard webhook for
69
+ # the URL is found, or one is created. Either way it is left active, since
70
+ # requested payments wait on what it delivers.
71
+ #
72
+ # @return [String] the webhook id
73
+ def put_webhook
74
+ stored = stored_webhook
75
+ if stored
76
+ update_webhook(stored) if stored['url'] != gateway.webhook_url || !stored['active']
77
+ return stored['id']
78
+ end
79
+
80
+ found = Array(list_webhooks['data']).find { |webhook| webhook['type'] == 'standard' && webhook['url'] == gateway.webhook_url }
81
+ if found
82
+ update_webhook(found) unless found['active']
83
+ return found['id']
84
+ end
85
+
86
+ gateway.adyen_call(:create_webhook) do |client|
87
+ client.management.webhooks_merchant_level_api.set_up_webhook(
88
+ { type: 'standard', url: gateway.webhook_url, active: true, communicationFormat: 'json' }, merchant_account
89
+ )
90
+ end['id']
91
+ end
92
+
93
+ def stored_webhook
94
+ return if gateway.preferred_webhook_id.blank?
95
+
96
+ gateway.adyen_call(:read_webhook) do |client|
97
+ client.management.webhooks_merchant_level_api.get_webhook(merchant_account, gateway.preferred_webhook_id)
98
+ end
99
+ rescue Spree::Core::GatewayError => e
100
+ raise unless e.message.match?(/not found/i)
101
+ end
102
+
103
+ def update_webhook(webhook)
104
+ gateway.adyen_call(:update_webhook) do |client|
105
+ client.management.webhooks_merchant_level_api.update_webhook({ url: gateway.webhook_url, active: true }, merchant_account, webhook['id'])
106
+ end
107
+ end
108
+
109
+ def list_webhooks
110
+ gateway.adyen_call(:list_webhooks) do |client|
111
+ client.management.webhooks_merchant_level_api.list_all_webhooks(merchant_account, query_params: { pageSize: 100 })
112
+ end
113
+ end
114
+
115
+ def generate_hmac_key(webhook_id)
116
+ gateway.adyen_call(:generate_hmac_key) do |client|
117
+ client.management.webhooks_merchant_level_api.generate_hmac_key(merchant_account, webhook_id)
118
+ end['hmacKey']
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,41 @@
1
+ module SpreeAdyen
2
+ # Captures, once the order is placed, the payments Adyen holds for a capture
3
+ # request (Klarna, Riverty, Affirm) on a method that captures at checkout:
4
+ # Adyen keeps those authorised whatever the account's capture delay says, so
5
+ # Spree asks, and the payment waits for Adyen's CAPTURE as any capture does.
6
+ class CaptureHeldPaymentsSubscriber < Spree::Subscriber
7
+ subscribes_to 'order.placed'
8
+
9
+ def handle(event)
10
+ order = Spree::Order.find_by_prefix_id(event.payload['id'])
11
+ return if order.nil?
12
+
13
+ order.settlement_payments.with_status(:pending).includes(:payment_method).find_each do |payment|
14
+ next unless held_for_capture?(payment)
15
+
16
+ # A payment already claimed by another capture is refused by the
17
+ # workflow's own claim, so a redelivered event captures nothing twice.
18
+ result = Spree.payment_capture_workflow.call(payment: payment)
19
+ report_failed_capture(payment, result) if result.failure?
20
+ end
21
+ end
22
+
23
+ private
24
+
25
+ # A refused capture leaves the payment failed, which the order's payment
26
+ # menu captures again, so the report tells someone it needs doing.
27
+ def report_failed_capture(payment, result)
28
+ Rails.error.report(
29
+ Spree::Core::GatewayError.new(result.error.to_s),
30
+ handled: true,
31
+ context: { payment_id: payment.prefixed_id, order_id: payment.order&.prefixed_id }
32
+ )
33
+ end
34
+
35
+ def held_for_capture?(payment)
36
+ payment.payment_method.is_a?(SpreeAdyen::Gateway) &&
37
+ payment.payment_method.capture_at_checkout? &&
38
+ SpreeAdyen::Variants.held_for_capture?(payment.metadata['adyen_variant'])
39
+ end
40
+ end
41
+ end
@@ -2,10 +2,25 @@
2
2
  en:
3
3
  spree:
4
4
  adyen:
5
+ errors:
6
+ invalid_api_key: Adyen rejected this API key. Check it in your Customer Area under Developers, API credentials.
7
+ merchant_account_unreachable: This API key cannot reach the merchant account %{merchant_account}. Check the account name, or use a credential that has access to it.
8
+ no_answer: 'Adyen did not answer: %{message}'
9
+ payment_not_found: No Adyen payment matches this session.
10
+ psp_reference_missing: Adyen cannot be asked to capture, cancel or refund this payment without its PSP reference, which Spree never recorded. Handle it in your Adyen Customer Area.
11
+ refused: 'Adyen refused the request: %{message}'
12
+ role_missing: This API key lacks a role the integration needs. Give it API credentials read and write, and Webhooks read and write, in your Customer Area.
13
+ session_required: Adyen payments are taken through a payment session.
5
14
  payment_session_errors:
6
- canceled: Payment canceled
7
- expired: Payment has been expired. Try again.
8
- refused: Payment refused
9
- payment_states:
10
- capture_pending: Capture Pending
11
- void_pending: Void Pending
15
+ already_paid: This cart has already been paid through Adyen.
16
+ amount_locked: This Adyen session can no longer change its amount. Create a new payment session.
17
+ amount_mismatch: Adyen reports a payment of %{paid} for a session of %{expected}, so it was not recorded.
18
+ amount_stale: The amount due has changed since this Adyen session was set up. Update its amount or create a new payment session.
19
+ not_open: This Adyen payment session can no longer be paid.
20
+ payments_count: Adyen reports %{count} payments for this session, so none was recorded. Check the session in your Adyen Customer Area.
21
+ reference_mismatch: This Adyen payment belongs to another session.
22
+ refused: 'Adyen did not accept the payment: %{reason}'
23
+ result_missing: Adyen's session result or redirect result is required to complete the session.
24
+ return_url_not_allowed: The return URL must be on one of the store's allowed origins.
25
+ token_missing: Adyen did not return a stored card for this session, so no card was saved.
26
+ zero_amount: Payment session amount must be greater than zero
@@ -1,19 +1,19 @@
1
+ require 'rails/generators'
2
+ require 'spree/core'
3
+
1
4
  module SpreeAdyen
2
5
  module Generators
6
+ # Kept as a no-op so `rake test_app` and any existing
7
+ # `rails g spree_adyen:install` invocations keep working. The gateway
8
+ # registers itself from the engine and stores its configuration in payment
9
+ # method preferences, so it owns no tables and has nothing to copy into the
10
+ # host app.
3
11
  class InstallGenerator < Rails::Generators::Base
4
- class_option :migrate, type: :boolean, default: true
5
-
6
- def add_migrations
7
- run 'bundle exec rake railties:install:migrations FROM=spree_adyen'
8
- end
12
+ desc 'No-op. spree_adyen registers its gateway automatically and ships no migrations.'
9
13
 
10
- def run_migrations
11
- run_migrations = options[:migrate] || ['', 'y', 'Y'].include?(ask('Would you like to run the migrations now? [Y/n]'))
12
- if run_migrations
13
- run 'bin/rails db:migrate'
14
- else
15
- puts 'Skipping rails db:migrate, don\'t forget to run it!'
16
- end
14
+ def notify_nothing_to_install
15
+ say 'spree_adyen registers its gateway automatically — nothing to install. ' \
16
+ 'Add an Adyen payment method in the admin to enter your API key and merchant account.'
17
17
  end
18
18
  end
19
19
  end
@@ -1,79 +1,15 @@
1
+ require 'rails/engine'
2
+
1
3
  module SpreeAdyen
2
4
  class Engine < Rails::Engine
3
- require 'spree/core'
4
5
  isolate_namespace Spree
5
6
  engine_name 'spree_adyen'
6
7
 
7
- Environment = Struct.new(:event_handlers, :events, :hmac_validators)
8
-
9
- config.eager_load_paths += %W(#{config.root}/app/services)
10
-
11
- # Only load API v2 controllers and serializers when spree_legacy_api_v2 gem is available
12
- if defined?(SpreeLegacyApiV2::Engine)
13
- config.autoload_paths << root.join('lib', 'spree_api_v2')
14
- config.eager_load_paths << root.join('lib', 'spree_api_v2')
15
- end
16
-
17
- config.generators do |g| # use rspec for tests
18
- g.test_framework :rspec
19
- end
20
-
21
- initializer 'spree_adyen.environment', before: :load_config_initializers do |app|
22
- app.config.spree_adyen = Environment.new
23
- app.config.spree_adyen.event_handlers = {}
24
- app.config.spree_adyen.events = {}
25
- app.config.spree_adyen.hmac_validators = {}
26
- SpreeAdyen::Config = SpreeAdyen::Configuration.new
27
- end
28
-
8
+ # Core assigns the payment method registry in its own after_initialize, so
9
+ # appending has to happen in a later one — engine callbacks run in load order.
29
10
  config.after_initialize do
30
- Rails.application.config.spree_adyen.event_handlers.merge!(
31
- 'AUTHORISATION' => SpreeAdyen::Webhooks::ProcessAuthorisationEventJob,
32
- 'CAPTURE' => SpreeAdyen::Webhooks::ProcessCaptureEventJob,
33
- 'CANCELLATION' => SpreeAdyen::Webhooks::ProcessCancellationEventJob
34
- )
35
-
36
- Rails.application.config.spree_adyen.events.merge!(
37
- 'AUTHORISATION' => SpreeAdyen::Webhooks::Event,
38
- 'CAPTURE' => SpreeAdyen::Webhooks::Event,
39
- 'CANCELLATION' => SpreeAdyen::Webhooks::Event
40
- )
41
-
42
- Rails.application.config.spree_adyen.hmac_validators.merge!(
43
- 'AUTHORISATION' => SpreeAdyen::Webhooks::StandardHmacValidator,
44
- 'CAPTURE' => SpreeAdyen::Webhooks::StandardHmacValidator,
45
- 'CANCELLATION' => SpreeAdyen::Webhooks::StandardHmacValidator
46
- )
47
- end
48
-
49
- initializer 'spree_adyen.assets' do |app|
50
- if app.config.respond_to?(:assets)
51
- app.config.assets.paths << root.join('app/javascript')
52
- app.config.assets.paths << root.join('vendor/javascript')
53
- app.config.assets.paths << root.join('vendor/stylesheets')
54
- app.config.assets.precompile += %w[spree_adyen_manifest]
55
- end
56
- end
57
-
58
- initializer 'spree_adyen.importmap', before: 'importmap' do |app|
59
- if app.config.respond_to?(:importmap)
60
- app.config.importmap.paths << root.join('config/importmap.rb')
61
- # https://github.com/rails/importmap-rails?tab=readme-ov-file#sweeping-the-cache-in-development-and-test
62
- app.config.importmap.cache_sweepers << root.join('app/javascript')
63
- end
11
+ Rails.application.config.spree.payment_methods << SpreeAdyen::Gateway
12
+ Spree.subscribers << SpreeAdyen::CaptureHeldPaymentsSubscriber
64
13
  end
65
-
66
- def self.activate
67
- glob_paths = [File.join(File.dirname(__FILE__), '../../app/**/*_decorator*.rb')]
68
- glob_paths << File.join(File.dirname(__FILE__), '../../lib/spree_api_v2/**/*_decorator*.rb') if defined?(SpreeLegacyApiV2::Engine)
69
-
70
- glob_paths.each do |glob_path|
71
- Dir.glob(glob_path) do |c|
72
- Rails.configuration.cache_classes ? require(c) : load(c)
73
- end
74
- end
75
- end
76
-
77
- config.to_prepare(&method(:activate).to_proc)
78
14
  end
79
15
  end
@@ -1,3 +1 @@
1
- Dir["#{File.dirname(__FILE__)}/testing_support/factories/**"].each do |f|
2
- load File.expand_path(f)
3
- end
1
+ Dir["#{File.dirname(__FILE__)}/testing_support/factories/**/*.rb"].each { |f| load File.expand_path(f) }
@@ -1,29 +1,22 @@
1
1
  FactoryBot.define do
2
- factory :adyen_gateway, parent: :payment_method, class: SpreeAdyen::Gateway do
3
- name { 'Adyen' }
2
+ factory :adyen_gateway, parent: :payment_method, class: 'SpreeAdyen::Gateway' do
3
+ sequence(:name) { |n| "Adyen #{n}" }
4
4
  type { 'SpreeAdyen::Gateway' }
5
5
 
6
- skip_auto_configuration { true }
7
- skip_api_key_validation { true }
8
-
9
6
  preferences do
10
7
  {
11
- api_key: 'secret',
12
- merchant_account: 'SpreeCommerceECOM',
13
- hmac_key: 'secret123',
14
- client_key: 'client123',
15
- webhook_id: 'webhook123'
8
+ api_key: ENV.fetch('ADYEN_API_KEY', 'adyen_api_key_test'),
9
+ merchant_account: ENV.fetch('ADYEN_MERCHANT_ACCOUNT', 'SpreeTestECOM'),
10
+ test_mode: true
16
11
  }
17
12
  end
18
13
 
19
- trait :with_apple_domain_association_file do
20
- transient do
21
- apple_domain_association_file_path do
22
- File.join(SpreeAdyen::Engine.root, 'spec', 'fixtures', 'files', 'apple-domain-association-file.txt')
23
- end
14
+ trait :configured do
15
+ after(:build) do |gateway|
16
+ gateway.preferred_client_key = 'test_CLIENTKEY'
17
+ gateway.preferred_hmac_key = '44782DEF547AAA06C910C43932B1EB0C71FC68D9D0C057550C48EC2ACF6BA056'
18
+ gateway.preferred_webhook_id = 'WBHK00000000000000000000'
24
19
  end
25
-
26
- apple_developer_merchantid_domain_association { Rack::Test::UploadedFile.new(apple_domain_association_file_path) }
27
20
  end
28
21
  end
29
22
  end
@@ -1,40 +1,24 @@
1
1
  FactoryBot.define do
2
- factory :adyen_payment_session, class: SpreeAdyen::PaymentSession do
3
- sequence(:adyen_id) { |n| "pi_#{n}" }
4
- adyen_data { 'a very long string' }
5
- amount { order.total_minus_store_credits }
6
- currency { order.currency }
7
- channel { 'Web' }
8
- status { 'initial' }
9
- expires_at { 1.hour.from_now }
10
- payment_method { create(:adyen_gateway) }
11
-
12
- association :user
13
- association :order, factory: :order_with_line_items
14
-
15
- trait :expired do
16
- expires_at { 1.hour.ago }
17
- skip_expiration_date_validation { true }
18
- end
19
-
20
- trait :initial do
21
- status { 'initial' }
22
- end
23
-
24
- trait :pending do
25
- status { 'pending' }
2
+ factory :adyen_payment_session, class: 'Spree::PaymentSessions::Adyen' do
3
+ transient do
4
+ owner { create(:order_with_line_items) }
26
5
  end
27
6
 
28
- trait :completed do
29
- status { 'completed' }
30
- end
31
-
32
- trait :outdated do
33
- status { 'outdated' }
34
- end
7
+ cart { owner if owner.is_a?(Spree::Cart) }
8
+ order { owner unless owner.is_a?(Spree::Cart) }
9
+ payment_method { create(:adyen_gateway, :configured, store: owner.store) }
10
+ amount { owner.total }
11
+ currency { owner.currency }
12
+ status { 'pending' }
13
+ external_id { "CS#{SecureRandom.hex(8).upcase}" }
14
+ external_data { { 'session_data' => 'Ab02b4c0!SESSIONDATA', 'manual_capture' => false, 'payable' => false } }
15
+ end
35
16
 
36
- trait :canceled do
37
- status { 'canceled' }
38
- end
17
+ factory :adyen_payment_setup_session, class: 'Spree::PaymentSetupSessions::Adyen' do
18
+ customer { create(:customer) }
19
+ payment_method { create(:adyen_gateway, :configured) }
20
+ status { 'pending' }
21
+ external_id { "CS#{SecureRandom.hex(8).upcase}" }
22
+ external_data { { 'session_data' => 'Ab02b4c0!SESSIONDATA' } }
39
23
  end
40
24
  end
data/lib/spree_adyen.rb CHANGED
@@ -1,39 +1,14 @@
1
+ require 'adyen-ruby-api-library'
1
2
  require 'spree_core'
2
3
  require 'spree_adyen/engine'
3
- require 'spree_adyen/version'
4
- require 'spree_adyen/configuration'
5
- require 'adyen-ruby-api-library'
6
4
 
7
5
  module SpreeAdyen
6
+ # Background queue for the gem's jobs. Defaults to Spree's default queue.
8
7
  def self.queue
9
- 'default'
10
- end
11
-
12
- def self.version
13
- VERSION
14
- end
15
-
16
- def self.event_handlers
17
- Rails.application.config.spree_adyen.event_handlers
18
- end
19
-
20
- def self.event_handlers=(value)
21
- Rails.application.config.spree_adyen.event_handlers = value
22
- end
23
-
24
- def self.events
25
- Rails.application.config.spree_adyen.events
26
- end
27
-
28
- def self.events=(value)
29
- Rails.application.config.spree_adyen.events = value
30
- end
31
-
32
- def self.hmac_validators
33
- Rails.application.config.spree_adyen.hmac_validators
8
+ @queue ||= Spree.queues.default
34
9
  end
35
10
 
36
- def self.hmac_validators=(value)
37
- Rails.application.config.spree_adyen.hmac_validators = value
11
+ class << self
12
+ attr_writer :queue
38
13
  end
39
14
  end
@@ -0,0 +1,39 @@
1
+ namespace :spree do
2
+ namespace :upgrade do
3
+ desc <<~DESC
4
+ Moves each Adyen payment method's previous HMAC key out of its metadata,
5
+ which the Admin API returns, into a secret preference, then configures
6
+ the method: client key, allowed origins and a webhook on the 6.0 URL. A
7
+ webhook 5.x left on /adyen/webhooks is moved in place.
8
+
9
+ Run once after upgrading to Spree 6.0. Safe to run again.
10
+ DESC
11
+ task configure_adyen_gateways: :environment do
12
+ configured = 0
13
+ failed = []
14
+
15
+ SpreeAdyen::Gateway.find_each do |payment_method|
16
+ # Locked as ConfigureJob locks it, since a save can run one meanwhile.
17
+ payment_method.with_lock do
18
+ previous_key = payment_method.metadata['previous_hmac_key']
19
+ if payment_method.metadata.key?('previous_hmac_key')
20
+ payment_method.preferred_previous_hmac_key = previous_key if previous_key.present? && payment_method.preferred_previous_hmac_key.blank?
21
+ payment_method.metadata = payment_method.metadata.except('previous_hmac_key')
22
+ payment_method.save!
23
+ end
24
+
25
+ SpreeAdyen::Configure.call(payment_method)
26
+ end
27
+ configured += 1
28
+ rescue StandardError => e
29
+ failed << { id: payment_method.id, error: e.message }
30
+ end
31
+
32
+ puts "Configured #{configured} Adyen payment method(s)."
33
+ next if failed.empty?
34
+
35
+ failed.each { |failure| puts " payment method #{failure[:id]}: #{failure[:error]}" }
36
+ abort 'Some Adyen payment methods could not be configured. Re-run after resolving the errors above.'
37
+ end
38
+ end
39
+ end