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
@@ -1,495 +1,371 @@
1
1
  module SpreeAdyen
2
+ # Adyen gateway built on the payment session API: Adyen's Sessions flow with
3
+ # Drop-in. A session payment's response code is always its Adyen session id,
4
+ # the key core links a session to its payment by; the PSP reference Adyen
5
+ # needs for a capture, cancel or refund lives in the payment's metadata.
2
6
  class Gateway < ::Spree::Gateway
3
- include PaymentSessions
4
- include PaymentSetupSessions
7
+ self.accepts_money_amounts = true
5
8
 
6
- CAPTURE_PSP_REFERENCE_METAFIELD_KEY = 'adyen.capture_psp_reference'.freeze
7
- CANCELLATION_PSP_REFERENCE_METAFIELD_KEY = 'adyen.cancellation_psp_reference'.freeze
8
-
9
- #
10
- # Attributes
11
- #
12
- attribute :skip_auto_configuration, :boolean, default: false
13
- attribute :skip_api_key_validation, :boolean, default: false
9
+ include SpreeAdyen::Gateway::PaymentSessions
10
+ include SpreeAdyen::Gateway::PaymentSetupSessions
11
+ include SpreeAdyen::Gateway::Webhooks
14
12
 
13
+ # Typed by the operator.
15
14
  preference :api_key, :password
16
15
  preference :merchant_account, :string
17
- preference :client_key, :password
18
- preference :hmac_key, :password
19
16
  preference :test_mode, :boolean, default: true
20
- preference :webhook_id, :string
17
+ # Adyen's live Checkout endpoints need it; the Management API does not.
21
18
  preference :live_url_prefix, :string
22
19
 
23
- has_one_attached :apple_developer_merchantid_domain_association, service: Spree.private_storage_service_name
24
-
25
- store_accessor :private_metadata, :previous_hmac_key
26
- #
27
- # Validations
28
- #
29
- validates :preferred_api_key, presence: true
20
+ # Written by configuration after save, never by an operator.
21
+ preference :client_key, :password, internal: true
22
+ preference :hmac_key, :password, internal: true
23
+ preference :previous_hmac_key, :password, internal: true
24
+ preference :webhook_id, :string, internal: true
25
+
26
+ # Explicit, instead of the library's 30 and 60 seconds; the read matches
27
+ # PayPal's gateway.
28
+ OPEN_TIMEOUT = 5
29
+ READ_TIMEOUT = 30
30
+ # A call that times out or gets a 5xx is retried this many times, with the
31
+ # same idempotency key.
32
+ RETRIES = 2
33
+ CONNECTION_ERRORS = [Faraday::TimeoutError, Faraday::ConnectionFailed].freeze
34
+ CREDENTIAL_PREFERENCES = %w[api_key merchant_account test_mode live_url_prefix].freeze
35
+
36
+ validates :preferred_api_key, :preferred_merchant_account, presence: true
30
37
  validates :preferred_live_url_prefix, presence: true, unless: :preferred_test_mode
31
- validate :validate_api_key, if: -> { preferred_api_key_changed? }, unless: :skip_api_key_validation
32
-
33
- #
34
- # Callbacks
35
- #
36
- after_commit :configure, if: :preferred_api_key_previously_changed?, unless: :skip_auto_configuration
37
-
38
- #
39
- # Associations
40
- #
41
- has_many :payment_sessions, class_name: 'SpreeAdyen::PaymentSession',
42
- foreign_key: 'payment_method_id',
43
- dependent: :delete_all,
44
- inverse_of: :payment_method
45
-
46
- # @param amount_in_cents [Integer] the amount in cents to capture
47
- # @param payment_source [Spree::CreditCard | Spree::PaymentSource]
48
- # @param gateway_options [Hash] this is an instance of Spree::Payment::GatewayOptions.to_hash
49
- def purchase(amount_in_cents, payment_source, gateway_options = {})
50
- handle_authorize_or_purchase(amount_in_cents, payment_source, gateway_options)
51
- end
52
-
53
- # @param amount_in_cents [Integer] the amount in cents to capture
54
- # @param payment_source [Spree::CreditCard | Spree::PaymentSource]
55
- # @param gateway_options [Hash] this is an instance of Spree::Payment::GatewayOptions.to_hash
56
- def authorize(amount_in_cents, payment_source, gateway_options = {})
57
- handle_authorize_or_purchase(amount_in_cents, payment_source, gateway_options)
58
- end
59
-
60
- def handle_authorize_or_purchase(amount_in_cents, payment_source, gateway_options = {})
61
- payload = SpreeAdyen::Payments::RequestPayloadPresenter.new(
62
- source: payment_source,
63
- amount_in_cents: amount_in_cents,
64
- manual_capture: !auto_capture?,
65
- gateway_options: gateway_options
66
- ).to_h
67
-
68
- response = send_request do
69
- client.checkout.payments_api.payments(payload, headers: { 'Idempotency-Key' => SecureRandom.uuid })
70
- end
71
- response_body = response.response
38
+ validate :validate_credential, unless: -> { Rails.env.test? }, if: :credentials_changed?
39
+ after_commit :configure_async, on: %i[create update]
72
40
 
73
- if response.status.to_i == 200
74
- success(response_body.pspReference, response_body)
75
- else
76
- failure(response_body.slice('pspReference', 'message').values.join(' - '))
77
- end
41
+ def self.logo_url
42
+ 'https://spreecommerce.org/docs/images/integrations/logos/adyen.png'
78
43
  end
79
44
 
80
- def cancel(id, payment)
81
- transaction_id = id
82
- payment ||= Spree::Payment.find_by(response_code: id)
83
- if payment.completed?
84
- amount = payment.credit_allowed
85
- return success(transaction_id, {}) if amount.zero?
86
- # Don't create a refund if the payment is for a shipment, we will create a refund for the whole shipping cost instead
87
- return success(transaction_id, {}) if payment.respond_to?(:for_shipment?) && payment.for_shipment?
88
-
89
- refund = payment.refunds.create!(
90
- amount: amount,
91
- reason: Spree::RefundReason.order_canceled_reason,
92
- refunder_id: payment.order.canceler_id
93
- )
94
-
95
- # Spree::Refund#response has the response from the `credit` action
96
- # For the authorization ID we need to use the payment.response_code
97
- # Otherwise we'll overwrite the payment authorization with the refund ID
98
- success(transaction_id, refund.response.params)
99
- else
100
- payment.void!
101
- success(transaction_id, {})
102
- end
45
+ def self.docs_url
46
+ 'https://spreecommerce.org/docs/integrations/payments/adyen'
103
47
  end
104
48
 
105
- def credit(amount_in_cents, _source, payment_id, gateway_options = {})
106
- refund = gateway_options[:originator]
107
- payment = refund.present? ? refund.payment : Spree::Payment.find_by(response_code: payment_id)
108
-
109
- return failure("#{payment_id} - Payment not found") unless payment
110
-
111
- payload = SpreeAdyen::RefundPayloadPresenter.new(
112
- payment: payment,
113
- amount_in_cents: amount_in_cents,
114
- payment_method: self,
115
- currency: payment.currency,
116
- refund: refund
117
- ).to_h
118
-
119
- response = send_request do
120
- client.checkout.modifications_api.refund_captured_payment(payload, payment.transaction_id, headers: { 'Idempotency-Key' => SecureRandom.uuid })
121
- end
122
-
123
- if response.status.to_i == 201
124
- success(response.response['pspReference'], response)
125
- else
126
- failure(response.response.slice('pspReference', 'message').values.join(' - '))
127
- end
49
+ def provider_class
50
+ self.class
128
51
  end
129
52
 
130
- def request_capture(amount_in_cents, response_code, _gateway_options = {})
131
- payment = Spree::Payment.find_by(response_code: response_code)
132
-
133
- return failure("#{response_code} - Payment not found") if payment.blank?
134
- return failure("#{response_code} - Payment is already captured") if payment.completed?
135
-
136
- payload = SpreeAdyen::CapturePayloadPresenter.new(
137
- amount_in_cents: amount_in_cents,
138
- payment: payment,
139
- payment_method: self
140
- ).to_h
141
-
142
- response = send_request do
143
- client.checkout.modifications_api.capture_authorised_payment(
144
- payload,
145
- payment.response_code,
146
- headers: { 'Idempotency-Key' => SecureRandom.uuid }
147
- )
148
- end
149
-
150
- if response.status.to_i == 201
151
- success(response.response['paymentPspReference'], response)
152
- else
153
- failure(response.response.slice('paymentPspReference', 'message').values.join(' - '))
154
- end
53
+ def default_name
54
+ 'Adyen'
155
55
  end
156
56
 
157
- # This only checks if the capture was successful by checking the presence of the capture PSP reference
158
- # The actual capture is requested in #request_capture and handled in the SpreeAdyen::Webhooks::EventProcessors::CaptureEventProcessor
159
- def capture(amount_in_cents, response_code, _gateway_options = {})
160
- payment = Spree::Payment.find_by(response_code: response_code)
161
-
162
- return failure("#{response_code} - Payment not found") if payment.blank?
163
- return failure("#{response_code} - Payment is already captured") if payment.completed?
164
- return failure("#{response_code} - Capture PSP reference not found") unless payment.has_metafield?(CAPTURE_PSP_REFERENCE_METAFIELD_KEY)
165
-
166
- success(payment.response_code, {})
57
+ def method_type
58
+ 'spree_adyen'
167
59
  end
168
60
 
169
- def request_void(response_code, _source, _gateway_options)
170
- payment = Spree::Payment.find_by(response_code: response_code)
171
-
172
- return failure("#{response_code} - Payment not found") if payment.blank?
173
- return failure("#{response_code} - Payment is already void") if payment.void?
174
-
175
- payload = SpreeAdyen::CancelPayloadPresenter.new(
176
- payment: payment,
177
- payment_method: self
178
- ).to_h
179
-
180
- response = send_request do
181
- client.checkout.modifications_api.cancel_authorised_payment_by_psp_reference(
182
- payload,
183
- payment.response_code,
184
- headers: { 'Idempotency-Key' => SecureRandom.uuid }
185
- )
186
- end
187
-
188
- if response.status.to_i == 201
189
- success(response.response['paymentPspReference'], response)
190
- else
191
- failure(response.response.slice('paymentPspReference', 'message').values.join(' - '))
192
- end
61
+ def payment_icon_name
62
+ 'adyen'
193
63
  end
194
64
 
195
- # This only checks if the void was successful by checking the presence of the cancellation PSP reference
196
- # The actual void is requested in #request_void and handled in the SpreeAdyen::Webhooks::EventProcessors::CancellationEventProcessor
197
- def void(response_code, _source, _gateway_options)
198
- payment = Spree::Payment.find_by(response_code: response_code)
199
-
200
- return failure("#{response_code} - Payment not found") if payment.blank?
201
- return failure("#{response_code} - Payment is already void") if payment.void?
202
- return failure("#{response_code} - Cancellation PSP reference not found") unless payment.has_metafield?(CANCELLATION_PSP_REFERENCE_METAFIELD_KEY)
203
-
204
- success(payment.response_code, {})
65
+ def session_required?
66
+ true
205
67
  end
206
68
 
207
- def webhook_url
208
- store = stores.first
209
- return nil unless store
210
-
211
- if SpreeAdyen::Config[:use_legacy_webhook_handlers]
212
- "#{store.formatted_url}/adyen/webhooks"
213
- else
214
- "#{store.formatted_url}/api/v3/webhooks/payments/#{prefixed_id}"
215
- end
69
+ def payment_session_class
70
+ Spree::PaymentSessions::Adyen
216
71
  end
217
72
 
218
- def parse_webhook_event(raw_body, headers)
219
- payload = JSON.parse(raw_body).with_indifferent_access
220
- event = SpreeAdyen::Webhooks::Event.new(event_data: payload)
221
-
222
- # Verify HMAC signature
223
- webhook_request_item = payload.dig('notificationItems', 0, 'NotificationRequestItem') || {}
224
- unless valid_hmac?(webhook_request_item)
225
- raise Spree::PaymentMethod::WebhookSignatureError, 'Invalid HMAC signature'
226
- end
227
-
228
- return nil if event.session_id.blank?
73
+ def payment_setup_session_class
74
+ Spree::PaymentSetupSessions::Adyen
75
+ end
229
76
 
230
- # Setup sessions (zero-auth tokenization) are processed inline here — they don't
231
- # fit core's payment-session webhook dispatch shape and there is no order to complete.
232
- setup_session = Spree::PaymentSetupSessions::Adyen.find_by(payment_method: self, external_id: event.session_id)
233
- if setup_session
234
- SpreeAdyen::PaymentSetupSessions::HandleAuthorisation.new(setup_session: setup_session, event: event).call if event.code == 'AUTHORISATION'
235
- return nil
236
- end
77
+ # Cards are saved under the customer's shopper reference, and core passes
78
+ # the source to void and credit.
79
+ def payment_profiles_supported?
80
+ true
81
+ end
237
82
 
238
- payment_session = Spree::PaymentSessions::Adyen.find_by(payment_method: self, external_id: event.session_id)
239
- return nil unless payment_session
240
-
241
- case event.code
242
- when 'AUTHORISATION'
243
- action = event.success? ? :authorized : :failed
244
- { action: action, payment_session: payment_session, metadata: { adyen_event: event } }
245
- when 'CAPTURE'
246
- { action: :captured, payment_session: payment_session, metadata: { adyen_event: event } }
247
- when 'CANCELLATION'
248
- { action: :canceled, payment_session: payment_session, metadata: { adyen_event: event } }
249
- else
250
- nil
251
- end
83
+ # Not offered for a currency missing from Adyen's currency table.
84
+ def available_for_order?(order)
85
+ super && SpreeAdyen::Amounts.supported?(order.currency)
252
86
  end
253
87
 
254
- def provider_class
255
- self.class
88
+ # Adyen's Customer Area page for the payment's PSP reference.
89
+ def gateway_dashboard_payment_url(payment)
90
+ psp_reference = payment.metadata['adyen_psp_reference'].presence
91
+ return if psp_reference.nil?
92
+
93
+ "https://ca-#{environment}.adyen.com/ca/ca/accounts/showTx.shtml?pspReference=#{psp_reference}&txType=Payment"
256
94
  end
257
95
 
96
+ # @return [String] 'test' or 'live'
258
97
  def environment
259
- if preferred_test_mode
260
- :test
261
- else
262
- :live
263
- end
98
+ preferred_test_mode ? 'test' : 'live'
264
99
  end
265
100
 
266
- def create_profile(payment); end
101
+ # Called by core when a session-created payment moves on. Adyen already
102
+ # holds the authorisation, so this makes no call.
103
+ #
104
+ # @return [Spree::PaymentResponse] authorized by the session id
105
+ def authorize(_money, _source, gateway_options = {})
106
+ payment = payment_from_options(gateway_options)
107
+ raise Spree::Core::GatewayError, I18n.t('spree.adyen.errors.session_required') if payment&.payment_session.nil?
267
108
 
268
- def payment_session_result(payment_session_id, session_result)
269
- response = send_request do
270
- client.checkout.payments_api.get_result_of_payment_session(payment_session_id, query_params: { sessionResult: session_result })
271
- end
272
- response_body = response.response
109
+ success(payment.response_code)
110
+ end
273
111
 
274
- if response.status.to_i == 200
275
- success(response_body.id, response_body)
276
- else
277
- failure(response_body.slice('pspReference', 'message').values.join(' - '))
278
- end
112
+ # @see #authorize
113
+ def purchase(money, source, gateway_options = {})
114
+ authorize(money, source, gateway_options)
279
115
  end
280
116
 
281
- # Creates an Adyen session via the Adyen Sessions API.
282
- # Used internally by the v3 PaymentSessions module and by the legacy SpreeAdyen::PaymentSession model.
117
+ # Requests a capture of the payment's PSP reference. Adyen answers by
118
+ # webhook, so the payment waits until it does.
283
119
  #
284
- # @param amount [BigDecimal] the amount
285
- # @param order [Spree::Order] the order to create a session for
286
- # @param channel [String] the channel (Web, iOS, Android)
287
- # @param return_url [String] the return URL after redirect flow
288
- # @return [Spree::PaymentResponse] the response from the session creation
289
- def create_adyen_session(amount, order, channel, return_url)
290
- payload = SpreeAdyen::PaymentSessions::RequestPayloadPresenter.new(
291
- order: order,
292
- amount: amount,
293
- user: order.user,
294
- merchant_account: preferred_merchant_account,
295
- payment_method: self,
296
- channel: channel,
297
- return_url: return_url
298
- ).to_h
299
-
300
- response = send_request do
301
- client.checkout.payments_api.sessions(payload, headers: { 'Idempotency-Key' => SecureRandom.uuid })
120
+ # @param money [Spree::Money]
121
+ # @param session_id [String] the payment's response code
122
+ # @return [Spree::PaymentResponse] requested, with the capture's own PSP reference
123
+ def capture(money, session_id, _gateway_options = {})
124
+ payment = payment_for(session_id)
125
+ psp_reference = psp_reference!(payment)
126
+ body = { merchantAccount: preferred_merchant_account, amount: adyen_amount(money) }
127
+ result = money_moving_call(payment, 'capture', payment.capture_events.count) do |client, headers, reference|
128
+ client.checkout.modifications_api.capture_authorised_payment(body.merge(reference: reference), psp_reference, headers: headers)
302
129
  end
303
- response_body = response.response
304
130
 
305
- if response.status.to_i == 201
306
- success(response_body.id, response_body)
307
- else
308
- failure(response_body.slice('pspReference', 'message').values.join(' - '))
309
- end
131
+ success(session_id, requested: true, reference: result['pspReference'])
310
132
  end
311
133
 
312
- # @return [Boolean] whether payment profiles are supported
313
- # this is used by spree to determine whenever payment source must be passed to gateway methods
314
- def payment_profiles_supported?
315
- true
316
- end
134
+ # Requests a cancel of the payment's authorisation, recording the cancel's
135
+ # PSP reference so the next attempt gets a new idempotency key.
136
+ #
137
+ # @return [Spree::PaymentResponse] requested
138
+ def void(session_id, _source = nil, _gateway_options = {})
139
+ payment = payment_for(session_id)
140
+ psp_reference = psp_reference!(payment)
141
+ references = Array(payment.metadata['adyen_cancel_references'])
142
+ result = money_moving_call(payment, 'cancel', references.size) do |client, headers, reference|
143
+ client.checkout.modifications_api.cancel_authorised_payment_by_psp_reference(
144
+ { merchantAccount: preferred_merchant_account, reference: reference }, psp_reference, headers: headers
145
+ )
146
+ end
317
147
 
318
- def default_name
319
- 'Adyen'
148
+ payment.update_columns(metadata: payment.metadata.merge('adyen_cancel_references' => references + [result['pspReference']]))
149
+ success(session_id, requested: true)
320
150
  end
321
151
 
322
- def method_type
323
- 'spree_adyen'
324
- end
152
+ # Requests a refund of the payment's PSP reference, keyed on the refund
153
+ # rows the payment had before this one.
154
+ #
155
+ # @param options [Hash] carries the Spree::Refund as +originator+
156
+ # @return [Spree::PaymentResponse] requested, authorized by the refund's PSP reference
157
+ def credit(money, _source, session_id, options = {})
158
+ payment = payment_for(session_id)
159
+ refund = options[:originator]
160
+ earlier_refunds = refund.is_a?(Spree::Refund) ? payment.refunds.where(id: ...refund.id).count : payment.refunds.count
161
+ psp_reference = psp_reference!(payment)
162
+ body = { merchantAccount: preferred_merchant_account, amount: adyen_amount(money) }
163
+ result = money_moving_call(payment, 'refund', earlier_refunds) do |client, headers, reference|
164
+ client.checkout.modifications_api.refund_captured_payment(body.merge(reference: reference), psp_reference, headers: headers)
165
+ end
325
166
 
326
- def payment_icon_name
327
- 'adyen'
167
+ success(result['pspReference'], requested: true)
328
168
  end
329
169
 
330
- def description_partial_name
331
- 'spree_adyen'
332
- end
170
+ # A completed payment is refunded, unless the operator asked to keep the
171
+ # money; anything else is voided.
172
+ def cancel(session_id, payment = nil, refund: true)
173
+ return void(session_id) unless payment&.completed?
174
+ return success(session_id) unless refund
333
175
 
334
- def configuration_guide_partial_name
335
- 'spree_adyen'
336
- end
176
+ amount = payment.credit_allowed
177
+ return success(session_id) if amount.zero?
178
+ return success(session_id) if payment.respond_to?(:for_shipment?) && payment.for_shipment?
337
179
 
338
- def custom_form_fields_partial_name
339
- 'spree_adyen'
340
- end
341
-
342
- def gateway_dashboard_payment_url(payment)
343
- return if payment.transaction_id.blank?
180
+ # Store passed explicitly: cancellation runs from jobs and webhooks where
181
+ # Spree::Current.store is nil.
182
+ result = Spree.refund_create_workflow.call(
183
+ payment: payment,
184
+ reason: Spree::RefundReason.order_canceled_reason(payment.owner.store),
185
+ refunder: payment.order&.canceler
186
+ )
187
+ raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?
344
188
 
345
- "https://ca-#{environment}.adyen.com/ca/ca/accounts/showTx.shtml?pspReference=#{payment.transaction_id}&txType=Payment"
189
+ success(session_id, requested: true)
346
190
  end
347
191
 
348
- def reusable_sources(order)
349
- if order.completed?
350
- sources_by_order order
351
- elsif order.user.present?
352
- credit_cards.where(user_id: order.user_id)
353
- else
354
- []
355
- end
192
+ # A captured payment is refunded instead.
193
+ def can_void?(payment)
194
+ !payment.completed?
356
195
  end
357
196
 
358
- def get_api_credential_details
359
- response = client.management.my_api_credential_api.get_api_credential_details
360
-
361
- if response.status.to_i == 200
362
- success(response.response.id, response.response)
363
- else
364
- failure(response.response.message)
197
+ # What is wrong with the credential, in words the operator can act on, or
198
+ # nil when it reaches the merchant account with the roles the gem needs.
199
+ #
200
+ # @return [String, nil]
201
+ def credential_problem
202
+ merchants = adyen_call(:list_merchants) do |client|
203
+ client.management.account_merchant_level_api.list_merchant_accounts(query_params: { pageSize: 100 })
365
204
  end
366
- rescue Adyen::AuthenticationError, Adyen::PermissionError
367
- raise
368
- rescue Adyen::AdyenError => e
369
- failure(parse_adyen_error_response(e)['message'])
370
- end
371
-
372
- def add_allowed_origin(domain)
373
- response = client.management.my_api_credential_api.add_allowed_origin({ domain: domain })
374
-
375
- if response.status.to_i == 200
376
- success(response.response.id, response.response)
377
- else
378
- failure(response.response)
205
+ reachable = Array(merchants['data']).pluck('id')
206
+ unless reachable.include?(preferred_merchant_account)
207
+ return I18n.t('spree.adyen.errors.merchant_account_unreachable', merchant_account: preferred_merchant_account)
379
208
  end
380
- rescue Adyen::AdyenError => e
381
- failure(parse_adyen_error_response(e))
382
- end
383
209
 
384
- def set_up_webhook(url)
385
- payload = SpreeAdyen::WebhookPayloadPresenter.new(url).to_h
386
- response = client.management.webhooks_merchant_level_api.set_up_webhook(payload, preferred_merchant_account)
387
-
388
- if response.status.to_i == 200
389
- success(response.response.id, response.response)
390
- else
391
- failure(response.response)
210
+ adyen_call(:list_webhooks) do |client|
211
+ client.management.webhooks_merchant_level_api.list_all_webhooks(preferred_merchant_account, query_params: { pageSize: 1 })
392
212
  end
393
- rescue Adyen::AdyenError => e
394
- failure(parse_adyen_error_response(e)['message'])
213
+ nil
214
+ rescue CredentialRejected
215
+ I18n.t('spree.adyen.errors.invalid_api_key')
216
+ rescue RoleMissing
217
+ I18n.t('spree.adyen.errors.role_missing')
395
218
  end
396
219
 
397
- def test_webhook
398
- response = client.management.webhooks_merchant_level_api.test_webhook({ types: ['AUTHORISATION'] }, preferred_merchant_account,
399
- preferred_webhook_id)
220
+ # Adyen refused the API key.
221
+ class CredentialRejected < Spree::Core::GatewayError; end
222
+ # The API key lacks a role a call needs.
223
+ class RoleMissing < Spree::Core::GatewayError; end
400
224
 
401
- if response.status.to_i == 200 && response.response.dig('data', 0, 'status') == 'success'
402
- success(nil, response.response)
403
- else
404
- failure(response.response)
225
+ # Calls Adyen through the library, retrying a timeout or a 5xx with the same
226
+ # idempotency key. Logs status lines only: bodies carry names, emails and
227
+ # addresses.
228
+ #
229
+ # @param operation [Symbol] named in the log line
230
+ # @param money_moving [Boolean] a call still unanswered after its retries
231
+ # raises AmbiguousGatewayError, since Adyen may have acted on it
232
+ # @yieldparam client [Adyen::Client]
233
+ # @return [Hash] Adyen's answer, string keys
234
+ def adyen_call(operation, money_moving: false)
235
+ attempt = 0
236
+ begin
237
+ attempt += 1
238
+ result = yield(adyen_client)
239
+ log_status(operation, result.status)
240
+ result.response.to_h.deep_stringify_keys
241
+ rescue *CONNECTION_ERRORS, Adyen::ServerError => e
242
+ log_status(operation, e.is_a?(Adyen::ServerError) ? e.code : e.class.name.demodulize)
243
+ if attempt <= RETRIES
244
+ wait_before_retry(attempt)
245
+ retry
246
+ end
247
+
248
+ error_class = money_moving ? Spree::Core::AmbiguousGatewayError : Spree::Core::GatewayError
249
+ raise error_class, I18n.t('spree.adyen.errors.no_answer', message: e.message.to_s.truncate(200))
250
+ rescue Adyen::AdyenError => e
251
+ log_status(operation, e.code)
252
+ raise refusal(e)
405
253
  end
406
- rescue Adyen::AdyenError => e
407
- failure(parse_adyen_error_response(e)['message'])
408
254
  end
409
255
 
410
- def generate_hmac_key
411
- response = client.management.webhooks_merchant_level_api.generate_hmac_key(preferred_merchant_account, preferred_webhook_id)
256
+ private
412
257
 
413
- if response.status.to_i == 200
414
- success(response.response.hmacKey, response.response)
415
- else
416
- failure(response.response)
417
- end
418
- rescue Adyen::AdyenError => e
419
- failure(parse_adyen_error_response(e)['message'])
258
+ # Configured when the method is created and whenever the credential or the
259
+ # merchant account changes. Not when configuration itself stores what it wrote.
260
+ def configure_async
261
+ return unless previously_new_record? || CREDENTIAL_PREFERENCES.any? { |key| public_send(:"saved_change_to_preferred_#{key}?") }
262
+
263
+ SpreeAdyen::ConfigureJob.perform_later(id)
420
264
  end
421
265
 
422
- def generate_client_key
423
- response = client.management.my_api_credential_api.generate_client_key
266
+ def credentials_changed?
267
+ return false if preferred_api_key.blank? || preferred_merchant_account.blank?
424
268
 
425
- if response.status.to_i == 200
426
- success(response.response.clientKey, response.response)
427
- else
428
- failure(response.response.message)
429
- end
430
- rescue Adyen::AdyenError => e
431
- failure(parse_adyen_error_response(e)['message'])
269
+ new_record? || CREDENTIAL_PREFERENCES.any? { |key| public_send(:"preferred_#{key}_changed?") }
432
270
  end
433
271
 
434
- def apple_domain_association_file_content
435
- @apple_domain_association_file_content ||= apple_developer_merchantid_domain_association&.download
272
+ def validate_credential
273
+ problem = credential_problem
274
+ errors.add(:base, problem) if problem
275
+ rescue Spree::Core::GatewayError => e
276
+ errors.add(:base, e.message)
436
277
  end
437
278
 
438
- private
439
-
440
- def validate_api_key
441
- return if preferred_api_key.blank?
442
-
443
- get_api_credential_details
444
- rescue Adyen::AuthenticationError => e
445
- errors.add(:preferred_api_key, "is invalid. Response: #{e.msg}")
446
- rescue Adyen::PermissionError => e
447
- errors.add(:preferred_api_key, "has insufficient permissions. Add missing roles to API credential. Response: #{e.msg}")
448
- rescue Adyen::AdyenError => e
449
- errors.add(:preferred_api_key, "An error occurred. Response: #{e.msg}")
279
+ def adyen_client
280
+ Adyen::Client.new(
281
+ api_key: preferred_api_key,
282
+ env: preferred_test_mode ? :test : :live,
283
+ live_url_prefix: preferred_live_url_prefix.presence,
284
+ connection_options: Faraday::ConnectionOptions.new(
285
+ request: Faraday::RequestOptions.new(open_timeout: OPEN_TIMEOUT, timeout: READ_TIMEOUT)
286
+ )
287
+ )
450
288
  end
451
289
 
452
- def configure
453
- return if preferred_api_key.blank?
290
+ def wait_before_retry(attempt)
291
+ sleep(0.5 * (2**(attempt - 1)))
292
+ end
454
293
 
455
- SpreeAdyen::Gateways::Configure.new(self).call
294
+ def log_status(operation, status)
295
+ Rails.logger.info("[spree_adyen] #{operation} #{status}")
456
296
  end
457
297
 
458
- def client
459
- @client ||= Adyen::Client.new.tap do |client|
460
- client.api_key = preferred_api_key
461
- client.env = environment
462
- client.live_url_prefix = preferred_live_url_prefix if environment == :live
298
+ # Adyen's own error code and message, never the library's summary.
299
+ def refusal(error)
300
+ body = begin
301
+ error.response.is_a?(String) ? JSON.parse(error.response) : error.response.to_h
302
+ rescue JSON::ParserError
303
+ {}
304
+ end
305
+ message = body['message'].presence || body['detail'].presence || error.msg.to_s
306
+ code = body['errorCode'].presence
307
+ text = I18n.t('spree.adyen.errors.refused', message: [message, code && "(#{code})"].compact.join(' '))
308
+
309
+ case error
310
+ when Adyen::AuthenticationError then CredentialRejected.new(text)
311
+ when Adyen::PermissionError then RoleMissing.new(text)
312
+ else Spree::Core::GatewayError.new(text)
463
313
  end
464
314
  end
465
315
 
466
- def send_request
467
- yield
468
- rescue Adyen::AdyenError => e
469
- raise Spree::Core::GatewayError, e.msg
316
+ # The payment a session id names, among this method's own.
317
+ def payment_for(session_id)
318
+ # A payment core split off a partial capture has no session, and so no
319
+ # PSP reference to ask Adyen about.
320
+ raise Spree::Core::GatewayError, I18n.t('spree.adyen.errors.psp_reference_missing') if session_id.blank?
321
+
322
+ payments.find_by!(response_code: session_id)
323
+ rescue ActiveRecord::RecordNotFound
324
+ raise Spree::Core::GatewayError, I18n.t('spree.adyen.errors.payment_not_found')
470
325
  end
471
326
 
472
- def parse_adyen_error_response(error)
473
- JSON.parse(error.response)
474
- rescue JSON::ParserError, TypeError
475
- { 'message' => error.msg }
327
+ def payment_from_options(gateway_options)
328
+ prefixed_id = gateway_options[:payment_prefixed_id].presence
329
+ payments.find_by_prefix_id(prefixed_id) if prefixed_id
476
330
  end
477
331
 
478
- def valid_hmac?(webhook_request_item)
479
- hmac_keys = [preferred_hmac_key, previous_hmac_key].compact
480
- return false if hmac_keys.empty?
332
+ def psp_reference!(payment)
333
+ payment.metadata['adyen_psp_reference'].presence ||
334
+ raise(Spree::Core::GatewayError, I18n.t('spree.adyen.errors.psp_reference_missing'))
335
+ end
481
336
 
482
- hmac_keys.any? do |key|
483
- Adyen::Utils::HmacValidator.new.valid_webhook_hmac?(webhook_request_item, key)
484
- end
337
+ def adyen_amount(money)
338
+ SpreeAdyen::Amounts.to_adyen_amount(money.to_d, money.currency.iso_code)
485
339
  end
486
340
 
487
- def success(authorization, full_response)
488
- Spree::PaymentResponse.new(true, nil, full_response.as_json, authorization: authorization)
341
+ # A capture, cancel or refund keyed from Spree records, so the key repeats
342
+ # only while the previous attempt's outcome is unknown and stays under
343
+ # Adyen's 64 characters. Adyen answers a repeated key with its first answer
344
+ # for days, so an attempt it refused is counted on the payment: the next
345
+ # one gets a new key instead of the old refusal.
346
+ #
347
+ # The request's reference is the key behind the order number, so staff
348
+ # find Spree's requests in the Customer Area, as with 5.x.
349
+ #
350
+ # @param attempt [Integer] the records the earlier answered attempts left
351
+ # @yieldparam reference [String] for the request body's +reference+
352
+ def money_moving_call(payment, action, attempt)
353
+ refusals = payment.metadata.dig('adyen_refusals', action).to_i
354
+ key = "spree-#{payment.prefixed_id}-#{action}-#{attempt + refusals}"
355
+ reference = [payment.owner&.number, key].compact.join('-')
356
+ adyen_call(action.to_sym, money_moving: true) { |client| yield(client, { 'Idempotency-Key' => key }, reference) }
357
+ rescue Spree::Core::AmbiguousGatewayError
358
+ raise
359
+ rescue Spree::Core::GatewayError
360
+ counted = (payment.metadata['adyen_refusals'] || {}).merge(action => refusals + 1)
361
+ payment.update_columns(metadata: payment.metadata.merge('adyen_refusals' => counted))
362
+ raise
489
363
  end
490
364
 
491
- def failure(error = nil)
492
- Spree::PaymentResponse.new(false, error)
365
+ def success(authorization, requested: false, reference: nil)
366
+ Spree::PaymentResponse.new(true, 'Adyen accepted the request', {},
367
+ authorization: authorization, requested: requested, reference: reference,
368
+ test: preferred_test_mode)
493
369
  end
494
370
  end
495
371
  end