spree_paypal_checkout 0.7.0 → 6.0.3

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 (52) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +16 -4
  3. data/README.md +34 -52
  4. data/Rakefile +7 -17
  5. data/app/jobs/spree_paypal_checkout/base_job.rb +5 -0
  6. data/app/jobs/spree_paypal_checkout/register_webhook_job.rb +20 -0
  7. data/app/maintenance_tasks/spree_paypal_checkout/maintenance_tasks/migrate_payments.rb +100 -0
  8. data/app/models/spree/payment_sessions/paypal_checkout.rb +39 -57
  9. data/app/models/spree_paypal_checkout/amounts.rb +55 -0
  10. data/app/models/spree_paypal_checkout/gateway/payment_sessions.rb +232 -149
  11. data/app/models/spree_paypal_checkout/gateway/webhooks.rb +112 -0
  12. data/app/models/spree_paypal_checkout/gateway.rb +418 -128
  13. data/app/models/spree_paypal_checkout/notifications_client.rb +82 -0
  14. data/app/models/spree_paypal_checkout/payment_sources/paypal.rb +43 -3
  15. data/app/presenters/spree_paypal_checkout/order_presenter.rb +121 -49
  16. data/app/services/spree_paypal_checkout/register_webhook.rb +30 -0
  17. data/config/locales/en.yml +23 -4
  18. data/lib/generators/spree_paypal_checkout/install/install_generator.rb +12 -12
  19. data/lib/spree_paypal_checkout/engine.rb +6 -37
  20. data/lib/spree_paypal_checkout/factories.rb +1 -48
  21. data/lib/spree_paypal_checkout/testing_support/factories/gateway_factory.rb +18 -0
  22. data/lib/spree_paypal_checkout/testing_support/factories/payment_session_factory.rb +16 -0
  23. data/lib/spree_paypal_checkout.rb +11 -3
  24. data/lib/tasks/register_paypal_webhooks.rake +37 -0
  25. metadata +33 -101
  26. data/app/assets/config/spree_paypal_checkout_manifest.js +0 -2
  27. data/app/controllers/spree_paypal_checkout/store_controller_decorator.rb +0 -9
  28. data/app/helpers/spree_paypal_checkout/base_helper.rb +0 -11
  29. data/app/javascript/spree_paypal_checkout/application.js +0 -16
  30. data/app/javascript/spree_paypal_checkout/controllers/checkout_paypal_controller.js +0 -117
  31. data/app/models/spree_paypal_checkout/base.rb +0 -6
  32. data/app/models/spree_paypal_checkout/order.rb +0 -71
  33. data/app/models/spree_paypal_checkout/order_decorator.rb +0 -11
  34. data/app/models/spree_paypal_checkout/payment_method_decorator.rb +0 -15
  35. data/app/models/spree_paypal_checkout/store_decorator.rb +0 -9
  36. data/app/services/spree_paypal_checkout/capture_order.rb +0 -104
  37. data/app/services/spree_paypal_checkout/create_payment.rb +0 -34
  38. data/app/services/spree_paypal_checkout/create_source.rb +0 -52
  39. data/app/views/spree/admin/payment_methods/configuration_guides/_spree_paypal_checkout.html.erb +0 -6
  40. data/app/views/spree/admin/payment_methods/descriptions/_spree_paypal_checkout.html.erb +0 -10
  41. data/app/views/spree/admin/payments/source_forms/_spree_paypal_checkout.html.erb +0 -7
  42. data/app/views/spree/checkout/payment/_spree_paypal_checkout.html.erb +0 -13
  43. data/app/views/spree/payment_sources/_paypal_checkout.html.erb +0 -16
  44. data/app/views/spree_paypal_checkout/_head.html.erb +0 -11
  45. data/config/importmap.rb +0 -6
  46. data/config/initializers/spree.rb +0 -7
  47. data/config/routes.rb +0 -16
  48. data/db/migrate/20250528095719_create_spree_paypal_checkout_orders.rb +0 -20
  49. data/lib/spree_api_v2/spree/api/v2/storefront/paypal_order_serializer.rb +0 -11
  50. data/lib/spree_api_v2/spree/api/v2/storefront/paypal_orders_controller.rb +0 -55
  51. data/lib/spree_paypal_checkout/configuration.rb +0 -5
  52. data/lib/spree_paypal_checkout/version.rb +0 -7
@@ -1,35 +1,61 @@
1
1
  module SpreePaypalCheckout
2
+ # PayPal Checkout gateway built on the payment session API. A session is a
3
+ # PayPal order: the buyer approves it in PayPal's window, then the server
4
+ # captures or authorizes it, so the server is the only thing that moves money.
5
+ #
6
+ # A payment's response code is always the PayPal order id, the key core uses
7
+ # to link a session to its payment. The capture and authorization ids PayPal
8
+ # issues are read from the order whenever a capture, refund or void needs them.
2
9
  class Gateway < ::Spree::Gateway
3
- include PaypalServerSdk
4
- include PaymentSessions
5
-
6
- GatewayResponse = Struct.new(:success, :message, :params, :authorization) do
7
- alias_method :success?, :success
10
+ self.accepts_money_amounts = true
11
+
12
+ # A capture PayPal has taken, whether or not it was refunded since.
13
+ CAPTURED_STATUSES = %w[COMPLETED PARTIALLY_REFUNDED REFUNDED].freeze
14
+ # A capture that took or holds the money.
15
+ MOVED_CAPTURE_STATUSES = (CAPTURED_STATUSES + %w[PENDING]).freeze
16
+ # An authorization that holds or held the money.
17
+ MOVED_AUTHORIZATION_STATUSES = %w[CREATED PENDING PARTIALLY_CAPTURED CAPTURED].freeze
18
+ # An authorization that can still be captured or voided.
19
+ OPEN_AUTHORIZATION_STATUSES = %w[CREATED PARTIALLY_CAPTURED PENDING].freeze
20
+ # Transport failures where PayPal may or may not have acted on the request.
21
+ CONNECTION_ERRORS = [Faraday::TimeoutError, Faraday::ConnectionFailed].freeze
22
+
23
+ # A refusal from PayPal, with its issue code (INSTRUMENT_DECLINED,
24
+ # AUTHORIZATION_EXPIRED, …) kept apart from the message for callers that
25
+ # act on it.
26
+ class PaypalError < Spree::Core::GatewayError
27
+ attr_reader :issue, :status
28
+
29
+ def initialize(message = nil, issue: nil, status: nil)
30
+ super(message)
31
+ @issue = issue
32
+ @status = status
33
+ end
8
34
  end
9
35
 
10
- #
11
- # Preferences
12
- #
36
+ include SpreePaypalCheckout::Gateway::PaymentSessions
37
+ include SpreePaypalCheckout::Gateway::Webhooks
38
+
13
39
  preference :client_id, :password
14
40
  preference :client_secret, :password
15
- preference :webhook_secret, :string
41
+ # The credentials do not say which PayPal environment they belong to.
16
42
  preference :test_mode, :boolean, default: true
43
+ # Written by webhook registration, never by an operator.
44
+ preference :webhook_id, :string, internal: true
17
45
 
18
- #
19
- # Validations
20
- #
21
46
  validates :preferred_client_id, :preferred_client_secret, presence: true
47
+ validate :validate_credentials, unless: -> { Rails.env.test? }, if: :credentials_changed?
22
48
 
23
- def provider_class
24
- self.class
49
+ def self.logo_url
50
+ 'https://spreecommerce.org/docs/images/integrations/logos/paypal.png'
25
51
  end
26
52
 
27
- def payment_source_class
28
- SpreePaypalCheckout::PaymentSources::Paypal
53
+ def self.docs_url
54
+ 'https://spreecommerce.org/docs/integrations/payments/paypal'
29
55
  end
30
56
 
31
- def payment_profiles_supported?
32
- true
57
+ def provider_class
58
+ self.class
33
59
  end
34
60
 
35
61
  def default_name
@@ -44,173 +70,437 @@ module SpreePaypalCheckout
44
70
  'paypal'
45
71
  end
46
72
 
47
- def description_partial_name
48
- 'spree_paypal_checkout'
73
+ def session_required?
74
+ true
49
75
  end
50
76
 
51
- def configuration_guide_partial_name
52
- 'spree_paypal_checkout'
77
+ def payment_session_class
78
+ Spree::PaymentSessions::PaypalCheckout
53
79
  end
54
80
 
55
- def source_partial_name
56
- 'paypal_checkout'
81
+ def payment_source_class
82
+ SpreePaypalCheckout::PaymentSources::Paypal
57
83
  end
58
84
 
59
- def webhook_url
60
- store = stores.first
61
- return nil unless store
85
+ # No saved PayPal accounts in this release, so core never calls
86
+ # create_profile and passes no source to credit and void.
87
+ def payment_profiles_supported?
88
+ false
89
+ end
62
90
 
63
- "#{store.formatted_url}/api/v3/webhooks/payments/#{prefixed_id}"
91
+ # Not offered for a currency PayPal does not take, nor for a total it
92
+ # would refuse, such as yen or forint with a fraction.
93
+ def available_for_order?(order)
94
+ super && SpreePaypalCheckout::Amounts.payable?(order.total_minus_store_credits, order.currency)
64
95
  end
65
96
 
66
- def create_profile(payment)
67
- user = payment.order.user
68
- return if user.blank?
97
+ # CAPTURE takes the money when the session completes; AUTHORIZE holds it
98
+ # for Spree to capture on dispatch or by hand.
99
+ #
100
+ # @return [String]
101
+ def paypal_intent
102
+ if capture_at_checkout?
103
+ PaypalServerSdk::CheckoutPaymentIntent::CAPTURE
104
+ else
105
+ PaypalServerSdk::CheckoutPaymentIntent::AUTHORIZE
106
+ end
107
+ end
69
108
 
70
- return if payment.source.blank?
71
- return unless payment.source.is_a?(SpreePaypalCheckout::PaymentSources::Paypal)
109
+ # PayPal's activity page lists transactions, not orders, so the link needs
110
+ # the capture or authorization id recorded at settlement.
111
+ def gateway_dashboard_payment_url(payment)
112
+ transaction_id = payment.metadata['paypal_capture_id'].presence || payment.metadata['paypal_authorization_id'].presence
113
+ return if transaction_id.blank?
72
114
 
73
- paypal_account_id = payment.source.account_id
115
+ host = preferred_test_mode ? 'www.sandbox.paypal.com' : 'www.paypal.com'
116
+ "https://#{host}/activity/payment/#{transaction_id}"
117
+ end
74
118
 
75
- return if paypal_account_id.blank?
119
+ # Called by core when a session-created payment moves on. The session has
120
+ # already captured or authorized the order, so this reads it back.
121
+ #
122
+ # @param _money [Spree::Money]
123
+ # @param _payment_source [Spree::PaymentSource, nil]
124
+ # @param gateway_options [Hash] Spree::Payment::GatewayOptions#to_hash
125
+ # @return [Spree::PaymentResponse]
126
+ def authorize(_money, _payment_source, gateway_options = {})
127
+ read_back(gateway_options)
128
+ end
76
129
 
77
- payment.payment_method.gateway_customers.find_or_create_by(user: user, profile_id: paypal_account_id)
130
+ # @see #authorize
131
+ def purchase(_money, _payment_source, gateway_options = {})
132
+ read_back(gateway_options)
78
133
  end
79
134
 
135
+ # Captures the order's authorization, in part or in full. It is the
136
+ # payment's only capture (`final_capture`): core authorizes any remainder
137
+ # as a payment of its own.
138
+ #
139
+ # @param money [Spree::Money]
140
+ # @param order_id [String] the PayPal order id
141
+ # @param gateway_options [Hash]
142
+ # @return [Spree::PaymentResponse]
143
+ # @raise [PaypalError] when PayPal refuses, or holds the capture as pending
144
+ def capture(money, order_id, gateway_options = {})
145
+ paypal_order = protect_from_error { paypal_order(order_id) }
146
+
147
+ capture = captures(paypal_order).first
148
+ if capture
149
+ raise_pending_capture(capture) if capture['status'] == 'PENDING'
150
+ if capture['status'].in?(CAPTURED_STATUSES)
151
+ response = already_captured(order_id, paypal_order, capture, money)
152
+ record_capture_id(gateway_options, capture['id'])
153
+ return response
154
+ end
155
+ end
156
+
157
+ authorization = open_authorization(paypal_order)
158
+ raise Spree::Core::GatewayError, no_authorization_message(paypal_order) if authorization.nil?
159
+
160
+ result = protect_from_error(money_moving: true) do
161
+ capture_authorization(authorization['id'], money, request_id: request_id(gateway_options, order_id, 'capture'))
162
+ end
163
+
164
+ case result['status']
165
+ when 'COMPLETED'
166
+ record_capture_id(gateway_options, result['id'])
167
+ success(order_id, result)
168
+ when 'PENDING' then raise_pending_capture(result)
169
+ else
170
+ raise PaypalError.new(I18n.t('spree.paypal_checkout.errors.capture_not_completed', status: result['status']),
171
+ issue: result['status'])
172
+ end
173
+ end
174
+
175
+ # Refunds the order's capture.
176
+ #
177
+ # @param money [Spree::Money]
178
+ # @param order_id [String] the PayPal order id
179
+ # @param options [Hash] carries the Spree::Refund as +originator+
180
+ # @return [Spree::PaymentResponse] authorized by the PayPal refund id
181
+ def credit(money, order_id, options = {})
182
+ paypal_order = protect_from_error { paypal_order(order_id) }
183
+ capture = captures(paypal_order).find { |candidate| candidate['status'].in?(CAPTURED_STATUSES) }
184
+ raise Spree::Core::GatewayError, I18n.t('spree.paypal_checkout.errors.nothing_to_refund') if capture.nil?
185
+
186
+ originator = options[:originator]
187
+ # Without a refund record there is nothing stable to key on, and reusing
188
+ # a key would replay an earlier refund instead of making this one.
189
+ request_id = originator.respond_to?(:prefixed_id) ? "spree-#{originator.prefixed_id}-refund" : "paypal-#{SecureRandom.uuid}"
190
+
191
+ result = protect_from_error(money_moving: true) do
192
+ refund_capture(capture['id'], money, request_id: request_id)
193
+ end
194
+ # PayPal can answer a refund it did not make with a status, not an error.
195
+ # A PENDING refund is recorded, as Stripe's are: core has no pending refund.
196
+ if result['status'].in?(%w[FAILED CANCELLED])
197
+ raise PaypalError.new(I18n.t('spree.paypal_checkout.errors.refund_not_completed', status: result['status']),
198
+ issue: result['status'])
199
+ end
200
+
201
+ success(result['id'], result)
202
+ end
203
+
204
+ # Releases the order's authorization. An order taken with the CAPTURE
205
+ # intent holds no authorization until it is captured, so there is nothing
206
+ # to release.
207
+ #
208
+ # @param order_id [String] the PayPal order id
209
+ # @param gateway_options [Hash]
210
+ # @return [Spree::PaymentResponse]
211
+ # @raise [PaypalError] when a capture is still pending: the money may yet
212
+ # arrive, and a payment voided in Spree could not take it
213
+ def void(order_id, gateway_options = {})
214
+ paypal_order = protect_from_error { paypal_order(order_id) }
215
+
216
+ capture = captures(paypal_order).first
217
+ if capture && capture['status'] == 'PENDING'
218
+ raise PaypalError.new(I18n.t('spree.paypal_checkout.errors.void_pending_capture'), issue: 'PENDING')
219
+ end
220
+ if capture && capture['status'].in?(CAPTURED_STATUSES)
221
+ raise Spree::Core::GatewayError, I18n.t('spree.paypal_checkout.errors.void_captured')
222
+ end
223
+
224
+ authorization = open_authorization(paypal_order)
225
+ return success(order_id, paypal_order) if authorization.nil?
226
+
227
+ result = protect_from_error(money_moving: true) do
228
+ void_authorization(authorization['id'], request_id: request_id(gateway_options, order_id, 'void'))
229
+ end
230
+
231
+ success(order_id, result)
232
+ end
233
+
234
+ # A completed payment can no longer be voided, so cancellation refunds it
235
+ # instead, unless the operator asked to keep the money. Refunds for a
236
+ # fulfillment are skipped; the delivery cost is refunded as a whole
237
+ # elsewhere.
238
+ def cancel(order_id, payment = nil, refund: true)
239
+ return void(order_id, payment ? payment.gateway_options : {}) unless payment&.completed?
240
+ return success(order_id, {}) unless refund
241
+
242
+ amount = payment.credit_allowed
243
+ return success(order_id, {}) if amount.zero?
244
+ return success(order_id, {}) if payment.respond_to?(:for_shipment?) && payment.for_shipment?
245
+
246
+ # Store passed explicitly: cancellation runs from jobs and webhooks where
247
+ # Spree::Current.store is nil.
248
+ result = Spree.refund_create_workflow.call(
249
+ payment: payment,
250
+ reason: Spree::RefundReason.order_canceled_reason(payment.owner.store),
251
+ refunder: payment.order.canceler
252
+ )
253
+ raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?
254
+
255
+ # The authorization must stay the order id, or the refund id would
256
+ # overwrite it.
257
+ success(payment.response_code, result.value.response.params)
258
+ end
259
+
260
+ # @param order_id [String]
261
+ # @return [Hash] the PayPal order, as PayPal writes it
262
+ def paypal_order(order_id)
263
+ client.orders.get_order('id' => order_id).data.to_hash
264
+ end
265
+
266
+ # @return [Hash] the capture
267
+ def capture_authorization(authorization_id, money, request_id:)
268
+ client.payments.capture_authorized_payment(
269
+ 'authorization_id' => authorization_id,
270
+ 'paypal_request_id' => request_id,
271
+ 'prefer' => 'return=representation',
272
+ 'body' => PaypalServerSdk::CaptureRequest.new(amount: paypal_money(money), final_capture: true)
273
+ ).data.to_hash
274
+ end
275
+
276
+ # @return [Hash] the refund
277
+ def refund_capture(capture_id, money, request_id:)
278
+ client.payments.refund_captured_payment(
279
+ 'capture_id' => capture_id,
280
+ 'paypal_request_id' => request_id,
281
+ 'prefer' => 'return=representation',
282
+ 'body' => PaypalServerSdk::RefundRequest.new(amount: paypal_money(money))
283
+ ).data.to_hash
284
+ end
285
+
286
+ # @return [Hash] the voided authorization; empty when PayPal answers
287
+ # without a body
288
+ def void_authorization(authorization_id, request_id:)
289
+ client.payments.void_payment(
290
+ 'authorization_id' => authorization_id,
291
+ 'paypal_request_id' => request_id,
292
+ 'prefer' => 'return=representation'
293
+ ).data&.to_hash || {}
294
+ end
295
+
296
+ # Asks PayPal for an access token with the stored credentials, which is
297
+ # how PayPal says whether it accepts them.
298
+ #
299
+ # @raise [PaypalServerSdk::APIException] when PayPal refuses them
300
+ def request_access_token
301
+ client.oauth2.fetch_token
302
+ end
303
+
304
+ # Rebuilt when the credentials change, since it carries them.
305
+ #
306
+ # @return [PaypalServerSdk::Client]
80
307
  def client
81
- @client ||= Client.new(
82
- client_credentials_auth_credentials: ClientCredentialsAuthCredentials.new(
83
- o_auth_client_id: preferred_client_id,
84
- o_auth_client_secret: preferred_client_secret
308
+ fingerprint = [preferred_client_id, preferred_client_secret, preferred_test_mode]
309
+ return @client if @client && @client_fingerprint == fingerprint
310
+
311
+ @client_fingerprint = fingerprint
312
+ @client = PaypalServerSdk::Client.new(
313
+ client_credentials_auth_credentials: PaypalServerSdk::ClientCredentialsAuthCredentials.new(
314
+ o_auth_client_id: preferred_client_id.to_s,
315
+ o_auth_client_secret: preferred_client_secret.to_s
85
316
  ),
86
- environment: preferred_test_mode ? Environment::SANDBOX : Environment::PRODUCTION,
87
- logging_configuration: LoggingConfiguration.new(
88
- log_level: Logger::INFO,
89
- request_logging_config: RequestLoggingConfiguration.new(
90
- log_body: true
91
- ),
92
- response_logging_config: ResponseLoggingConfiguration.new(
93
- log_headers: true
94
- )
317
+ environment: preferred_test_mode ? PaypalServerSdk::Environment::SANDBOX : PaypalServerSdk::Environment::PRODUCTION,
318
+ timeout: 30,
319
+ max_retries: 2,
320
+ # Retrying a POST is safe only because every one that moves money
321
+ # carries a PayPal-Request-Id; a PATCH only ever replaces the whole
322
+ # purchase unit.
323
+ retry_methods: %i[get post patch],
324
+ logging_configuration: PaypalServerSdk::LoggingConfiguration.new(
325
+ logger: Rails.logger,
326
+ log_level: log_level,
327
+ # Bodies carry buyer names, emails and addresses.
328
+ request_logging_config: PaypalServerSdk::RequestLoggingConfiguration.new(log_body: false, log_headers: false),
329
+ response_logging_config: PaypalServerSdk::ResponseLoggingConfiguration.new(log_body: false, log_headers: false)
95
330
  )
96
331
  )
97
332
  end
98
333
 
99
- def authorize(amount_in_cents, payment_source, gateway_options = {})
100
- raise 'Not implemented'
334
+ def captures(paypal_order)
335
+ payments_of(paypal_order, 'captures')
336
+ end
337
+
338
+ def authorizations(paypal_order)
339
+ payments_of(paypal_order, 'authorizations')
340
+ end
341
+
342
+ # Whether PayPal took the money, or holds a capture of it.
343
+ def capture_taken?(paypal_order)
344
+ captures(paypal_order).any? { |capture| capture['status'].in?(MOVED_CAPTURE_STATUSES) }
101
345
  end
102
346
 
103
- # Purchase is the same as authorize + capture in one step
104
- def purchase(amount_in_cents, payment_source, gateway_options = {})
105
- capture(amount_in_cents, payment_source.paypal_id, gateway_options)
347
+ # Whether PayPal took or holds money against the order.
348
+ def money_moved?(paypal_order)
349
+ capture_taken?(paypal_order) ||
350
+ authorizations(paypal_order).any? { |authorization| authorization['status'].in?(MOVED_AUTHORIZATION_STATUSES) }
106
351
  end
107
352
 
108
- # Capture a previously authorized payment
109
- # @param amount_in_cents [Integer] the amount in cents to capture
110
- # @param paypal_id [String] the PayPal Order ID
111
- # @param gateway_options [Hash] this is an instance of Spree::Payment::GatewayOptions.to_hash
112
- def capture(amount_in_cents, paypal_id, gateway_options = {})
113
- protect_from_error do
114
- order = find_order(gateway_options[:order_id])
115
- return failure('Order not found') unless order
353
+ private
116
354
 
117
- response = client.orders.capture_order({
118
- 'id' => paypal_id,
119
- 'prefer' => 'return=representation'
120
- })
355
+ def read_back(gateway_options)
356
+ payment = find_payment(gateway_options)
357
+ return failure('Payment not found') if payment.blank?
358
+ return failure('Payment is missing a PayPal order') if payment.response_code.blank?
121
359
 
122
- if response.data.status == 'COMPLETED'
123
- success(response.data.id, response.data.as_json)
124
- else
125
- failure('Failed to capture PayPal payment', response.data)
126
- end
127
- end
360
+ paypal_order = protect_from_error { paypal_order(payment.response_code) }
361
+ return success(payment.response_code, paypal_order) if capture_taken?(paypal_order) || open_authorization(paypal_order)
362
+
363
+ failure(no_authorization_message(paypal_order))
128
364
  end
129
365
 
130
- def void(authorization, _source, gateway_options = {})
131
- protect_from_error do
132
- response = client.payments.void_payment({
133
- 'authorization_id' => authorization,
134
- 'prefer' => 'return=representation'
135
- })
366
+ # Scoped through this gateway's own payments and found by the prefixed id;
367
+ # the stored number remains only for callers still passing pre-6.0 options.
368
+ def find_payment(gateway_options)
369
+ prefixed_id = gateway_options[:payment_prefixed_id]
370
+ payment = prefixed_id.present? ? payments.find_by_prefix_id(prefixed_id) : nil
371
+ return payment if payment.present?
372
+
373
+ payment_number = gateway_options[:payment_id].presence || gateway_options[:order_id]
374
+ payments.find_by(number: payment_number) if payment_number.present?
375
+ end
136
376
 
137
- success(authorization, response.data.as_json)
377
+ def open_authorization(paypal_order)
378
+ authorizations(paypal_order).find do |authorization|
379
+ authorization['status'].in?(OPEN_AUTHORIZATION_STATUSES)
138
380
  end
139
381
  end
140
382
 
141
- def credit(amount_in_cents, _payment_source, paypal_payment_id, gateway_options = {})
142
- refund_originator = gateway_options[:originator]
143
- order = refund_originator.respond_to?(:order) ? refund_originator.order : refund_originator
383
+ def payments_of(paypal_order, kind)
384
+ Array(paypal_order['purchase_units']).flat_map { |unit| Array(unit.dig('payments', kind)) }
385
+ end
144
386
 
145
- return failure('Order not found') unless order
387
+ def no_authorization_message(paypal_order)
388
+ authorization = authorizations(paypal_order).first
389
+ if authorization
390
+ I18n.t('spree.paypal_checkout.errors.authorization_not_open', status: authorization['status'])
391
+ else
392
+ I18n.t('spree.paypal_checkout.errors.nothing_to_capture', status: paypal_order['status'])
393
+ end
394
+ end
146
395
 
147
- protect_from_error do
148
- payload = {
149
- capture_id: paypal_payment_id,
150
- amount: {
151
- value: (amount_in_cents / 100.0).to_s,
152
- currency_code: order.currency.upcase
153
- }
154
- }.deep_stringify_keys
396
+ # A capture an earlier request already made, perhaps one that timed out.
397
+ # It is only this capture if it took the amount now asked for.
398
+ def already_captured(order_id, paypal_order, capture, money)
399
+ return success(order_id, paypal_order) if amount_matches?(capture['amount'], money, money.currency)
155
400
 
156
- response = client.payments.refund_captured_payment(payload)
401
+ captured = capture['amount'] || {}
402
+ raise Spree::Core::GatewayError, I18n.t('spree.paypal_checkout.errors.captured_other_amount',
403
+ captured: "#{captured['value']} #{captured['currency_code']}",
404
+ requested: "#{SpreePaypalCheckout::Amounts.to_paypal(money, money.currency)} #{money.currency.to_s.upcase}")
405
+ end
157
406
 
158
- success(response.data.id, response.data.as_json)
159
- end
407
+ # @param paypal_amount [Hash, nil] an amount as PayPal writes it
408
+ def amount_matches?(paypal_amount, amount, currency)
409
+ paypal_amount = paypal_amount || {}
410
+ paypal_amount['currency_code'] == currency.to_s.upcase &&
411
+ paypal_amount['value'] == SpreePaypalCheckout::Amounts.to_paypal(amount, currency)
160
412
  end
161
413
 
162
- def cancel(authorization, payment = nil)
163
- protect_from_error do
164
- if payment&.completed?
165
- amount = payment.credit_allowed
166
- return success(authorization, {}) if amount.zero?
414
+ # Settlement records a capture only when checkout took one, so a capture
415
+ # made later records its own id for the dashboard link.
416
+ def record_capture_id(gateway_options, capture_id)
417
+ payment = find_payment(gateway_options)
418
+ return if payment.nil? || payment.metadata['paypal_capture_id'] == capture_id
167
419
 
168
- refund = payment.refunds.create!(
169
- amount: amount,
170
- reason: Spree::RefundReason.order_canceled_reason,
171
- refunder_id: payment.order.canceler_id
172
- )
420
+ payment.update_columns(metadata: payment.metadata.merge('paypal_capture_id' => capture_id))
421
+ end
173
422
 
174
- success(payment.response_code, refund.response.params)
175
- else
176
- response = client.payments.void_payment({
177
- 'authorization_id' => authorization,
178
- 'prefer' => 'return=representation'
179
- })
423
+ def raise_pending_capture(capture)
424
+ reason = capture.dig('status_details', 'reason') || 'PENDING'
425
+ raise PaypalError.new(I18n.t('spree.paypal_checkout.errors.capture_pending', reason: reason), issue: reason)
426
+ end
180
427
 
181
- success(authorization, response.data.as_json)
182
- end
183
- end
428
+ # Keyed on the Spree payment, so a retry or a double click reaches PayPal
429
+ # as the same request and cannot move money twice.
430
+ def request_id(gateway_options, order_id, action)
431
+ base = gateway_options[:idempotency_key].presence || "paypal-#{order_id}"
432
+ "#{base}-#{action}"
184
433
  end
185
434
 
186
- private
435
+ def paypal_money(money)
436
+ SpreePaypalCheckout::Amounts.to_paypal_money(money, money.currency)
437
+ end
438
+
439
+ def log_level
440
+ Logger.const_get(ENV.fetch('PAYPAL_LOG_LEVEL', 'info').upcase)
441
+ rescue NameError
442
+ Logger::INFO
443
+ end
187
444
 
188
- def find_order(order_id)
189
- return nil unless order_id
445
+ def credentials_changed?
446
+ return false if preferred_client_id.blank? || preferred_client_secret.blank?
190
447
 
191
- order_number, _payment_number = order_id.split('-')
192
- Spree::Order.find_by(number: order_number)
448
+ new_record? || preferred_client_id_changed? || preferred_client_secret_changed? || preferred_test_mode_changed?
193
449
  end
194
450
 
195
- def find_capture_id(order_data)
196
- return nil unless order_data
451
+ def validate_credentials
452
+ request_access_token
453
+ rescue PaypalServerSdk::APIException
454
+ errors.add(:base, :credentials_rejected, message: credentials_rejected_message)
455
+ rescue *CONNECTION_ERRORS
456
+ errors.add(:base, :paypal_unavailable, message: I18n.t('spree.paypal_checkout.errors.paypal_unavailable'))
457
+ end
197
458
 
198
- # Navigate through the order data to find the capture ID
199
- order_data.dig('purchase_units', 0, 'payments', 'captures', 0, 'id')
459
+ def credentials_rejected_message
460
+ I18n.t('spree.paypal_checkout.errors.credentials_rejected', environment: preferred_test_mode ? 'sandbox' : 'live')
200
461
  end
201
462
 
202
- def protect_from_error
463
+ # PayPal's refusal becomes a GatewayError naming its issue code. A call
464
+ # that moves money and gets no answer becomes an AmbiguousGatewayError,
465
+ # since PayPal may have acted on it.
466
+ def protect_from_error(money_moving: false)
203
467
  yield
204
468
  rescue PaypalServerSdk::APIException => e
205
- raise Spree::Core::GatewayError, "PayPal API error: #{e.message}"
469
+ message = e.is_a?(PaypalServerSdk::ErrorException) ? paypal_error_message(e) : "PayPal: #{e.message}"
470
+ # A server error or a request timeout says nothing about whether PayPal
471
+ # acted, even after the SDK's retries.
472
+ if money_moving && (e.response_code.to_i >= 500 || e.response_code.to_i == 408)
473
+ raise Spree::Core::AmbiguousGatewayError, I18n.t('spree.paypal_checkout.errors.outcome_unknown', message: message)
474
+ end
475
+
476
+ issue = paypal_issue(e) if e.is_a?(PaypalServerSdk::ErrorException)
477
+ raise PaypalError.new(message, issue: issue, status: e.response_code)
478
+ rescue CoreLibrary::AuthValidationException
479
+ raise Spree::Core::GatewayError, credentials_rejected_message
480
+ rescue *CONNECTION_ERRORS => e
481
+ error_class = money_moving ? Spree::Core::AmbiguousGatewayError : Spree::Core::GatewayError
482
+ raise error_class, I18n.t('spree.paypal_checkout.errors.no_answer', message: e.message)
483
+ end
484
+
485
+ # PayPal's own issue code, such as INSTRUMENT_DECLINED, when it gave one.
486
+ def paypal_issue(error)
487
+ paypal_detail(error)&.issue || error.name
488
+ end
489
+
490
+ def paypal_error_message(error)
491
+ [paypal_issue(error), paypal_detail(error)&.description || error.message].compact.join(': ')
492
+ end
493
+
494
+ def paypal_detail(error)
495
+ error.details.first if error.details.is_a?(Array)
206
496
  end
207
497
 
208
- def success(authorization, response)
209
- GatewayResponse.new(true, 'Transaction successful', response, authorization)
498
+ def success(authorization, full_response)
499
+ Spree::PaymentResponse.new(true, nil, full_response.as_json, authorization: authorization)
210
500
  end
211
501
 
212
- def failure(message, response = {})
213
- GatewayResponse.new(false, message, response, nil)
502
+ def failure(error = nil)
503
+ Spree::PaymentResponse.new(false, error)
214
504
  end
215
505
  end
216
506
  end