Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Added PayPal payment sessions and settlement

Łukasz Adamczyk8fc240e73cb8
diff --git a/spree/providers/paypal/app/models/spree/payment_sessions/paypal_checkout.rb b/spree/providers/paypal/app/models/spree/payment_sessions/paypal_checkout.rb
index 52dce53664..314c85c5c2 100644
--- a/spree/providers/paypal/app/models/spree/payment_sessions/paypal_checkout.rb
+++ b/spree/providers/paypal/app/models/spree/payment_sessions/paypal_checkout.rb
@@ -1,5 +1,58 @@
module Spree
# Stored under this name in `type` columns since 5.x, so it is kept.
class PaymentSessions::PaypalCheckout < PaymentSession
+ # The order read at completion, or by prepare_for_settlement! on the
+ # webhook path, so settlement inside the lock does no PayPal I/O.
+ attr_writer :paypal_order
+
+ def intent
+ external_data&.dig('intent')
+ end
+
+ # Moves only after a recoverable decline, so a buyer's next try reaches
+ # PayPal as a new request rather than a replay of the declined one.
+ #
+ # @return [Integer]
+ def attempt
+ (external_data&.dig('attempt') || 1).to_i
+ end
+
+ # Whether Complete ever asked PayPal to move money for this session.
+ def complete_attempted?
+ external_data.present? && (external_data.key?('attempt') || external_data.key?('paypal_result'))
+ end
+
+ # @return [Hash]
+ def paypal_order
+ @paypal_order ||= payment_method.paypal_order(external_id)
+ end
+
+ # Settlement reads the order only to create the payment, so a session that
+ # already has one needs no PayPal call.
+ def prepare_for_settlement!
+ paypal_order if payment.nil?
+ self
+ end
+
+ # @return [SpreePaypalCheckout::PaymentSources::Paypal, nil]
+ def payment_source_for_settlement
+ SpreePaypalCheckout::PaymentSources::Paypal.for_payment_source(
+ paypal_order['payment_source'],
+ payment_method: payment_method,
+ customer: owner&.customer,
+ paypal_order_id: external_id
+ )
+ end
+
+ # Records what PayPal issued against the order, which refunds and the
+ # dashboard link cannot read from the order id alone.
+ def apply_settlement_metadata(payment, metadata)
+ super
+
+ capture = payment_method.captures(paypal_order).first
+ authorization = payment_method.authorizations(paypal_order).first
+ payment.metadata['paypal_capture_id'] = capture['id'] if capture
+ payment.metadata['paypal_authorization_id'] = authorization['id'] if authorization
+ end
end
end
diff --git a/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rb b/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rb
index fc0ac12820..2d504d21a8 100644
--- a/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rb
+++ b/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rb
@@ -11,6 +11,10 @@ module SpreePaypalCheckout
# A capture PayPal has taken, whether or not it was refunded since.
CAPTURED_STATUSES = %w[COMPLETED PARTIALLY_REFUNDED REFUNDED].freeze
+ # A capture that took or holds the money.
+ MOVED_CAPTURE_STATUSES = (CAPTURED_STATUSES + %w[PENDING]).freeze
+ # An authorization that holds or held the money.
+ MOVED_AUTHORIZATION_STATUSES = %w[CREATED PENDING PARTIALLY_CAPTURED CAPTURED].freeze
# An authorization that can still be captured or voided.
OPEN_AUTHORIZATION_STATUSES = %w[CREATED PARTIALLY_CAPTURED PENDING].freeze
# Transport failures where PayPal may or may not have acted on the request.
@@ -20,14 +24,17 @@ module SpreePaypalCheckout
# AUTHORIZATION_EXPIRED, …) kept apart from the message for callers that
# act on it.
class PaypalError < Spree::Core::GatewayError
- attr_reader :issue
+ attr_reader :issue, :status
- def initialize(message = nil, issue: nil)
+ def initialize(message = nil, issue: nil, status: nil)
super(message)
@issue = issue
+ @status = status
end
end
+ include SpreePaypalCheckout::Gateway::PaymentSessions
+
preference :client_id, :password
preference :client_secret, :password
# The credentials do not say which PayPal environment they belong to.
@@ -70,14 +77,20 @@ module SpreePaypalCheckout
Spree::PaymentSessions::PaypalCheckout
end
+ def payment_source_class
+ SpreePaypalCheckout::PaymentSources::Paypal
+ end
+
# No saved PayPal accounts in this release, so core never calls
# create_profile and passes no source to credit and void.
def payment_profiles_supported?
false
end
+ # Not offered for a currency PayPal does not take, nor for a total it
+ # would refuse, such as yen or forint with a fraction.
def available_for_order?(order)
- super && SpreePaypalCheckout::Amounts.supported_currency?(order.currency)
+ super && SpreePaypalCheckout::Amounts.payable?(order.total_minus_store_credits, order.currency)
end
# CAPTURE takes the money when the session completes; AUTHORIZE holds it
@@ -133,7 +146,11 @@ module SpreePaypalCheckout
capture = captures(paypal_order).first
if capture
raise_pending_capture(capture) if capture['status'] == 'PENDING'
- return success(order_id, paypal_order) if capture['status'].in?(CAPTURED_STATUSES)
+ if capture['status'].in?(CAPTURED_STATUSES)
+ response = already_captured(order_id, paypal_order, capture, money)
+ record_capture_id(gateway_options, capture['id'])
+ return response
+ end
end
authorization = open_authorization(paypal_order)
@@ -144,7 +161,9 @@ module SpreePaypalCheckout
end
case result['status']
- when 'COMPLETED' then success(order_id, result)
+ when 'COMPLETED'
+ record_capture_id(gateway_options, result['id'])
+ success(order_id, result)
when 'PENDING' then raise_pending_capture(result)
else
raise PaypalError.new(I18n.t('spree.paypal_checkout.errors.capture_not_completed', status: result['status']),
@@ -272,8 +291,7 @@ module SpreePaypalCheckout
#
# @raise [PaypalServerSdk::APIException] when PayPal refuses them
def request_access_token
- basic = ["#{preferred_client_id}:#{preferred_client_secret}"].pack('m0')
- client.o_auth_authorization.request_token('authorization' => "Basic #{basic}").data
+ client.oauth2.fetch_token
end
# Rebuilt when the credentials change, since it carries them.
@@ -306,6 +324,25 @@ module SpreePaypalCheckout
)
end
+ def captures(paypal_order)
+ payments_of(paypal_order, 'captures')
+ end
+
+ def authorizations(paypal_order)
+ payments_of(paypal_order, 'authorizations')
+ end
+
+ # Whether PayPal took the money, or holds a capture of it.
+ def capture_taken?(paypal_order)
+ captures(paypal_order).any? { |capture| capture['status'].in?(MOVED_CAPTURE_STATUSES) }
+ end
+
+ # Whether PayPal took or holds money against the order.
+ def money_moved?(paypal_order)
+ capture_taken?(paypal_order) ||
+ authorizations(paypal_order).any? { |authorization| authorization['status'].in?(MOVED_AUTHORIZATION_STATUSES) }
+ end
+
private
def read_back(gateway_options)
@@ -314,7 +351,7 @@ module SpreePaypalCheckout
return failure('Payment is missing a PayPal order') if payment.response_code.blank?
paypal_order = protect_from_error { paypal_order(payment.response_code) }
- return success(payment.response_code, paypal_order) if captures(paypal_order).any? || open_authorization(paypal_order)
+ return success(payment.response_code, paypal_order) if capture_taken?(paypal_order) || open_authorization(paypal_order)
failure(no_authorization_message(paypal_order))
end
@@ -330,12 +367,8 @@ module SpreePaypalCheckout
payments.find_by(number: payment_number) if payment_number.present?
end
- def captures(paypal_order)
- payments_of(paypal_order, 'captures')
- end
-
def open_authorization(paypal_order)
- payments_of(paypal_order, 'authorizations').find do |authorization|
+ authorizations(paypal_order).find do |authorization|
authorization['status'].in?(OPEN_AUTHORIZATION_STATUSES)
end
end
@@ -345,7 +378,7 @@ module SpreePaypalCheckout
end
def no_authorization_message(paypal_order)
- authorization = payments_of(paypal_order, 'authorizations').first
+ authorization = authorizations(paypal_order).first
if authorization
I18n.t('spree.paypal_checkout.errors.authorization_not_open', status: authorization['status'])
else
@@ -353,6 +386,33 @@ module SpreePaypalCheckout
end
end
+ # A capture an earlier request already made, perhaps one that timed out.
+ # It is only this capture if it took the amount now asked for.
+ def already_captured(order_id, paypal_order, capture, money)
+ return success(order_id, paypal_order) if amount_matches?(capture['amount'], money, money.currency)
+
+ captured = capture['amount'] || {}
+ raise Spree::Core::GatewayError, I18n.t('spree.paypal_checkout.errors.captured_other_amount',
+ captured: "#{captured['value']} #{captured['currency_code']}",
+ requested: "#{SpreePaypalCheckout::Amounts.to_paypal(money, money.currency)} #{money.currency.to_s.upcase}")
+ end
+
+ # @param paypal_amount [Hash, nil] an amount as PayPal writes it
+ def amount_matches?(paypal_amount, amount, currency)
+ paypal_amount = paypal_amount || {}
+ paypal_amount['currency_code'] == currency.to_s.upcase &&
+ paypal_amount['value'] == SpreePaypalCheckout::Amounts.to_paypal(amount, currency)
+ end
+
+ # Settlement records a capture only when checkout took one, so a capture
+ # made later records its own id for the dashboard link.
+ def record_capture_id(gateway_options, capture_id)
+ payment = find_payment(gateway_options)
+ return if payment.nil? || payment.metadata['paypal_capture_id'] == capture_id
+
+ payment.update_columns(metadata: payment.metadata.merge('paypal_capture_id' => capture_id))
+ end
+
def raise_pending_capture(capture)
reason = capture.dig('status_details', 'reason') || 'PENDING'
raise PaypalError.new(I18n.t('spree.paypal_checkout.errors.capture_pending', reason: reason), issue: reason)
@@ -366,8 +426,7 @@ module SpreePaypalCheckout
end
def paypal_money(money)
- currency = money.currency.to_s.upcase
- PaypalServerSdk::Money.new(currency_code: currency, value: SpreePaypalCheckout::Amounts.to_paypal(money, currency))
+ SpreePaypalCheckout::Amounts.to_paypal_money(money, money.currency)
end
def log_level
@@ -399,13 +458,16 @@ module SpreePaypalCheckout
# since PayPal may have acted on it.
def protect_from_error(money_moving: false)
yield
- rescue PaypalServerSdk::ErrorException => e
- detail = e.details.is_a?(Array) ? e.details.first : nil
- issue = detail&.issue || e.name
- description = detail&.description || e.message
- raise PaypalError.new([issue, description].compact.join(': '), issue: issue)
rescue PaypalServerSdk::APIException => e
- raise PaypalError, "PayPal: #{e.reason}"
+ message = e.is_a?(PaypalServerSdk::ErrorException) ? paypal_error_message(e) : "PayPal: #{e.message}"
+ # A server error or a request timeout says nothing about whether PayPal
+ # acted, even after the SDK's retries.
+ if money_moving && (e.response_code.to_i >= 500 || e.response_code.to_i == 408)
+ raise Spree::Core::AmbiguousGatewayError, I18n.t('spree.paypal_checkout.errors.outcome_unknown', message: message)
+ end
+
+ issue = paypal_issue(e) if e.is_a?(PaypalServerSdk::ErrorException)
+ raise PaypalError.new(message, issue: issue, status: e.response_code)
rescue CoreLibrary::AuthValidationException
raise Spree::Core::GatewayError, credentials_rejected_message
rescue *CONNECTION_ERRORS => e
@@ -413,6 +475,19 @@ module SpreePaypalCheckout
raise error_class, I18n.t('spree.paypal_checkout.errors.no_answer', message: e.message)
end
+ # PayPal's own issue code, such as INSTRUMENT_DECLINED, when it gave one.
+ def paypal_issue(error)
+ paypal_detail(error)&.issue || error.name
+ end
+
+ def paypal_error_message(error)
+ [paypal_issue(error), paypal_detail(error)&.description || error.message].compact.join(': ')
+ end
+
+ def paypal_detail(error)
+ error.details.first if error.details.is_a?(Array)
+ end
+
def success(authorization, full_response)
Spree::PaymentResponse.new(true, nil, full_response.as_json, authorization: authorization)
end
diff --git a/spree/providers/paypal/app/models/spree_paypal_checkout/gateway/payment_sessions.rb b/spree/providers/paypal/app/models/spree_paypal_checkout/gateway/payment_sessions.rb
new file mode 100644
index 0000000000..9db75ead43
--- /dev/null
+++ b/spree/providers/paypal/app/models/spree_paypal_checkout/gateway/payment_sessions.rb
@@ -0,0 +1,287 @@
+module SpreePaypalCheckout
+ class Gateway < ::Spree::Gateway
+ # A PayPal payment session is a PayPal order. Creating the session creates
+ # the order, the buyer approves it in PayPal's window, and completing the
+ # session captures or authorizes it. Until then the order is inert: nothing
+ # but this server can take money against it.
+ module PaymentSessions
+ extend ActiveSupport::Concern
+
+ # Written by the gem; a client's values for them are ignored.
+ OWNED_EXTERNAL_DATA_KEYS = %w[client_id intent attempt paypal_result].freeze
+ # The buyer's card or account was refused and PayPal lets them pick
+ # another in the same window, so the session stays open for them.
+ RECOVERABLE_DECLINE = 'INSTRUMENT_DECLINED'.freeze
+ # Answers that say nothing about the order: PayPal turned the request away
+ # before looking, or could not be reached at all.
+ RETRYABLE_STATUS_CODES = [401, 408, 429].freeze
+
+ # Opens a new session on every call, canceling the cart's open PayPal
+ # sessions first so only one order can ever be paid.
+ #
+ # @param order [Spree::Cart, Spree::Order]
+ # @return [Spree::PaymentSessions::PaypalCheckout]
+ # @raise [Spree::Core::GatewayError] for a zero amount, an amount PayPal
+ # cannot take, or a cart this method has already been paid for
+ def create_payment_session(order:, amount: nil, external_data: {})
+ total = amount.present? ? BigDecimal(amount.to_s) : order.total_minus_store_credits
+ raise Spree::Core::GatewayError, I18n.t('spree.paypal_checkout.payment_session_errors.zero_amount') unless total.positive?
+
+ SpreePaypalCheckout::Amounts.to_paypal(total, order.currency)
+ replace_open_sessions(order)
+
+ intent = paypal_intent
+ presenter = SpreePaypalCheckout::OrderPresenter.new(order: order, amount: total, intent: intent)
+ paypal_order = protect_from_error { create_paypal_order(presenter.order_request) }
+
+ payment_session_class.create!(
+ owner: order,
+ payment_method: self,
+ amount: total,
+ currency: order.currency,
+ status: 'pending',
+ external_id: paypal_order['id'],
+ customer: order.customer,
+ # The JS SDK must load with the client id that created the order and
+ # the order's own intent, or PayPal's buttons refuse it.
+ external_data: client_external_data(external_data).merge(
+ 'client_id' => preferred_client_id,
+ 'intent' => intent
+ )
+ )
+ end
+
+ # A new amount is sent to PayPal before the session takes it, so PayPal
+ # never captures a total Spree no longer charges. The whole purchase unit
+ # is replaced: items and breakdown come and go with whether they add up.
+ def update_payment_session(payment_session:, amount: nil, external_data: {})
+ attrs = {}
+
+ new_amount = BigDecimal(amount.to_s) if amount.present?
+ if new_amount && new_amount != payment_session.amount
+ presenter = SpreePaypalCheckout::OrderPresenter.new(
+ order: payment_session.owner, amount: new_amount, intent: payment_session.intent || paypal_intent
+ )
+ protect_from_error { patch_paypal_order(payment_session.external_id, presenter.purchase_unit) }
+ attrs[:amount] = new_amount
+ end
+
+ data = client_external_data(external_data)
+ attrs[:external_data] = (payment_session.external_data || {}).merge(data) if data.any?
+
+ payment_session.update!(attrs) if attrs.any?
+ end
+
+ # Captures or authorizes the order the buyer approved, then settles the
+ # payment. Does NOT complete the cart: the storefront's cart-complete
+ # call or the webhook handler does that.
+ #
+ # @raise [Spree::Core::GatewayError] when the session is not open, or
+ # PayPal declines; a recoverable decline leaves the session open
+ def complete_payment_session(payment_session:, params: {})
+ unless payment_session.pending? || payment_session.processing?
+ raise Spree::Core::GatewayError, I18n.t('spree.paypal_checkout.payment_session_errors.not_open')
+ end
+
+ paypal_order = protect_from_error { paypal_order(payment_session.external_id) }
+
+ # A capture that timed out may have gone through; it is settled, not
+ # taken again.
+ unless money_moved?(paypal_order)
+ unless order_matches_session?(paypal_order, payment_session)
+ payment_session.fail if payment_session.can_fail?
+ return payment_session
+ end
+
+ paypal_order = move_money(payment_session)
+ end
+
+ settle(payment_session, paypal_order)
+ end
+
+ # A session that never reached Complete is canceled here alone: its order
+ # can only ever be paid by this server. Otherwise the order is read,
+ # since a capture that timed out may have gone through.
+ #
+ # @return [Boolean] whether the session was canceled
+ # @raise [Spree::Core::GatewayError] when PayPal has taken the money
+ # @raise [StandardError] PayPal's own error when it could not be asked
+ def cancel_payment_session(payment_session:)
+ return payment_session.cancel unless payment_session.complete_attempted?
+
+ paypal_order = paypal_order(payment_session.external_id)
+
+ if capture_taken?(paypal_order)
+ raise Spree::Core::GatewayError, I18n.t('spree.paypal_checkout.payment_session_errors.payment_captured')
+ end
+
+ authorization = open_authorization(paypal_order)
+ void_authorization(authorization['id'], request_id: "#{payment_session.prefixed_id}-void") if authorization
+
+ payment_session.cancel
+ rescue PaypalServerSdk::ErrorException => e
+ raise if retryable_paypal_error?(e)
+ # An order the account the credentials now reach does not know can no
+ # longer be paid.
+ return payment_session.cancel if e.response_code == 404
+
+ raise Spree::Core::GatewayError, paypal_error_message(e)
+ end
+
+ # @return [Hash] the created order
+ def create_paypal_order(order_request)
+ client.orders.create_order('body' => order_request, 'prefer' => 'return=minimal').data.to_hash
+ end
+
+ def patch_paypal_order(paypal_order_id, purchase_unit)
+ client.orders.patch_order(
+ 'id' => paypal_order_id,
+ 'body' => [
+ PaypalServerSdk::Patch.new(
+ op: PaypalServerSdk::PatchOp::REPLACE,
+ path: "/purchase_units/@reference_id=='default'",
+ value: purchase_unit.to_hash
+ )
+ ]
+ )
+ end
+
+ # @return [Hash] the order, with its capture
+ def capture_paypal_order(paypal_order_id, request_id:)
+ client.orders.capture_order(
+ 'id' => paypal_order_id,
+ 'paypal_request_id' => request_id,
+ 'prefer' => 'return=representation'
+ ).data.to_hash
+ end
+
+ # @return [Hash] the order, with its authorization
+ def authorize_paypal_order(paypal_order_id, request_id:)
+ client.orders.authorize_order(
+ 'id' => paypal_order_id,
+ 'paypal_request_id' => request_id,
+ 'prefer' => 'return=representation'
+ ).data.to_hash
+ end
+
+ private
+
+ # The attempt is stored before PayPal is asked, so a cancel after a
+ # timeout knows to look at the order, and a retry of the same attempt
+ # reaches PayPal as the same request.
+ def move_money(payment_session)
+ attempt = payment_session.attempt
+ payment_session.update!(external_data: payment_session.external_data.merge('attempt' => attempt))
+ action = payment_session.intent == PaypalServerSdk::CheckoutPaymentIntent::AUTHORIZE ? 'authorize' : 'capture'
+ request_id = "#{payment_session.prefixed_id}-#{action}-#{attempt}"
+
+ paypal_order = protect_from_error(money_moving: true) do
+ action == 'authorize' ? authorize_paypal_order(payment_session.external_id, request_id: request_id) : capture_paypal_order(payment_session.external_id, request_id: request_id)
+ end
+ return paypal_order if money_moved?(paypal_order)
+
+ payment_session.fail if payment_session.can_fail?
+ status = payment_status(paypal_order)
+ raise PaypalError.new(I18n.t('spree.paypal_checkout.payment_session_errors.declined', status: status), issue: status)
+ rescue PaypalError => e
+ if e.issue == RECOVERABLE_DECLINE
+ payment_session.update!(external_data: payment_session.external_data.merge('attempt' => attempt + 1))
+ elsif !e.status.to_i.in?(RETRYABLE_STATUS_CODES) && payment_session.reload.can_fail?
+ # A rate limit or a refused token is not a decline: the buyer can
+ # complete the same session again.
+ payment_session.fail
+ end
+ raise
+ end
+
+ # Once money has moved the session is never failed: a failed session
+ # lets the storefront open another and charge again.
+ def settle(payment_session, paypal_order)
+ payment_session.paypal_order = paypal_order
+ payment_session.update!(
+ external_data: payment_session.external_data.merge('paypal_result' => paypal_result(paypal_order))
+ )
+ report_amount_mismatch(payment_session, paypal_order)
+
+ payment_session.process if payment_session.can_process?
+ capture = captures(paypal_order).first
+ payment_session.settle_payment!(captured: capture.present? && capture['status'] == 'COMPLETED')
+ payment_session.complete unless payment_session.completed?
+ payment_session
+ end
+
+ def order_matches_session?(paypal_order, payment_session)
+ amount_matches?(Array(paypal_order['purchase_units']).first&.dig('amount'), payment_session.amount, payment_session.currency)
+ end
+
+ def report_amount_mismatch(payment_session, paypal_order)
+ moved = first_payment(paypal_order)
+ return if moved.nil? || amount_matches?(moved['amount'], payment_session.amount, payment_session.currency)
+
+ expected = SpreePaypalCheckout::Amounts.to_paypal(payment_session.amount, payment_session.currency)
+
+ Rails.error.report(
+ Spree::Core::GatewayError.new(
+ "PayPal took #{moved.dig('amount', 'value')} #{moved.dig('amount', 'currency_code')} " \
+ "for a session of #{expected} #{payment_session.currency.upcase}"
+ ),
+ context: { payment_session_id: payment_session.id, paypal_order_id: payment_session.external_id },
+ source: 'spree_paypal_checkout.complete_payment_session'
+ )
+ end
+
+ def paypal_result(paypal_order)
+ capture = captures(paypal_order).first
+ authorization = authorizations(paypal_order).first
+ {
+ 'status' => paypal_order['status'],
+ 'capture_id' => capture&.dig('id'),
+ 'capture_status' => capture&.dig('status'),
+ 'authorization_id' => authorization&.dig('id'),
+ 'authorization_status' => authorization&.dig('status')
+ }.compact
+ end
+
+ def payment_status(paypal_order)
+ first_payment(paypal_order)&.dig('status') || paypal_order['status']
+ end
+
+ def first_payment(paypal_order)
+ captures(paypal_order).first || authorizations(paypal_order).first
+ end
+
+ # Only the payable ones are canceled; a failed session's order can no
+ # longer be completed by anyone.
+ def replace_open_sessions(order)
+ sessions = order.payment_sessions.where(payment_method: self)
+ if sessions.exists?(status: 'completed')
+ raise Spree::Core::GatewayError, I18n.t('spree.paypal_checkout.payment_session_errors.payment_in_progress')
+ end
+
+ sessions.active.order(:id).each do |payment_session|
+ cancel_payment_session(payment_session: payment_session)
+ end
+ rescue Spree::Core::GatewayError
+ raise
+ rescue StandardError => e
+ raise unless retryable_error?(e)
+
+ # Checkout speaks GatewayError. The unused-session job does not: it
+ # retries these, and has to see them unwrapped.
+ raise Spree::Core::GatewayError, e.message
+ end
+
+ def retryable_error?(error)
+ error.is_a?(PaypalServerSdk::ErrorException) ? retryable_paypal_error?(error) : error.is_a?(Faraday::Error) || error.is_a?(CoreLibrary::AuthValidationException)
+ end
+
+ def retryable_paypal_error?(error)
+ error.response_code.in?(RETRYABLE_STATUS_CODES) || error.response_code.to_i >= 500
+ end
+
+ def client_external_data(external_data)
+ external_data.to_h.stringify_keys.except(*OWNED_EXTERNAL_DATA_KEYS)
+ end
+ end
+ end
+end
diff --git a/spree/providers/paypal/app/models/spree_paypal_checkout/payment_sources/paypal.rb b/spree/providers/paypal/app/models/spree_paypal_checkout/payment_sources/paypal.rb
new file mode 100644
index 0000000000..0a689c3d5f
--- /dev/null
+++ b/spree/providers/paypal/app/models/spree_paypal_checkout/payment_sources/paypal.rb
@@ -0,0 +1,55 @@
+module SpreePaypalCheckout
+ module PaymentSources
+ # What the buyer paid with in PayPal's window: a PayPal or Venmo account, or
+ # a card typed in by a buyer without one. A card is kept here rather than as
+ # a Spree::CreditCard: PayPal issues no reusable card id without vaulting,
+ # so it could never be charged again and must not appear among saved cards.
+ class Paypal < ::Spree::PaymentSource
+ WALLETS = %w[paypal venmo].freeze
+
+ store_accessor :metadata, :wallet, :email, :name, :account_id, :account_status, :brand, :last_digits
+
+ # @param payment_source [Hash, nil] the PayPal order's `payment_source`
+ # @param payment_method [SpreePaypalCheckout::Gateway]
+ # @param customer [Spree::Customer, nil]
+ # @param paypal_order_id [String] keys the source
+ # @return [Paypal, nil] nil for a kind the gem does not model
+ def self.for_payment_source(payment_source, payment_method:, customer:, paypal_order_id:)
+ kind, details = Hash(payment_source).find { |key, value| (WALLETS + ['card']).include?(key) && value.is_a?(Hash) }
+ return if kind.nil?
+
+ metadata = if kind == 'card'
+ { 'name' => details['name'], 'brand' => details['brand'], 'last_digits' => details['last_digits'] }
+ else
+ {
+ 'email' => details['email_address'],
+ 'name' => paypal_name(details['name']),
+ 'account_id' => details['account_id'],
+ 'account_status' => details['account_status'],
+ 'user_name' => details['user_name']
+ }
+ end
+
+ # One source per PayPal order: nothing is saved at PayPal to reuse,
+ # and a source shared by account would show one customer's payment
+ # under another who paid with the same PayPal account.
+ source = find_or_initialize_by(payment_method: payment_method, gateway_payment_profile_id: "#{kind}-#{paypal_order_id}")
+ source.customer ||= customer
+ source.metadata = { 'wallet' => kind }.merge(metadata.compact)
+ source.save!
+ source
+ end
+
+ def self.paypal_name(name)
+ return name if name.is_a?(String)
+ return if name.blank?
+
+ [name['given_name'], name['surname']].compact.join(' ').presence || name['full_name']
+ end
+
+ def self.display_name
+ 'PayPal'
+ end
+ end
+ end
+end
diff --git a/spree/providers/paypal/config/locales/en.yml b/spree/providers/paypal/config/locales/en.yml
index cbe7edf7c7..9c8b583e9e 100644
--- a/spree/providers/paypal/config/locales/en.yml
+++ b/spree/providers/paypal/config/locales/en.yml
@@ -4,12 +4,20 @@ en:
paypal_checkout:
errors:
authorization_not_open: "PayPal can no longer capture this payment: its authorization is %{status}."
+ captured_other_amount: "PayPal already captured %{captured} on this order, not the %{requested} asked for."
capture_not_completed: "PayPal did not complete the capture (status %{status})."
capture_pending: "PayPal is holding this capture: %{reason}. It completes when PayPal releases it."
credentials_rejected: "PayPal %{environment} rejected this client id and secret — check that Test mode matches the credentials."
no_answer: "PayPal did not answer: %{message}"
nothing_to_capture: "This PayPal order has no authorization to capture (order status %{status})."
nothing_to_refund: "This PayPal order has no capture to refund."
+ outcome_unknown: "PayPal could not say whether it took the payment: %{message}"
paypal_unavailable: "PayPal could not be reached to check the client id and secret. Try again later."
void_captured: "PayPal has already captured this payment; refund it instead."
void_pending_capture: "PayPal is still holding a capture on this payment; refund it once it completes."
+ payment_session_errors:
+ declined: "PayPal declined the payment (status %{status})."
+ not_open: "This PayPal payment session can no longer be completed."
+ payment_captured: "PayPal has already taken the money for this session."
+ payment_in_progress: "A PayPal payment for this checkout is already in progress."
+ zero_amount: "Payment session amount must be greater than zero"
diff --git a/spree/providers/paypal/spec/models/spree/payment_sessions/paypal_checkout_spec.rb b/spree/providers/paypal/spec/models/spree/payment_sessions/paypal_checkout_spec.rb
new file mode 100644
index 0000000000..f6337ffb86
--- /dev/null
+++ b/spree/providers/paypal/spec/models/spree/payment_sessions/paypal_checkout_spec.rb
@@ -0,0 +1,89 @@
+require 'spec_helper'
+
+RSpec.describe Spree::PaymentSessions::PaypalCheckout do
+ let(:store) { @default_store }
+ let(:gateway) { create(:paypal_checkout_gateway, store: store) }
+ let(:cart) { create(:cart_with_line_items, store: store) }
+ let(:payment_session) { create(:paypal_checkout_payment_session, owner: cart, payment_method: gateway, external_id: 'ORDER1234567890AB') }
+
+ it 'keeps the 5.x stored class name' do
+ expect(described_class.name).to eq('Spree::PaymentSessions::PaypalCheckout')
+ end
+
+ it 'reads the client id and intent the gem wrote' do
+ expect(payment_session.external_data['client_id']).to eq('paypal_client_id_test')
+ expect(payment_session.intent).to eq('CAPTURE')
+ end
+
+ describe '#attempt' do
+ it 'starts at one' do
+ expect(payment_session.attempt).to eq(1)
+ end
+
+ it 'reads the stored attempt' do
+ payment_session.external_data = payment_session.external_data.merge('attempt' => 3)
+
+ expect(payment_session.attempt).to eq(3)
+ end
+ end
+
+ describe '#complete_attempted?' do
+ it 'is false before Complete asked PayPal for anything' do
+ expect(payment_session).not_to be_complete_attempted
+ end
+
+ it 'is true once an attempt is recorded' do
+ payment_session.external_data = payment_session.external_data.merge('attempt' => 1)
+
+ expect(payment_session).to be_complete_attempted
+ end
+ end
+
+ describe '#prepare_for_settlement!' do
+ it 'fetches the PayPal order once, outside the lock' do
+ allow(gateway).to receive(:paypal_order).and_return(paypal_order_data)
+
+ payment_session.prepare_for_settlement!
+ payment_session.paypal_order
+
+ expect(gateway).to have_received(:paypal_order).once.with('ORDER1234567890AB')
+ end
+
+ it 'asks PayPal for nothing once the session has its payment' do
+ create(:payment, cart: cart, order: nil, payment_method: gateway, amount: cart.total, response_code: 'ORDER1234567890AB')
+ allow(gateway).to receive(:paypal_order)
+
+ payment_session.prepare_for_settlement!
+
+ expect(gateway).not_to have_received(:paypal_order)
+ end
+ end
+
+ describe 'settlement' do
+ before { payment_session.paypal_order = paypal_order_data(captures: [paypal_capture], extra: { 'payment_source' => source }) }
+
+ let(:source) { { 'venmo' => { 'email_address' => '[email protected]', 'account_id' => 'VENMO123', 'user_name' => 'buyer' } } }
+
+ it 'builds the PayPal source from the order' do
+ built = payment_session.payment_source_for_settlement
+
+ expect(built.wallet).to eq('venmo')
+ expect(built.email).to eq('[email protected]')
+ end
+
+ it 'records the capture id' do
+ payment = Spree::Payment.new
+ payment_session.apply_settlement_metadata(payment, { 'note' => 'kept' })
+
+ expect(payment.metadata).to eq('note' => 'kept', 'paypal_capture_id' => 'CAPTURE123456789A')
+ end
+
+ it 'records the authorization id' do
+ payment_session.paypal_order = paypal_order_data(authorizations: [paypal_authorization])
+ payment = Spree::Payment.new
+ payment_session.apply_settlement_metadata(payment, {})
+
+ expect(payment.metadata).to eq('paypal_authorization_id' => 'AUTHORIZ123456789')
+ end
+ end
+end
diff --git a/spree/providers/paypal/spec/models/spree_paypal_checkout/gateway/payment_sessions_spec.rb b/spree/providers/paypal/spec/models/spree_paypal_checkout/gateway/payment_sessions_spec.rb
new file mode 100644
index 0000000000..af1a418956
--- /dev/null
+++ b/spree/providers/paypal/spec/models/spree_paypal_checkout/gateway/payment_sessions_spec.rb
@@ -0,0 +1,453 @@
+require 'spec_helper'
+
+RSpec.describe SpreePaypalCheckout::Gateway::PaymentSessions do
+ let(:store) { @default_store }
+ let(:gateway) { create(:paypal_checkout_gateway, store: store, capture_method: 'checkout') }
+ let(:cart) { create(:cart_ready_for_delivery, store: store, line_items_count: 1, line_items_price: BigDecimal('10')) }
+ let(:paypal_order_id) { 'ORDER1234567890AB' }
+
+ def session_for(cart, **attrs)
+ create(:paypal_checkout_payment_session, owner: cart, payment_method: gateway, amount: cart.total, **attrs)
+ end
+
+ def approved_order(amount: format('%.2f', cart.total), currency: 'USD', **attrs)
+ paypal_order_data(id: paypal_order_id, status: 'APPROVED', **attrs).tap do |order|
+ order['purchase_units'].first['amount'] = { 'currency_code' => currency, 'value' => amount }
+ end
+ end
+
+ def captured_order(status: 'COMPLETED', reason: nil, value: format('%.2f', cart.total), payment_source: nil)
+ approved_order(
+ status: 'COMPLETED',
+ captures: [paypal_capture(status: status, reason: reason, value: value)],
+ extra: payment_source ? { 'payment_source' => payment_source } : {}
+ )
+ end
+
+ describe '#create_payment_session' do
+ subject(:payment_session) { gateway.create_payment_session(order: cart, external_data: external_data) }
+
+ let(:external_data) { {} }
+
+ before do
+ allow(gateway).to receive(:create_paypal_order).and_return({ 'id' => paypal_order_id, 'status' => 'CREATED' })
+ end
+
+ it 'creates the PayPal order and stores its id, the client id and the intent' do
+ expect(payment_session).to be_persisted
+ expect(payment_session.external_id).to eq(paypal_order_id)
+ expect(payment_session.amount).to eq(cart.total)
+ expect(payment_session.external_data).to eq('client_id' => 'paypal_client_id_test', 'intent' => 'CAPTURE')
+ end
+
+ it 'sends the order the presenter builds' do
+ payment_session
+
+ expect(gateway).to have_received(:create_paypal_order) do |order_request|
+ expect(order_request.to_hash['intent']).to eq('CAPTURE')
+ expect(order_request.to_hash['purchase_units'].first['custom_id']).to eq(cart.prefixed_id)
+ end
+ end
+
+ context 'with a method that captures on dispatch' do
+ let(:gateway) { create(:paypal_checkout_gateway, store: store, capture_method: 'on_dispatch') }
+
+ it 'asks for an authorization' do
+ expect(payment_session.intent).to eq('AUTHORIZE')
+ end
+ end
+
+ context 'when the client sends values for keys the gem owns' do
+ let(:external_data) { { 'client_id' => 'forged', 'intent' => 'AUTHORIZE', 'attempt' => 7, 'note' => 'kept' } }
+
+ it 'ignores them and keeps the rest' do
+ expect(payment_session.external_data).to eq(
+ 'client_id' => 'paypal_client_id_test', 'intent' => 'CAPTURE', 'note' => 'kept'
+ )
+ end
+ end
+
+ it 'refuses a zero amount' do
+ expect { gateway.create_payment_session(order: cart, amount: '0') }.
+ to raise_error(Spree::Core::GatewayError, 'Payment session amount must be greater than zero')
+ end
+
+ it 'refuses a cart that already has a completed PayPal session' do
+ session_for(cart, status: 'completed')
+
+ expect { payment_session }.to raise_error(Spree::Core::GatewayError, /already in progress/)
+ expect(gateway).not_to have_received(:create_paypal_order)
+ end
+
+ it 'cancels the open sessions it replaces' do
+ earlier = session_for(cart, external_id: 'EARLIERORDER12345')
+
+ payment_session
+
+ expect(earlier.reload).to be_canceled
+ end
+
+ it 'turns PayPal being unreachable while replacing a session into a gateway error' do
+ session_for(cart, external_id: 'EARLIERORDER12345', external_data: { 'attempt' => 1 })
+ allow(gateway).to receive(:paypal_order).and_raise(Faraday::ConnectionFailed, 'refused')
+
+ expect { payment_session }.to raise_error(Spree::Core::GatewayError, 'refused')
+ end
+
+ it 'creates an order with the CAPTURE intent and a fixed shipping address', vcr: { cassette_name: 'create_order_capture' } do
+ allow(gateway).to receive(:create_paypal_order).and_call_original
+
+ expect(payment_session.external_id).to be_present
+ end
+
+ context 'with a digital cart and an authorizing method' do
+ let(:gateway) { create(:paypal_checkout_gateway, store: store, capture_method: 'on_dispatch') }
+ let(:cart) { create(:cart_with_line_items, store: store, line_items_price: BigDecimal('10')) }
+
+ it 'creates an order with the AUTHORIZE intent and no shipping', vcr: { cassette_name: 'create_order_authorize' } do
+ allow(gateway).to receive(:create_paypal_order).and_call_original
+ allow(cart).to receive(:shipping_address_required?).and_return(false)
+
+ expect(payment_session.external_id).to be_present
+ expect(payment_session.intent).to eq('AUTHORIZE')
+ end
+ end
+ end
+
+ describe '#update_payment_session' do
+ let(:payment_session) { session_for(cart, external_id: paypal_order_id) }
+
+ before { allow(gateway).to receive(:patch_paypal_order) }
+
+ it 'replaces the purchase unit at PayPal before taking the new amount' do
+ gateway.update_payment_session(payment_session: payment_session, amount: '25.00')
+
+ expect(gateway).to have_received(:patch_paypal_order) do |order_id, purchase_unit|
+ expect(order_id).to eq(paypal_order_id)
+ expect(purchase_unit.to_hash['amount']['value']).to eq('25.00')
+ end
+ expect(payment_session.reload.amount).to eq(BigDecimal('25'))
+ end
+
+ it 'keeps the old amount when PayPal refuses the patch' do
+ allow(gateway).to receive(:patch_paypal_order).and_raise(paypal_error('ORDER_ALREADY_CAPTURED'))
+
+ expect { gateway.update_payment_session(payment_session: payment_session, amount: '25.00') }.
+ to raise_error(Spree::Core::GatewayError, /ORDER_ALREADY_CAPTURED/)
+ expect(payment_session.reload.amount).to eq(cart.total)
+ end
+
+ it 'leaves PayPal alone when the amount did not change' do
+ gateway.update_payment_session(payment_session: payment_session, amount: cart.total.to_s)
+
+ expect(gateway).not_to have_received(:patch_paypal_order)
+ end
+
+ it 'ignores values for keys the gem owns' do
+ gateway.update_payment_session(payment_session: payment_session, external_data: { 'intent' => 'AUTHORIZE', 'note' => 'x' })
+
+ expect(payment_session.reload.external_data).to include('intent' => 'CAPTURE', 'note' => 'x')
+ end
+
+ it 'patches the amount against PayPal', vcr: { cassette_name: 'update_order_amount' } do
+ allow(gateway).to receive(:patch_paypal_order).and_call_original
+ # Recording needs an order this method created; PAYPAL_CREATED_ORDER_ID names it.
+ payment_session.update_columns(external_id: ENV.fetch('PAYPAL_CREATED_ORDER_ID', paypal_order_id))
+
+ gateway.update_payment_session(payment_session: payment_session, amount: (cart.total + 1).to_s)
+
+ expect(payment_session.reload.amount).to eq(cart.total + 1)
+ end
+ end
+
+ describe '#complete_payment_session' do
+ subject(:complete) { gateway.complete_payment_session(payment_session: payment_session) }
+
+ let(:payment_session) { session_for(cart, external_id: paypal_order_id) }
+ let(:wallet) do
+ { 'paypal' => { 'email_address' => '[email protected]', 'account_id' => 'PAYERID1234', 'account_status' => 'VERIFIED',
+ 'name' => { 'given_name' => 'Ada', 'surname' => 'Lovelace' } } }
+ end
+
+ before { allow(gateway).to receive(:paypal_order).with(paypal_order_id).and_return(approved_order) }
+
+ it 'captures with a request id for this attempt and settles a captured payment' do
+ allow(gateway).to receive(:capture_paypal_order).and_return(captured_order(payment_source: wallet))
+
+ complete
+
+ expect(gateway).to have_received(:capture_paypal_order).
+ with(paypal_order_id, request_id: "#{payment_session.prefixed_id}-capture-1")
+ expect(payment_session.reload).to be_completed
+ payment = payment_session.payment
+ expect(payment).to be_completed
+ expect(payment.response_code).to eq(paypal_order_id)
+ expect(payment.metadata['paypal_capture_id']).to eq('CAPTURE123456789A')
+ expect(payment.source).to be_a(SpreePaypalCheckout::PaymentSources::Paypal)
+ expect(payment.source.email).to eq('[email protected]')
+ expect(payment_session.external_data).to include(
+ 'client_id' => 'paypal_client_id_test', 'intent' => 'CAPTURE',
+ 'paypal_result' => include('capture_id' => 'CAPTURE123456789A', 'capture_status' => 'COMPLETED')
+ )
+ end
+
+ it 'never completes the cart' do
+ allow(gateway).to receive(:capture_paypal_order).and_return(captured_order)
+
+ expect { complete }.not_to(change { Spree::Order.count })
+ end
+
+ it 'settles a capture PayPal holds as pending without taking it' do
+ allow(gateway).to receive(:capture_paypal_order).and_return(captured_order(status: 'PENDING', reason: 'ECHECK'))
+
+ complete
+
+ expect(payment_session.reload).to be_completed
+ expect(payment_session.payment).to be_present
+ expect(payment_session.payment).not_to be_completed
+ end
+
+ context 'with an authorizing session' do
+ let(:payment_session) do
+ session_for(cart, external_id: paypal_order_id, external_data: { 'client_id' => 'x', 'intent' => 'AUTHORIZE' })
+ end
+
+ it 'authorizes and settles a pending payment' do
+ allow(gateway).to receive(:authorize_paypal_order).
+ and_return(approved_order(status: 'COMPLETED', authorizations: [paypal_authorization(value: format('%.2f', cart.total))]))
+
+ complete
+
+ expect(gateway).to have_received(:authorize_paypal_order).
+ with(paypal_order_id, request_id: "#{payment_session.prefixed_id}-authorize-1")
+ payment = payment_session.reload.payment
+ expect(payment).to be_pending
+ expect(payment.metadata['paypal_authorization_id']).to eq('AUTHORIZ123456789')
+ end
+ end
+
+ it 'fails the session without moving money when the order amount differs' do
+ allow(gateway).to receive(:paypal_order).and_return(approved_order(amount: '1.00'))
+ allow(gateway).to receive(:capture_paypal_order)
+
+ complete
+
+ expect(payment_session.reload).to be_failed
+ expect(gateway).not_to have_received(:capture_paypal_order)
+ end
+
+ it 'fails the session without moving money when the currency differs' do
+ allow(gateway).to receive(:paypal_order).and_return(approved_order(currency: 'EUR'))
+ allow(gateway).to receive(:capture_paypal_order)
+
+ complete
+
+ expect(payment_session.reload).to be_failed
+ expect(gateway).not_to have_received(:capture_paypal_order)
+ end
+
+ it 'settles and reports a captured amount that still differs' do
+ allow(gateway).to receive(:capture_paypal_order).and_return(captured_order(value: '9.99'))
+ allow(Rails.error).to receive(:report)
+
+ complete
+
+ expect(payment_session.reload).to be_completed
+ expect(Rails.error).to have_received(:report).with(
+ an_instance_of(Spree::Core::GatewayError), hash_including(source: 'spree_paypal_checkout.complete_payment_session')
+ )
+ end
+
+ it 'settles an order a timed-out capture already took, without capturing again' do
+ allow(gateway).to receive(:paypal_order).and_return(captured_order)
+ allow(gateway).to receive(:capture_paypal_order)
+
+ complete
+
+ expect(payment_session.reload).to be_completed
+ expect(gateway).not_to have_received(:capture_paypal_order)
+ end
+
+ context 'when PayPal declines the funding source' do
+ before { allow(gateway).to receive(:capture_paypal_order).and_raise(paypal_error('INSTRUMENT_DECLINED')) }
+
+ it 'leaves the session open for another try and moves the attempt on' do
+ expect { complete }.to raise_error(Spree::Core::GatewayError, /INSTRUMENT_DECLINED/)
+
+ expect(payment_session.reload).to be_pending
+ expect(payment_session.attempt).to eq(2)
+ end
+
+ it 'sends the next try as a new request' do
+ expect { complete }.to raise_error(Spree::Core::GatewayError)
+ allow(gateway).to receive(:capture_paypal_order).and_return(captured_order)
+
+ gateway.complete_payment_session(payment_session: payment_session.reload)
+
+ expect(gateway).to have_received(:capture_paypal_order).
+ with(paypal_order_id, request_id: "#{payment_session.prefixed_id}-capture-2")
+ end
+ end
+
+ it 'fails the session on any other decline' do
+ allow(gateway).to receive(:capture_paypal_order).and_raise(paypal_error('ORDER_NOT_APPROVED'))
+
+ expect { complete }.to raise_error(Spree::Core::GatewayError, /ORDER_NOT_APPROVED/)
+ expect(payment_session.reload).to be_failed
+ end
+
+ it 'fails the session when the capture comes back declined' do
+ allow(gateway).to receive(:capture_paypal_order).and_return(captured_order(status: 'DECLINED'))
+
+ expect { complete }.to raise_error(Spree::Core::GatewayError, 'PayPal declined the payment (status DECLINED).')
+ expect(payment_session.reload).to be_failed
+ end
+
+ it 'leaves the session open and reports an ambiguous error when the capture gets no answer' do
+ allow(gateway).to receive(:capture_paypal_order).and_raise(Faraday::TimeoutError, 'timed out')
+
+ expect { complete }.to raise_error(Spree::Core::AmbiguousGatewayError)
+ expect(payment_session.reload).to be_pending
+ expect(payment_session.attempt).to eq(1)
+ expect(payment_session).to be_complete_attempted
+ end
+
+ it 'leaves the session open and reports an ambiguous error when PayPal answers with a server error' do
+ allow(gateway).to receive(:capture_paypal_order).and_raise(paypal_error('INTERNAL_SERVER_ERROR', status: 503))
+
+ expect { complete }.to raise_error(Spree::Core::AmbiguousGatewayError)
+ expect(payment_session.reload).to be_pending
+ expect(payment_session.attempt).to eq(1)
+ end
+
+ it 'leaves the session open when PayPal turns the request away before looking at it' do
+ allow(gateway).to receive(:capture_paypal_order).and_raise(paypal_error('RATE_LIMIT_REACHED', status: 429))
+
+ expect { complete }.to raise_error(Spree::Core::GatewayError, /RATE_LIMIT_REACHED/)
+ expect(payment_session.reload).to be_pending
+ end
+
+ it 'refuses a session that is not open' do
+ payment_session.update_columns(status: 'failed')
+ allow(gateway).to receive(:capture_paypal_order)
+
+ expect { complete }.to raise_error(Spree::Core::GatewayError, /can no longer be completed/)
+ expect(gateway).not_to have_received(:capture_paypal_order)
+ end
+
+ context 'against PayPal' do
+ # Recording needs a 10.00 USD order a sandbox buyer approved by hand.
+ let(:cart) { create(:cart_with_line_items, store: store, line_items_price: BigDecimal('10')) }
+
+ before do
+ allow(gateway).to receive(:paypal_order).and_call_original
+ payment_session.update_columns(amount: BigDecimal('10'), external_id: recorded_order_id)
+ end
+
+ context 'when capturing', vcr: { cassette_name: 'complete_capture' } do
+ let(:recorded_order_id) { ENV.fetch('PAYPAL_APPROVED_CAPTURE_ORDER_ID', paypal_order_id) }
+
+ it 'captures the approved order' do
+ gateway.complete_payment_session(payment_session: payment_session.reload)
+
+ expect(payment_session.reload).to be_completed
+ expect(payment_session.payment).to be_completed
+ end
+ end
+
+ context 'when authorizing', vcr: { cassette_name: 'complete_authorize' } do
+ let(:recorded_order_id) { ENV.fetch('PAYPAL_APPROVED_AUTHORIZE_ORDER_ID', paypal_order_id) }
+
+ it 'authorizes the approved order' do
+ payment_session.update_columns(external_data: { 'client_id' => 'x', 'intent' => 'AUTHORIZE' })
+
+ gateway.complete_payment_session(payment_session: payment_session.reload)
+
+ expect(payment_session.reload.payment).to be_pending
+ end
+ end
+
+ context 'when the funding source is declined', vcr: { cassette_name: 'complete_instrument_declined' } do
+ let(:recorded_order_id) { ENV.fetch('PAYPAL_APPROVED_DECLINED_ORDER_ID', paypal_order_id) }
+
+ it 'keeps the session open' do
+ # PayPal's sandbox negative testing forces the decline while recording.
+ allow(gateway.client.orders).to receive(:capture_order).and_wrap_original do |original, options|
+ original.call(options.merge('paypal_mock_response' => '{"mock_application_codes":"INSTRUMENT_DECLINED"}'))
+ end
+
+ expect { gateway.complete_payment_session(payment_session: payment_session.reload) }.
+ to raise_error(Spree::Core::GatewayError, /INSTRUMENT_DECLINED/)
+ expect(payment_session.reload).to be_pending
+ end
+ end
+ end
+ end
+
+ describe '#cancel_payment_session' do
+ subject(:cancel) { gateway.cancel_payment_session(payment_session: payment_session) }
+
+ let(:payment_session) { session_for(cart, external_id: paypal_order_id, external_data: external_data) }
+ let(:external_data) { { 'client_id' => 'x', 'intent' => 'CAPTURE', 'attempt' => 1 } }
+
+ context 'when Complete was never reached' do
+ let(:external_data) { { 'client_id' => 'x', 'intent' => 'CAPTURE' } }
+
+ it 'cancels without asking PayPal' do
+ allow(gateway).to receive(:paypal_order)
+
+ expect(cancel).to be(true)
+ expect(payment_session.reload).to be_canceled
+ expect(gateway).not_to have_received(:paypal_order)
+ end
+ end
+
+ it 'cancels when nothing moved' do
+ allow(gateway).to receive(:paypal_order).and_return(approved_order)
+
+ expect(cancel).to be(true)
+ end
+
+ it 'voids an authorization and cancels' do
+ allow(gateway).to receive(:paypal_order).and_return(approved_order(authorizations: [paypal_authorization]))
+ allow(gateway).to receive(:void_authorization).and_return({})
+
+ expect(cancel).to be(true)
+ expect(gateway).to have_received(:void_authorization).
+ with('AUTHORIZ123456789', request_id: "#{payment_session.prefixed_id}-void")
+ end
+
+ it 'refuses a captured order' do
+ allow(gateway).to receive(:paypal_order).and_return(captured_order)
+
+ expect { cancel }.to raise_error(Spree::Core::GatewayError, /already taken the money/)
+ expect(payment_session.reload).not_to be_canceled
+ end
+
+ it "treats PayPal's refusal as a gateway error" do
+ allow(gateway).to receive(:paypal_order).and_raise(paypal_error('PERMISSION_DENIED', status: 403))
+
+ expect { cancel }.to raise_error(Spree::Core::GatewayError, /PERMISSION_DENIED/)
+ end
+
+ it 'cancels an order the account no longer knows' do
+ allow(gateway).to receive(:paypal_order).and_raise(paypal_error('RESOURCE_NOT_FOUND', status: 404))
+
+ expect(cancel).to be(true)
+ end
+
+ [
+ ['a timeout', -> { Faraday::TimeoutError.new('timed out') }, Faraday::TimeoutError],
+ ['a rate limit', -> { paypal_error('RATE_LIMIT_REACHED', status: 429) }, PaypalServerSdk::ErrorException],
+ ['a server error', -> { paypal_error('INTERNAL_SERVER_ERROR', status: 500) }, PaypalServerSdk::ErrorException],
+ ['rejected credentials', -> { CoreLibrary::AuthValidationException.new('invalid') }, CoreLibrary::AuthValidationException]
+ ].each do |label, error, error_class|
+ it "raises PayPal's own error for #{label}, so the unused-session job retries" do
+ allow(gateway).to receive(:paypal_order).and_raise(instance_exec(&error))
+
+ expect { cancel }.to raise_error(error_class) { |raised| expect(raised).not_to be_a(Spree::Core::GatewayError) }
+ expect(payment_session.reload).not_to be_canceled
+ end
+ end
+ end
+end
diff --git a/spree/providers/paypal/spec/models/spree_paypal_checkout/gateway_spec.rb b/spree/providers/paypal/spec/models/spree_paypal_checkout/gateway_spec.rb
index b932eec36c..0c90fa8cb0 100644
--- a/spree/providers/paypal/spec/models/spree_paypal_checkout/gateway_spec.rb
+++ b/spree/providers/paypal/spec/models/spree_paypal_checkout/gateway_spec.rb
@@ -53,6 +53,12 @@ RSpec.describe SpreePaypalCheckout::Gateway do
expect(gateway.available_for_order?(cart)).to be(false)
end
+
+ it 'is false for a total PayPal would refuse' do
+ cart.update_columns(currency: 'TWD', total: BigDecimal('1234.50'))
+
+ expect(gateway.available_for_order?(cart)).to be(false)
+ end
end
describe '#paypal_intent' do
@@ -227,6 +233,12 @@ RSpec.describe SpreePaypalCheckout::Gateway do
expect(gateway.authorize(money, nil, options).authorization).to eq(order_id)
end
+ it 'fails for an order whose only capture was declined' do
+ allow(gateway).to receive(:paypal_order).and_return(paypal_order_data(captures: [paypal_capture(status: 'DECLINED')]))
+
+ expect(gateway.purchase(money, nil, options)).not_to be_success
+ end
+
it 'fails for an order no money has moved on' do
allow(gateway).to receive(:paypal_order).and_return(paypal_order_data(status: 'APPROVED'))
@@ -256,6 +268,21 @@ RSpec.describe SpreePaypalCheckout::Gateway do
with('AUTHORIZ123456789', money, request_id: 'spree-py_test123-capture')
end
+ it 'records the capture id on the payment through the capture workflow, keeping the authorization id' do
+ order = create(:order, store: store, total: 10)
+ payment = create(:payment, status: 'pending', order: order, payment_method: gateway, response_code: order_id,
+ amount: 10, metadata: { 'paypal_authorization_id' => 'AUTHORIZ123456789' })
+ allow_any_instance_of(described_class).to receive(:paypal_order).with(order_id).
+ and_return(paypal_order_data(authorizations: [paypal_authorization]))
+ allow_any_instance_of(described_class).to receive(:capture_authorization).and_return(paypal_capture)
+
+ expect(Spree.payment_capture_workflow.call(payment: payment)).to be_success
+ expect(payment.reload).to be_completed
+ expect(payment.metadata).to eq(
+ 'paypal_authorization_id' => 'AUTHORIZ123456789', 'paypal_capture_id' => 'CAPTURE123456789A'
+ )
+ end
+
it 'raises naming the pending reason when PayPal holds the capture' do
allow(gateway).to receive(:capture_authorization).
and_return(paypal_capture(status: 'PENDING', reason: 'PENDING_REVIEW'))
@@ -280,6 +307,19 @@ RSpec.describe SpreePaypalCheckout::Gateway do
expect { capture }.to raise_error(Spree::Core::AmbiguousGatewayError)
end
+
+ it 'raises an ambiguous error for a server error the SDK cannot read' do
+ response = PaypalHelpers::PaypalResponse.new(502, '<html>Bad Gateway</html>', {})
+ allow(gateway).to receive(:capture_authorization).and_raise(PaypalServerSdk::APIException.new('Bad Gateway', response))
+
+ expect { capture }.to raise_error(Spree::Core::AmbiguousGatewayError)
+ end
+
+ it 'raises an ambiguous error when PayPal answers the capture with a server error' do
+ allow(gateway).to receive(:capture_authorization).and_raise(paypal_error('INTERNAL_SERVER_ERROR', status: 500))
+
+ expect { capture }.to raise_error(Spree::Core::AmbiguousGatewayError, /could not say whether it took the payment/)
+ end
end
it 'succeeds without a call when the order was captured already' do
@@ -291,6 +331,24 @@ RSpec.describe SpreePaypalCheckout::Gateway do
expect(gateway).not_to have_received(:capture_authorization)
end
+ it 'records the id of a capture PayPal already took' do
+ order = create(:order, store: store, total: 10)
+ payment = create(:payment, order: order, payment_method: gateway, response_code: order_id, amount: 10)
+ allow(gateway).to receive(:paypal_order).and_return(paypal_order_data(captures: [paypal_capture]))
+
+ gateway.capture(money, order_id, gateway_options.merge(payment_prefixed_id: payment.prefixed_id))
+
+ expect(payment.reload.metadata['paypal_capture_id']).to eq('CAPTURE123456789A')
+ end
+
+ it 'refuses to report an earlier capture of another amount as this one' do
+ allow(gateway).to receive(:paypal_order).and_return(paypal_order_data(captures: [paypal_capture(value: '4.00')]))
+
+ expect { capture }.to raise_error(
+ Spree::Core::GatewayError, 'PayPal already captured 4.00 USD on this order, not the 10.00 USD asked for.'
+ )
+ end
+
it 'raises when an earlier capture is still pending' do
allow(gateway).to receive(:paypal_order).
and_return(paypal_order_data(captures: [paypal_capture(status: 'PENDING', reason: 'ECHECK')]))
diff --git a/spree/providers/paypal/spec/models/spree_paypal_checkout/payment_sources/paypal_spec.rb b/spree/providers/paypal/spec/models/spree_paypal_checkout/payment_sources/paypal_spec.rb
new file mode 100644
index 0000000000..e20780ab37
--- /dev/null
+++ b/spree/providers/paypal/spec/models/spree_paypal_checkout/payment_sources/paypal_spec.rb
@@ -0,0 +1,89 @@
+require 'spec_helper'
+
+RSpec.describe SpreePaypalCheckout::PaymentSources::Paypal do
+ subject(:source) do
+ described_class.for_payment_source(payment_source, payment_method: gateway, customer: customer, paypal_order_id: 'ORDER1234567890AB')
+ end
+
+ let(:gateway) { create(:paypal_checkout_gateway) }
+ let(:customer) { create(:customer) }
+
+ context 'with a PayPal wallet' do
+ let(:payment_source) do
+ {
+ 'paypal' => {
+ 'email_address' => '[email protected]', 'account_id' => 'PAYERID1234', 'account_status' => 'VERIFIED',
+ 'name' => { 'given_name' => 'Ada', 'surname' => 'Lovelace' }
+ }
+ }
+ end
+
+ it 'records the account' do
+ expect(source).to be_persisted
+ expect(source.gateway_payment_profile_id).to eq('paypal-ORDER1234567890AB')
+ expect(source.customer).to eq(customer)
+ expect(source.metadata).to eq(
+ 'wallet' => 'paypal', 'email' => '[email protected]', 'name' => 'Ada Lovelace',
+ 'account_id' => 'PAYERID1234', 'account_status' => 'VERIFIED'
+ )
+ end
+
+ it 'keeps another customer paying with the same account on a source of their own' do
+ other = create(:customer)
+ theirs = described_class.for_payment_source(payment_source, payment_method: gateway, customer: other, paypal_order_id: 'A')
+
+ expect(source).not_to eq(theirs)
+ expect(theirs.customer).to eq(other)
+ expect(source.customer).to eq(customer)
+ end
+
+ it 'returns the same source when the order settles again' do
+ again = described_class.for_payment_source(payment_source, payment_method: gateway, customer: customer, paypal_order_id: 'ORDER1234567890AB')
+
+ expect(again).to eq(source)
+ end
+ end
+
+ context 'with a Venmo wallet' do
+ let(:payment_source) { { 'venmo' => { 'email_address' => '[email protected]', 'account_id' => 'VENMO123', 'user_name' => 'ada' } } }
+
+ it 'records it as Venmo' do
+ expect(source.wallet).to eq('venmo')
+ expect(source.metadata['user_name']).to eq('ada')
+ end
+ end
+
+ context 'with a card paid in PayPal\'s window' do
+ let(:payment_source) { { 'card' => { 'name' => 'Ada Lovelace', 'last_digits' => '4242', 'brand' => 'VISA', 'type' => 'CREDIT' } } }
+
+ it 'records the brand and last digits on a PayPal source, never a credit card' do
+ expect(source).to be_a(described_class)
+ expect(source.wallet).to eq('card')
+ expect(source.brand).to eq('VISA')
+ expect(source.last_digits).to eq('4242')
+ expect(Spree::CreditCard.count).to eq(0)
+ end
+
+ it 'records a card PayPal reports without details' do
+ source = described_class.for_payment_source({ 'card' => {} }, payment_method: gateway, customer: nil, paypal_order_id: 'B')
+
+ expect(source.metadata).to eq('wallet' => 'card')
+ end
+ end
+
+ context 'with a kind the gem does not model' do
+ let(:payment_source) { { 'ideal' => { 'name' => 'Ada' } } }
+
+ it { is_expected.to be_nil }
+ end
+
+ context 'without a payment source' do
+ let(:payment_source) { nil }
+
+ it { is_expected.to be_nil }
+ end
+
+ it 'is named PayPal' do
+ expect(described_class.display_name).to eq('PayPal')
+ end
+end