spree_adyen 0.10.0 → 6.0.6

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 (155) 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 +5 -0
  10. data/app/models/spree_adyen/amounts.rb +69 -0
  11. data/app/models/spree_adyen/gateway/payment_sessions.rb +221 -98
  12. data/app/models/spree_adyen/gateway/payment_setup_sessions.rb +68 -0
  13. data/app/models/spree_adyen/gateway/webhooks.rb +142 -0
  14. data/app/models/spree_adyen/gateway.rb +275 -391
  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 +37 -173
  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/payments/request_payload_presenter.rb +0 -85
  117. data/app/presenters/spree_adyen/refund_payload_presenter.rb +0 -38
  118. data/app/presenters/spree_adyen/webhook_payload_presenter.rb +0 -28
  119. data/app/presenters/spree_adyen/webhooks/credit_card_presenter.rb +0 -43
  120. data/app/services/spree_adyen/gateways/add_allowed_origin.rb +0 -36
  121. data/app/services/spree_adyen/gateways/configuration.rb +0 -41
  122. data/app/services/spree_adyen/gateways/configure.rb +0 -60
  123. data/app/services/spree_adyen/payment_sessions/find_or_create.rb +0 -51
  124. data/app/services/spree_adyen/payment_sessions/process_with_result.rb +0 -49
  125. data/app/services/spree_adyen/webhooks/actions/create_source.rb +0 -112
  126. data/app/services/spree_adyen/webhooks/actions/find_or_create_credit_card.rb +0 -33
  127. data/app/services/spree_adyen/webhooks/event.rb +0 -104
  128. data/app/services/spree_adyen/webhooks/event_processors/authorisation_event_processor.rb +0 -69
  129. data/app/services/spree_adyen/webhooks/event_processors/cancellation_event_processor.rb +0 -49
  130. data/app/services/spree_adyen/webhooks/event_processors/capture_event_processor.rb +0 -48
  131. data/app/services/spree_adyen/webhooks/handle_event.rb +0 -43
  132. data/app/services/spree_adyen/webhooks/standard_hmac_validator.rb +0 -37
  133. data/app/views/layouts/spree_adyen/default.html.erb +0 -14
  134. data/app/views/spree/admin/payment_methods/configuration_guides/_spree_adyen.html.erb +0 -14
  135. data/app/views/spree/admin/payment_methods/custom_form_fields/_spree_adyen.html.erb +0 -18
  136. data/app/views/spree/admin/payment_methods/descriptions/_spree_adyen.html.erb +0 -12
  137. data/app/views/spree/admin/payments/source_forms/_spree_adyen.html.erb +0 -7
  138. data/app/views/spree/checkout/payment/_spree_adyen.html.erb +0 -40
  139. data/app/views/spree_adyen/_drop_in.html.erb +0 -12
  140. data/app/views/spree_adyen/_head.html.erb +0 -2
  141. data/app/views/spree_adyen/payment_sessions/redirect.html.erb +0 -5
  142. data/config/importmap.rb +0 -7
  143. data/config/initializers/spree.rb +0 -34
  144. data/config/initializers/spree_permitted_attributes.rb +0 -5
  145. data/config/routes.rb +0 -35
  146. data/db/migrate/20250630150000_setup_spree_adyen_models.rb +0 -17
  147. data/db/migrate/20250811140113_add_channel_to_adyen_payment_sessions.rb +0 -10
  148. data/db/migrate/20250813152608_add_return_url_to_spree_adyen_payment_sessions.rb +0 -15
  149. data/lib/spree_adyen/configuration.rb +0 -42
  150. data/lib/spree_adyen/version.rb +0 -7
  151. data/lib/spree_api_v2/spree/api/v2/storefront/adyen/base_controller.rb +0 -21
  152. data/lib/spree_api_v2/spree/api/v2/storefront/adyen/payment_sessions_controller.rb +0 -72
  153. data/lib/spree_api_v2/spree_adyen/api/v2/storefront/payment_session_serializer.rb +0 -21
  154. data/vendor/javascript/@adyen--adyen-web.js +0 -4
  155. data/vendor/stylesheets/adyen.css +0 -106
@@ -1,487 +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
7
+ self.accepts_money_amounts = true
4
8
 
5
- CAPTURE_PSP_REFERENCE_METAFIELD_KEY = 'adyen.capture_psp_reference'.freeze
6
- CANCELLATION_PSP_REFERENCE_METAFIELD_KEY = 'adyen.cancellation_psp_reference'.freeze
7
-
8
- #
9
- # Attributes
10
- #
11
- attribute :skip_auto_configuration, :boolean, default: false
12
- attribute :skip_api_key_validation, :boolean, default: false
9
+ include SpreeAdyen::Gateway::PaymentSessions
10
+ include SpreeAdyen::Gateway::PaymentSetupSessions
11
+ include SpreeAdyen::Gateway::Webhooks
13
12
 
13
+ # Typed by the operator.
14
14
  preference :api_key, :password
15
15
  preference :merchant_account, :string
16
- preference :client_key, :password
17
- preference :hmac_key, :password
18
16
  preference :test_mode, :boolean, default: true
19
- preference :webhook_id, :string
17
+ # Adyen's live Checkout endpoints need it; the Management API does not.
20
18
  preference :live_url_prefix, :string
21
19
 
22
- has_one_attached :apple_developer_merchantid_domain_association, service: Spree.private_storage_service_name
23
-
24
- store_accessor :private_metadata, :previous_hmac_key
25
- #
26
- # Validations
27
- #
28
- 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
29
37
  validates :preferred_live_url_prefix, presence: true, unless: :preferred_test_mode
30
- validate :validate_api_key, if: -> { preferred_api_key_changed? }, unless: :skip_api_key_validation
31
-
32
- #
33
- # Callbacks
34
- #
35
- after_commit :configure, if: :preferred_api_key_previously_changed?, unless: :skip_auto_configuration
36
-
37
- #
38
- # Associations
39
- #
40
- has_many :payment_sessions, class_name: 'SpreeAdyen::PaymentSession',
41
- foreign_key: 'payment_method_id',
42
- dependent: :delete_all,
43
- inverse_of: :payment_method
44
-
45
- # @param amount_in_cents [Integer] the amount in cents to capture
46
- # @param payment_source [Spree::CreditCard | Spree::PaymentSource]
47
- # @param gateway_options [Hash] this is an instance of Spree::Payment::GatewayOptions.to_hash
48
- def purchase(amount_in_cents, payment_source, gateway_options = {})
49
- handle_authorize_or_purchase(amount_in_cents, payment_source, gateway_options)
50
- end
51
-
52
- # @param amount_in_cents [Integer] the amount in cents to capture
53
- # @param payment_source [Spree::CreditCard | Spree::PaymentSource]
54
- # @param gateway_options [Hash] this is an instance of Spree::Payment::GatewayOptions.to_hash
55
- def authorize(amount_in_cents, payment_source, gateway_options = {})
56
- handle_authorize_or_purchase(amount_in_cents, payment_source, gateway_options)
57
- end
58
-
59
- def handle_authorize_or_purchase(amount_in_cents, payment_source, gateway_options = {})
60
- payload = SpreeAdyen::Payments::RequestPayloadPresenter.new(
61
- source: payment_source,
62
- amount_in_cents: amount_in_cents,
63
- manual_capture: !auto_capture?,
64
- gateway_options: gateway_options
65
- ).to_h
66
-
67
- response = send_request do
68
- client.checkout.payments_api.payments(payload, headers: { 'Idempotency-Key' => SecureRandom.uuid })
69
- end
70
- response_body = response.response
38
+ validate :validate_credential, unless: -> { Rails.env.test? }, if: :credentials_changed?
39
+ after_commit :configure_async, on: %i[create update]
71
40
 
72
- if response.status.to_i == 200
73
- success(response_body.pspReference, response_body)
74
- else
75
- failure(response_body.slice('pspReference', 'message').values.join(' - '))
76
- end
41
+ def self.logo_url
42
+ 'https://spreecommerce.org/docs/images/integrations/logos/adyen.png'
77
43
  end
78
44
 
79
- def cancel(id, payment)
80
- transaction_id = id
81
- payment ||= Spree::Payment.find_by(response_code: id)
82
- if payment.completed?
83
- amount = payment.credit_allowed
84
- return success(transaction_id, {}) if amount.zero?
85
- # Don't create a refund if the payment is for a shipment, we will create a refund for the whole shipping cost instead
86
- return success(transaction_id, {}) if payment.respond_to?(:for_shipment?) && payment.for_shipment?
87
-
88
- refund = payment.refunds.create!(
89
- amount: amount,
90
- reason: Spree::RefundReason.order_canceled_reason,
91
- refunder_id: payment.order.canceler_id
92
- )
93
-
94
- # Spree::Refund#response has the response from the `credit` action
95
- # For the authorization ID we need to use the payment.response_code
96
- # Otherwise we'll overwrite the payment authorization with the refund ID
97
- success(transaction_id, refund.response.params)
98
- else
99
- payment.void!
100
- success(transaction_id, {})
101
- end
45
+ def self.docs_url
46
+ 'https://spreecommerce.org/docs/integrations/payments/adyen'
102
47
  end
103
48
 
104
- def credit(amount_in_cents, _source, payment_id, gateway_options = {})
105
- refund = gateway_options[:originator]
106
- payment = refund.present? ? refund.payment : Spree::Payment.find_by(response_code: payment_id)
107
-
108
- return failure("#{payment_id} - Payment not found") unless payment
109
-
110
- payload = SpreeAdyen::RefundPayloadPresenter.new(
111
- payment: payment,
112
- amount_in_cents: amount_in_cents,
113
- payment_method: self,
114
- currency: payment.currency,
115
- refund: refund
116
- ).to_h
117
-
118
- response = send_request do
119
- client.checkout.modifications_api.refund_captured_payment(payload, payment.transaction_id, headers: { 'Idempotency-Key' => SecureRandom.uuid })
120
- end
121
-
122
- if response.status.to_i == 201
123
- success(response.response['pspReference'], response)
124
- else
125
- failure(response.response.slice('pspReference', 'message').values.join(' - '))
126
- end
49
+ def provider_class
50
+ self.class
127
51
  end
128
52
 
129
- def request_capture(amount_in_cents, response_code, _gateway_options = {})
130
- payment = Spree::Payment.find_by(response_code: response_code)
131
-
132
- return failure("#{response_code} - Payment not found") if payment.blank?
133
- return failure("#{response_code} - Payment is already captured") if payment.completed?
134
-
135
- payload = SpreeAdyen::CapturePayloadPresenter.new(
136
- amount_in_cents: amount_in_cents,
137
- payment: payment,
138
- payment_method: self
139
- ).to_h
140
-
141
- response = send_request do
142
- client.checkout.modifications_api.capture_authorised_payment(
143
- payload,
144
- payment.response_code,
145
- headers: { 'Idempotency-Key' => SecureRandom.uuid }
146
- )
147
- end
148
-
149
- if response.status.to_i == 201
150
- success(response.response['paymentPspReference'], response)
151
- else
152
- failure(response.response.slice('paymentPspReference', 'message').values.join(' - '))
153
- end
53
+ def default_name
54
+ 'Adyen'
154
55
  end
155
56
 
156
- # This only checks if the capture was successful by checking the presence of the capture PSP reference
157
- # The actual capture is requested in #request_capture and handled in the SpreeAdyen::Webhooks::EventProcessors::CaptureEventProcessor
158
- def capture(amount_in_cents, response_code, _gateway_options = {})
159
- payment = Spree::Payment.find_by(response_code: response_code)
160
-
161
- return failure("#{response_code} - Payment not found") if payment.blank?
162
- return failure("#{response_code} - Payment is already captured") if payment.completed?
163
- return failure("#{response_code} - Capture PSP reference not found") unless payment.has_metafield?(CAPTURE_PSP_REFERENCE_METAFIELD_KEY)
164
-
165
- success(payment.response_code, {})
57
+ def method_type
58
+ 'spree_adyen'
166
59
  end
167
60
 
168
- def request_void(response_code, _source, _gateway_options)
169
- payment = Spree::Payment.find_by(response_code: response_code)
170
-
171
- return failure("#{response_code} - Payment not found") if payment.blank?
172
- return failure("#{response_code} - Payment is already void") if payment.void?
173
-
174
- payload = SpreeAdyen::CancelPayloadPresenter.new(
175
- payment: payment,
176
- payment_method: self
177
- ).to_h
178
-
179
- response = send_request do
180
- client.checkout.modifications_api.cancel_authorised_payment_by_psp_reference(
181
- payload,
182
- payment.response_code,
183
- headers: { 'Idempotency-Key' => SecureRandom.uuid }
184
- )
185
- end
186
-
187
- if response.status.to_i == 201
188
- success(response.response['paymentPspReference'], response)
189
- else
190
- failure(response.response.slice('paymentPspReference', 'message').values.join(' - '))
191
- end
61
+ def payment_icon_name
62
+ 'adyen'
192
63
  end
193
64
 
194
- # This only checks if the void was successful by checking the presence of the cancellation PSP reference
195
- # The actual void is requested in #request_void and handled in the SpreeAdyen::Webhooks::EventProcessors::CancellationEventProcessor
196
- def void(response_code, _source, _gateway_options)
197
- payment = Spree::Payment.find_by(response_code: response_code)
198
-
199
- return failure("#{response_code} - Payment not found") if payment.blank?
200
- return failure("#{response_code} - Payment is already void") if payment.void?
201
- return failure("#{response_code} - Cancellation PSP reference not found") unless payment.has_metafield?(CANCELLATION_PSP_REFERENCE_METAFIELD_KEY)
202
-
203
- success(payment.response_code, {})
65
+ def session_required?
66
+ true
204
67
  end
205
68
 
206
- def webhook_url
207
- store = stores.first
208
- return nil unless store
209
-
210
- if SpreeAdyen::Config[:use_legacy_webhook_handlers]
211
- "#{store.formatted_url}/adyen/webhooks"
212
- else
213
- "#{store.formatted_url}/api/v3/webhooks/payments/#{prefixed_id}"
214
- end
69
+ def payment_session_class
70
+ Spree::PaymentSessions::Adyen
215
71
  end
216
72
 
217
- def parse_webhook_event(raw_body, headers)
218
- payload = JSON.parse(raw_body).with_indifferent_access
219
- event = SpreeAdyen::Webhooks::Event.new(event_data: payload)
73
+ def payment_setup_session_class
74
+ Spree::PaymentSetupSessions::Adyen
75
+ end
220
76
 
221
- # Verify HMAC signature
222
- webhook_request_item = payload.dig('notificationItems', 0, 'NotificationRequestItem') || {}
223
- unless valid_hmac?(webhook_request_item)
224
- raise Spree::PaymentMethod::WebhookSignatureError, 'Invalid HMAC signature'
225
- 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
226
82
 
227
- # Find payment session — scoped to this gateway
228
- payment_session = event.session_id.present? ?
229
- Spree::PaymentSessions::Adyen.find_by(payment_method: self, external_id: event.session_id) : nil
230
-
231
- return nil unless payment_session
232
-
233
- case event.code
234
- when 'AUTHORISATION'
235
- action = event.success? ? :authorized : :failed
236
- { action: action, payment_session: payment_session, metadata: { adyen_event: event } }
237
- when 'CAPTURE'
238
- { action: :captured, payment_session: payment_session, metadata: { adyen_event: event } }
239
- when 'CANCELLATION'
240
- { action: :canceled, payment_session: payment_session, metadata: { adyen_event: event } }
241
- else
242
- nil
243
- 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)
244
86
  end
245
87
 
246
- def provider_class
247
- 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"
248
94
  end
249
95
 
96
+ # @return [String] 'test' or 'live'
250
97
  def environment
251
- if preferred_test_mode
252
- :test
253
- else
254
- :live
255
- end
98
+ preferred_test_mode ? 'test' : 'live'
256
99
  end
257
100
 
258
- 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?
259
108
 
260
- def payment_session_result(payment_session_id, session_result)
261
- response = send_request do
262
- client.checkout.payments_api.get_result_of_payment_session(payment_session_id, query_params: { sessionResult: session_result })
263
- end
264
- response_body = response.response
109
+ success(payment.response_code)
110
+ end
265
111
 
266
- if response.status.to_i == 200
267
- success(response_body.id, response_body)
268
- else
269
- failure(response_body.slice('pspReference', 'message').values.join(' - '))
270
- end
112
+ # @see #authorize
113
+ def purchase(money, source, gateway_options = {})
114
+ authorize(money, source, gateway_options)
271
115
  end
272
116
 
273
- # Creates an Adyen session via the Adyen Sessions API.
274
- # 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.
275
119
  #
276
- # @param amount [BigDecimal] the amount
277
- # @param order [Spree::Order] the order to create a session for
278
- # @param channel [String] the channel (Web, iOS, Android)
279
- # @param return_url [String] the return URL after redirect flow
280
- # @return [Spree::PaymentResponse] the response from the session creation
281
- def create_adyen_session(amount, order, channel, return_url)
282
- payload = SpreeAdyen::PaymentSessions::RequestPayloadPresenter.new(
283
- order: order,
284
- amount: amount,
285
- user: order.user,
286
- merchant_account: preferred_merchant_account,
287
- payment_method: self,
288
- channel: channel,
289
- return_url: return_url
290
- ).to_h
291
-
292
- response = send_request do
293
- 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)
294
129
  end
295
- response_body = response.response
296
130
 
297
- if response.status.to_i == 201
298
- success(response_body.id, response_body)
299
- else
300
- failure(response_body.slice('pspReference', 'message').values.join(' - '))
301
- end
131
+ success(session_id, requested: true, reference: result['pspReference'])
302
132
  end
303
133
 
304
- # @return [Boolean] whether payment profiles are supported
305
- # this is used by spree to determine whenever payment source must be passed to gateway methods
306
- def payment_profiles_supported?
307
- true
308
- 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
309
147
 
310
- def default_name
311
- 'Adyen'
148
+ payment.update_columns(metadata: payment.metadata.merge('adyen_cancel_references' => references + [result['pspReference']]))
149
+ success(session_id, requested: true)
312
150
  end
313
151
 
314
- def method_type
315
- 'spree_adyen'
316
- 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
317
166
 
318
- def payment_icon_name
319
- 'adyen'
167
+ success(result['pspReference'], requested: true)
320
168
  end
321
169
 
322
- def description_partial_name
323
- 'spree_adyen'
324
- 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
325
175
 
326
- def configuration_guide_partial_name
327
- 'spree_adyen'
328
- 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?
329
179
 
330
- def custom_form_fields_partial_name
331
- 'spree_adyen'
332
- end
333
-
334
- def gateway_dashboard_payment_url(payment)
335
- 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?
336
188
 
337
- "https://ca-#{environment}.adyen.com/ca/ca/accounts/showTx.shtml?pspReference=#{payment.transaction_id}&txType=Payment"
189
+ success(session_id, requested: true)
338
190
  end
339
191
 
340
- def reusable_sources(order)
341
- if order.completed?
342
- sources_by_order order
343
- elsif order.user.present?
344
- credit_cards.where(user_id: order.user_id)
345
- else
346
- []
347
- end
192
+ # A captured payment is refunded instead.
193
+ def can_void?(payment)
194
+ !payment.completed?
348
195
  end
349
196
 
350
- def get_api_credential_details
351
- response = client.management.my_api_credential_api.get_api_credential_details
352
-
353
- if response.status.to_i == 200
354
- success(response.response.id, response.response)
355
- else
356
- 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 })
357
204
  end
358
- rescue Adyen::AuthenticationError, Adyen::PermissionError
359
- raise
360
- rescue Adyen::AdyenError => e
361
- failure(parse_adyen_error_response(e)['message'])
362
- end
363
-
364
- def add_allowed_origin(domain)
365
- response = client.management.my_api_credential_api.add_allowed_origin({ domain: domain })
366
-
367
- if response.status.to_i == 200
368
- success(response.response.id, response.response)
369
- else
370
- 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)
371
208
  end
372
- rescue Adyen::AdyenError => e
373
- failure(parse_adyen_error_response(e))
374
- end
375
-
376
- def set_up_webhook(url)
377
- payload = SpreeAdyen::WebhookPayloadPresenter.new(url).to_h
378
- response = client.management.webhooks_merchant_level_api.set_up_webhook(payload, preferred_merchant_account)
379
209
 
380
- if response.status.to_i == 200
381
- success(response.response.id, response.response)
382
- else
383
- 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 })
384
212
  end
385
- rescue Adyen::AdyenError => e
386
- 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')
387
218
  end
388
219
 
389
- def test_webhook
390
- response = client.management.webhooks_merchant_level_api.test_webhook({ types: ['AUTHORISATION'] }, preferred_merchant_account,
391
- 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
392
224
 
393
- if response.status.to_i == 200 && response.response.dig('data', 0, 'status') == 'success'
394
- success(nil, response.response)
395
- else
396
- 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)
397
253
  end
398
- rescue Adyen::AdyenError => e
399
- failure(parse_adyen_error_response(e)['message'])
400
254
  end
401
255
 
402
- def generate_hmac_key
403
- response = client.management.webhooks_merchant_level_api.generate_hmac_key(preferred_merchant_account, preferred_webhook_id)
256
+ private
404
257
 
405
- if response.status.to_i == 200
406
- success(response.response.hmacKey, response.response)
407
- else
408
- failure(response.response)
409
- end
410
- rescue Adyen::AdyenError => e
411
- 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)
412
264
  end
413
265
 
414
- def generate_client_key
415
- 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?
416
268
 
417
- if response.status.to_i == 200
418
- success(response.response.clientKey, response.response)
419
- else
420
- failure(response.response.message)
421
- end
422
- rescue Adyen::AdyenError => e
423
- failure(parse_adyen_error_response(e)['message'])
269
+ new_record? || CREDENTIAL_PREFERENCES.any? { |key| public_send(:"preferred_#{key}_changed?") }
424
270
  end
425
271
 
426
- def apple_domain_association_file_content
427
- @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)
428
277
  end
429
278
 
430
- private
431
-
432
- def validate_api_key
433
- return if preferred_api_key.blank?
434
-
435
- get_api_credential_details
436
- rescue Adyen::AuthenticationError => e
437
- errors.add(:preferred_api_key, "is invalid. Response: #{e.msg}")
438
- rescue Adyen::PermissionError => e
439
- errors.add(:preferred_api_key, "has insufficient permissions. Add missing roles to API credential. Response: #{e.msg}")
440
- rescue Adyen::AdyenError => e
441
- 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
+ )
442
288
  end
443
289
 
444
- def configure
445
- return if preferred_api_key.blank?
290
+ def wait_before_retry(attempt)
291
+ sleep(0.5 * (2**(attempt - 1)))
292
+ end
446
293
 
447
- SpreeAdyen::Gateways::Configure.new(self).call
294
+ def log_status(operation, status)
295
+ Rails.logger.info("[spree_adyen] #{operation} #{status}")
448
296
  end
449
297
 
450
- def client
451
- @client ||= Adyen::Client.new.tap do |client|
452
- client.api_key = preferred_api_key
453
- client.env = environment
454
- 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)
455
313
  end
456
314
  end
457
315
 
458
- def send_request
459
- yield
460
- rescue Adyen::AdyenError => e
461
- 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')
462
325
  end
463
326
 
464
- def parse_adyen_error_response(error)
465
- JSON.parse(error.response)
466
- rescue JSON::ParserError, TypeError
467
- { '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
468
330
  end
469
331
 
470
- def valid_hmac?(webhook_request_item)
471
- hmac_keys = [preferred_hmac_key, previous_hmac_key].compact
472
- 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
473
336
 
474
- hmac_keys.any? do |key|
475
- Adyen::Utils::HmacValidator.new.valid_webhook_hmac?(webhook_request_item, key)
476
- end
337
+ def adyen_amount(money)
338
+ SpreeAdyen::Amounts.to_adyen_amount(money.to_d, money.currency.iso_code)
477
339
  end
478
340
 
479
- def success(authorization, full_response)
480
- 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
481
363
  end
482
364
 
483
- def failure(error = nil)
484
- 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)
485
369
  end
486
370
  end
487
371
  end