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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Added the PayPal client, credential check and money verbs
Łukasz Adamczyk669cd64e7ce0
diff --git a/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rb b/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rbindex 8bbf22fc0b..fc0ac12820 100644--- a/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rb+++ b/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rb@@ -2,9 +2,32 @@ module SpreePaypalCheckout# PayPal Checkout gateway built on the payment session API. A session is a# PayPal order: the buyer approves it in PayPal's window, then the server# captures or authorizes it, so the server is the only thing that moves money.+ #+ # A payment's response code is always the PayPal order id, the key core uses+ # to link a session to its payment. The capture and authorization ids PayPal+ # issues are read from the order whenever a capture, refund or void needs them.class Gateway < ::Spree::Gatewayself.accepts_money_amounts = true+ # A capture PayPal has taken, whether or not it was refunded since.+ CAPTURED_STATUSES = %w[COMPLETED PARTIALLY_REFUNDED REFUNDED].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.+ CONNECTION_ERRORS = [Faraday::TimeoutError, Faraday::ConnectionFailed].freeze++ # A refusal from PayPal, with its issue code (INSTRUMENT_DECLINED,+ # AUTHORIZATION_EXPIRED, …) kept apart from the message for callers that+ # act on it.+ class PaypalError < Spree::Core::GatewayError+ attr_reader :issue++ def initialize(message = nil, issue: nil)+ super(message)+ @issue = issue+ end+ end+preference :client_id, :passwordpreference :client_secret, :password# The credentials do not say which PayPal environment they belong to.@@ -13,6 +36,7 @@ module SpreePaypalCheckoutpreference :webhook_id, :string, internal: truevalidates :preferred_client_id, :preferred_client_secret, presence: true+ validate :validate_credentials, unless: -> { Rails.env.test? }, if: :credentials_changed?def self.logo_url'https://spreecommerce.org/docs/images/integrations/logos/paypal.png'@@ -67,5 +91,334 @@ module SpreePaypalCheckoutPaypalServerSdk::CheckoutPaymentIntent::AUTHORIZEendend++ # PayPal's activity page lists transactions, not orders, so the link needs+ # the capture or authorization id recorded at settlement.+ def gateway_dashboard_payment_url(payment)+ transaction_id = payment.metadata['paypal_capture_id'].presence || payment.metadata['paypal_authorization_id'].presence+ return if transaction_id.blank?++ host = preferred_test_mode ? 'www.sandbox.paypal.com' : 'www.paypal.com'+ "https://#{host}/activity/payment/#{transaction_id}"+ end++ # Called by core when a session-created payment moves on. The session has+ # already captured or authorized the order, so this reads it back.+ #+ # @param _money [Spree::Money]+ # @param _payment_source [Spree::PaymentSource, nil]+ # @param gateway_options [Hash] Spree::Payment::GatewayOptions#to_hash+ # @return [Spree::PaymentResponse]+ def authorize(_money, _payment_source, gateway_options = {})+ read_back(gateway_options)+ end++ # @see #authorize+ def purchase(_money, _payment_source, gateway_options = {})+ read_back(gateway_options)+ end++ # Captures the order's authorization, in part or in full. It is the+ # payment's only capture (`final_capture`): core authorizes any remainder+ # as a payment of its own.+ #+ # @param money [Spree::Money]+ # @param order_id [String] the PayPal order id+ # @param gateway_options [Hash]+ # @return [Spree::PaymentResponse]+ # @raise [PaypalError] when PayPal refuses, or holds the capture as pending+ def capture(money, order_id, gateway_options = {})+ paypal_order = protect_from_error { paypal_order(order_id) }++ 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)+ end++ authorization = open_authorization(paypal_order)+ raise Spree::Core::GatewayError, no_authorization_message(paypal_order) if authorization.nil?++ result = protect_from_error(money_moving: true) do+ capture_authorization(authorization['id'], money, request_id: request_id(gateway_options, order_id, 'capture'))+ end++ case result['status']+ when 'COMPLETED' then 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']),+ issue: result['status'])+ end+ end++ # Refunds the order's capture.+ #+ # @param money [Spree::Money]+ # @param order_id [String] the PayPal order id+ # @param options [Hash] carries the Spree::Refund as +originator++ # @return [Spree::PaymentResponse] authorized by the PayPal refund id+ def credit(money, order_id, options = {})+ paypal_order = protect_from_error { paypal_order(order_id) }+ capture = captures(paypal_order).find { |candidate| candidate['status'].in?(CAPTURED_STATUSES) }+ raise Spree::Core::GatewayError, I18n.t('spree.paypal_checkout.errors.nothing_to_refund') if capture.nil?++ originator = options[:originator]+ # Without a refund record there is nothing stable to key on, and reusing+ # a key would replay an earlier refund instead of making this one.+ request_id = originator.respond_to?(:prefixed_id) ? "spree-#{originator.prefixed_id}-refund" : "paypal-#{SecureRandom.uuid}"++ result = protect_from_error(money_moving: true) do+ refund_capture(capture['id'], money, request_id: request_id)+ end++ success(result['id'], result)+ end++ # Releases the order's authorization. An order taken with the CAPTURE+ # intent holds no authorization until it is captured, so there is nothing+ # to release.+ #+ # @param order_id [String] the PayPal order id+ # @param gateway_options [Hash]+ # @return [Spree::PaymentResponse]+ # @raise [PaypalError] when a capture is still pending: the money may yet+ # arrive, and a payment voided in Spree could not take it+ def void(order_id, gateway_options = {})+ paypal_order = protect_from_error { paypal_order(order_id) }++ capture = captures(paypal_order).first+ if capture && capture['status'] == 'PENDING'+ raise PaypalError.new(I18n.t('spree.paypal_checkout.errors.void_pending_capture'), issue: 'PENDING')+ end+ if capture && capture['status'].in?(CAPTURED_STATUSES)+ raise Spree::Core::GatewayError, I18n.t('spree.paypal_checkout.errors.void_captured')+ end++ authorization = open_authorization(paypal_order)+ return success(order_id, paypal_order) if authorization.nil?++ result = protect_from_error(money_moving: true) do+ void_authorization(authorization['id'], request_id: request_id(gateway_options, order_id, 'void'))+ end++ success(order_id, result)+ end++ # A completed payment can no longer be voided, so cancellation refunds it+ # instead, unless the operator asked to keep the money. Refunds for a+ # fulfillment are skipped; the delivery cost is refunded as a whole+ # elsewhere.+ def cancel(order_id, payment = nil, refund: true)+ return void(order_id, payment ? payment.gateway_options : {}) unless payment&.completed?+ return success(order_id, {}) unless refund++ amount = payment.credit_allowed+ return success(order_id, {}) if amount.zero?+ return success(order_id, {}) if payment.respond_to?(:for_shipment?) && payment.for_shipment?++ # Store passed explicitly: cancellation runs from jobs and webhooks where+ # Spree::Current.store is nil.+ result = Spree.refund_create_workflow.call(+ payment: payment,+ reason: Spree::RefundReason.order_canceled_reason(payment.owner.store),+ refunder: payment.order.canceler+ )+ raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?++ # The authorization must stay the order id, or the refund id would+ # overwrite it.+ success(payment.response_code, result.value.response.params)+ end++ # @param order_id [String]+ # @return [Hash] the PayPal order, as PayPal writes it+ def paypal_order(order_id)+ client.orders.get_order('id' => order_id).data.to_hash+ end++ # @return [Hash] the capture+ def capture_authorization(authorization_id, money, request_id:)+ client.payments.capture_authorized_payment(+ 'authorization_id' => authorization_id,+ 'paypal_request_id' => request_id,+ 'prefer' => 'return=representation',+ 'body' => PaypalServerSdk::CaptureRequest.new(amount: paypal_money(money), final_capture: true)+ ).data.to_hash+ end++ # @return [Hash] the refund+ def refund_capture(capture_id, money, request_id:)+ client.payments.refund_captured_payment(+ 'capture_id' => capture_id,+ 'paypal_request_id' => request_id,+ 'prefer' => 'return=representation',+ 'body' => PaypalServerSdk::RefundRequest.new(amount: paypal_money(money))+ ).data.to_hash+ end++ # @return [Hash] the voided authorization; empty when PayPal answers+ # without a body+ def void_authorization(authorization_id, request_id:)+ client.payments.void_payment(+ 'authorization_id' => authorization_id,+ 'paypal_request_id' => request_id,+ 'prefer' => 'return=representation'+ ).data&.to_hash || {}+ end++ # Asks PayPal for an access token with the stored credentials, which is+ # how PayPal says whether it accepts them.+ #+ # @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+ end++ # Rebuilt when the credentials change, since it carries them.+ #+ # @return [PaypalServerSdk::Client]+ def client+ fingerprint = [preferred_client_id, preferred_client_secret, preferred_test_mode]+ return @client if @client && @client_fingerprint == fingerprint++ @client_fingerprint = fingerprint+ @client = PaypalServerSdk::Client.new(+ client_credentials_auth_credentials: PaypalServerSdk::ClientCredentialsAuthCredentials.new(+ o_auth_client_id: preferred_client_id.to_s,+ o_auth_client_secret: preferred_client_secret.to_s+ ),+ environment: preferred_test_mode ? PaypalServerSdk::Environment::SANDBOX : PaypalServerSdk::Environment::PRODUCTION,+ timeout: 30,+ max_retries: 2,+ # Retrying a POST is safe only because every one that moves money+ # carries a PayPal-Request-Id; a PATCH only ever replaces the whole+ # purchase unit.+ retry_methods: %i[get post patch],+ logging_configuration: PaypalServerSdk::LoggingConfiguration.new(+ logger: Rails.logger,+ log_level: log_level,+ # Bodies carry buyer names, emails and addresses.+ request_logging_config: PaypalServerSdk::RequestLoggingConfiguration.new(log_body: false, log_headers: false),+ response_logging_config: PaypalServerSdk::ResponseLoggingConfiguration.new(log_body: false, log_headers: false)+ )+ )+ end++ private++ def read_back(gateway_options)+ payment = find_payment(gateway_options)+ return failure('Payment not found') if payment.blank?+ 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)++ failure(no_authorization_message(paypal_order))+ end++ # Scoped through this gateway's own payments and found by the prefixed id;+ # the stored number remains only for callers still passing pre-6.0 options.+ def find_payment(gateway_options)+ prefixed_id = gateway_options[:payment_prefixed_id]+ payment = prefixed_id.present? ? payments.find_by_prefix_id(prefixed_id) : nil+ return payment if payment.present?++ payment_number = gateway_options[:payment_id].presence || gateway_options[:order_id]+ 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|+ authorization['status'].in?(OPEN_AUTHORIZATION_STATUSES)+ end+ end++ def payments_of(paypal_order, kind)+ Array(paypal_order['purchase_units']).flat_map { |unit| Array(unit.dig('payments', kind)) }+ end++ def no_authorization_message(paypal_order)+ authorization = payments_of(paypal_order, 'authorizations').first+ if authorization+ I18n.t('spree.paypal_checkout.errors.authorization_not_open', status: authorization['status'])+ else+ I18n.t('spree.paypal_checkout.errors.nothing_to_capture', status: paypal_order['status'])+ end+ 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)+ end++ # Keyed on the Spree payment, so a retry or a double click reaches PayPal+ # as the same request and cannot move money twice.+ def request_id(gateway_options, order_id, action)+ base = gateway_options[:idempotency_key].presence || "paypal-#{order_id}"+ "#{base}-#{action}"+ end++ def paypal_money(money)+ currency = money.currency.to_s.upcase+ PaypalServerSdk::Money.new(currency_code: currency, value: SpreePaypalCheckout::Amounts.to_paypal(money, currency))+ end++ def log_level+ Logger.const_get(ENV.fetch('PAYPAL_LOG_LEVEL', 'info').upcase)+ rescue NameError+ Logger::INFO+ end++ def credentials_changed?+ return false if preferred_client_id.blank? || preferred_client_secret.blank?++ new_record? || preferred_client_id_changed? || preferred_client_secret_changed? || preferred_test_mode_changed?+ end++ def validate_credentials+ request_access_token+ rescue PaypalServerSdk::APIException+ errors.add(:base, :credentials_rejected, message: credentials_rejected_message)+ rescue *CONNECTION_ERRORS+ errors.add(:base, :paypal_unavailable, message: I18n.t('spree.paypal_checkout.errors.paypal_unavailable'))+ end++ def credentials_rejected_message+ I18n.t('spree.paypal_checkout.errors.credentials_rejected', environment: preferred_test_mode ? 'sandbox' : 'live')+ end++ # PayPal's refusal becomes a GatewayError naming its issue code. A call+ # that moves money and gets no answer becomes an AmbiguousGatewayError,+ # 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}"+ rescue CoreLibrary::AuthValidationException+ raise Spree::Core::GatewayError, credentials_rejected_message+ rescue *CONNECTION_ERRORS => e+ error_class = money_moving ? Spree::Core::AmbiguousGatewayError : Spree::Core::GatewayError+ raise error_class, I18n.t('spree.paypal_checkout.errors.no_answer', message: e.message)+ end++ def success(authorization, full_response)+ Spree::PaymentResponse.new(true, nil, full_response.as_json, authorization: authorization)+ end++ def failure(error = nil)+ Spree::PaymentResponse.new(false, error)+ endendenddiff --git a/spree/providers/paypal/config/locales/en.yml b/spree/providers/paypal/config/locales/en.ymlindex e97bcd18af..cbe7edf7c7 100644--- a/spree/providers/paypal/config/locales/en.yml+++ b/spree/providers/paypal/config/locales/en.yml@@ -1,4 +1,15 @@---en:spree:- paypal_checkout: {}+ paypal_checkout:+ errors:+ authorization_not_open: "PayPal can no longer capture this payment: its authorization is %{status}."+ 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."+ 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."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.rbindex 01dbadade6..b932eec36c 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@@ -3,6 +3,9 @@ require 'spec_helper'RSpec.describe SpreePaypalCheckout::Gateway dolet(:store) { @default_store }let(:gateway) { create(:paypal_checkout_gateway, store: store) }+ let(:order_id) { 'ORDER1234567890AB' }+ let(:money) { Spree::Money.new(BigDecimal('10'), currency: 'USD') }+ let(:gateway_options) { { idempotency_key: 'spree-py_test123' } }it 'is registered as a payment method' doexpect(Rails.application.config.spree.payment_methods).to include(described_class)@@ -71,4 +74,380 @@ RSpec.describe SpreePaypalCheckout::Gateway doexpect(gateway.paypal_intent).to eq('AUTHORIZE')endend++ describe '#client' do+ subject(:config) { gateway.client.config }++ it 'talks to the sandbox in test mode' do+ expect(config.environment).to eq(PaypalServerSdk::Environment::SANDBOX)+ end++ it 'talks to the live site otherwise' do+ gateway.preferred_test_mode = false++ expect(config.environment).to eq(PaypalServerSdk::Environment::PRODUCTION)+ end++ it 'times out after 30 seconds and retries GET, POST and PATCH twice' do+ expect(config.timeout).to eq(30)+ expect(config.max_retries).to eq(2)+ expect(config.retry_methods).to eq(%i[get post patch])+ expect(config.retry_statuses).to eq([408, 413, 429, 500, 502, 503, 504, 521, 522, 524])+ end++ it 'never logs bodies or headers' do+ logging = config.logging_configuration++ expect(logging.request_logging_config.log_body).to be(false)+ expect(logging.request_logging_config.log_headers).to be(false)+ expect(logging.response_logging_config.log_body).to be(false)+ expect(logging.response_logging_config.log_headers).to be(false)+ end++ it 'logs at the level PAYPAL_LOG_LEVEL sets' do+ allow(ENV).to receive(:fetch).and_call_original+ allow(ENV).to receive(:fetch).with('PAYPAL_LOG_LEVEL', 'info').and_return('debug')++ expect(config.logging_configuration.log_level).to eq(Logger::DEBUG)+ end++ it 'is rebuilt when the credentials change' do+ first = gateway.client+ gateway.preferred_client_secret = 'rotated'++ expect(gateway.client).not_to be(first)+ end+ end++ describe 'credential check' do+ before { allow(Rails.env).to receive(:test?).and_return(false) }++ let(:gateway) { build(:paypal_checkout_gateway, store: store) }++ it 'accepts credentials PayPal issues a token for' do+ allow(gateway).to receive(:request_access_token).and_return(double)++ expect(gateway).to be_valid+ end++ it 'names what to fix when the sandbox refuses them' do+ allow(gateway).to receive(:request_access_token).and_raise(paypal_error('invalid_client', status: 401))++ expect(gateway).not_to be_valid+ expect(gateway.errors[:base]).to eq(+ ['PayPal sandbox rejected this client id and secret — check that Test mode matches the credentials.']+ )+ end++ it 'names the live site when test mode is off' do+ gateway.preferred_test_mode = false+ allow(gateway).to receive(:request_access_token).and_raise(paypal_error('invalid_client', status: 401))++ expect(gateway).not_to be_valid+ expect(gateway.errors[:base].first).to start_with('PayPal live rejected')+ end++ it 'says PayPal could not be reached when it does not answer' do+ allow(gateway).to receive(:request_access_token).and_raise(Faraday::ConnectionFailed, 'refused')++ expect(gateway).not_to be_valid+ expect(gateway.errors[:base]).to eq(['PayPal could not be reached to check the client id and secret. Try again later.'])+ end++ it 'is not asked again when the credentials did not change' do+ allow(gateway).to receive(:request_access_token).and_return(double)+ gateway.save!+ gateway.name = 'PayPal (renamed)'++ expect(gateway).to be_valid+ expect(gateway).to have_received(:request_access_token).once+ end+ end++ describe 'credential check against PayPal' do+ it 'accepts sandbox credentials', vcr: { cassette_name: 'credentials_valid' } do+ expect(gateway.request_access_token.access_token).to be_present+ end++ it 'reports credentials PayPal rejects', vcr: { cassette_name: 'credentials_rejected' } do+ gateway.preferred_client_id = 'not-a-client-id'+ gateway.preferred_client_secret = 'not-a-secret'++ expect { gateway.request_access_token }.to raise_error(PaypalServerSdk::APIException)+ end+ end++ describe '#gateway_dashboard_payment_url' do+ let(:payment) { build(:payment, payment_method: gateway) }++ it 'links to the capture on the sandbox activity page' do+ payment.metadata = { 'paypal_capture_id' => 'CAPTURE123', 'paypal_authorization_id' => 'AUTH123' }++ expect(gateway.gateway_dashboard_payment_url(payment)).to eq('https://www.sandbox.paypal.com/activity/payment/CAPTURE123')+ end++ it 'links to the authorization when nothing was captured' do+ payment.metadata = { 'paypal_authorization_id' => 'AUTH123' }++ expect(gateway.gateway_dashboard_payment_url(payment)).to eq('https://www.sandbox.paypal.com/activity/payment/AUTH123')+ end++ it 'links to the live site outside test mode' do+ gateway.preferred_test_mode = false+ payment.metadata = { 'paypal_capture_id' => 'CAPTURE123' }++ expect(gateway.gateway_dashboard_payment_url(payment)).to eq('https://www.paypal.com/activity/payment/CAPTURE123')+ end++ it 'has no link without an id' do+ payment.metadata = {}++ expect(gateway.gateway_dashboard_payment_url(payment)).to be_nil+ end+ end++ describe '#authorize and #purchase' do+ let(:order) { create(:order, store: store, total: 10) }+ let!(:payment) { create(:payment, order: order, payment_method: gateway, response_code: order_id, amount: 10) }+ let(:options) { { payment_prefixed_id: payment.prefixed_id } }++ it 'reads back a captured order and answers with its id' do+ allow(gateway).to receive(:paypal_order).with(order_id).+ and_return(paypal_order_data(captures: [paypal_capture]))++ response = gateway.purchase(money, nil, options)++ expect(response).to be_success+ expect(response.authorization).to eq(order_id)+ end++ it 'reads back an authorized order' do+ allow(gateway).to receive(:paypal_order).and_return(paypal_order_data(authorizations: [paypal_authorization]))++ expect(gateway.authorize(money, nil, options).authorization).to eq(order_id)+ 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'))++ expect(gateway.authorize(money, nil, options)).not_to be_success+ end++ it 'fails for a payment it does not know' do+ expect(gateway.authorize(money, nil, { payment_prefixed_id: 'py_unknown' })).not_to be_success+ end+ end++ describe '#capture' do+ subject(:capture) { gateway.capture(money, order_id, gateway_options) }++ context 'with an open authorization' do+ before do+ allow(gateway).to receive(:paypal_order).with(order_id).+ and_return(paypal_order_data(authorizations: [paypal_authorization]))+ end++ it 'captures it as the final capture, keyed on the payment, and answers with the order id' do+ allow(gateway).to receive(:capture_authorization).and_return(paypal_capture)++ expect(capture).to be_success+ expect(capture.authorization).to eq(order_id)+ expect(gateway).to have_received(:capture_authorization).+ with('AUTHORIZ123456789', money, request_id: 'spree-py_test123-capture')+ 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'))++ expect { capture }.to raise_error(+ described_class::PaypalError,+ 'PayPal is holding this capture: PENDING_REVIEW. It completes when PayPal releases it.'+ )+ end++ it "raises with PayPal's reason when the authorization has expired" do+ allow(gateway).to receive(:capture_authorization).+ and_raise(paypal_error('AUTHORIZATION_EXPIRED', 'The authorization has expired.'))++ expect { capture }.to raise_error(described_class::PaypalError, 'AUTHORIZATION_EXPIRED: The authorization has expired.') { |error|+ expect(error.issue).to eq('AUTHORIZATION_EXPIRED')+ }+ end++ it 'raises an ambiguous error when the capture gets no answer' do+ allow(gateway).to receive(:capture_authorization).and_raise(Faraday::TimeoutError, 'timed out')++ expect { capture }.to raise_error(Spree::Core::AmbiguousGatewayError)+ end+ end++ it 'succeeds without a call when the order was captured already' do+ allow(gateway).to receive(:paypal_order).and_return(paypal_order_data(captures: [paypal_capture]))+ allow(gateway).to receive(:capture_authorization)++ expect(capture).to be_success+ expect(capture.authorization).to eq(order_id)+ expect(gateway).not_to have_received(:capture_authorization)+ 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')]))++ expect { capture }.to raise_error(described_class::PaypalError, /holding this capture: ECHECK/)+ end++ it 'raises naming the status of an authorization that can no longer be captured' do+ allow(gateway).to receive(:paypal_order).+ and_return(paypal_order_data(authorizations: [paypal_authorization(status: 'EXPIRED')]))++ expect { capture }.to raise_error(Spree::Core::GatewayError, /its authorization is EXPIRED/)+ end++ it 'reports a read that gets no answer as a plain gateway error' do+ allow(gateway).to receive(:paypal_order).and_raise(Faraday::TimeoutError, 'timed out')++ expect { capture }.to raise_error(Spree::Core::GatewayError) { |error|+ expect(error).not_to be_a(Spree::Core::AmbiguousGatewayError)+ }+ end++ it 'captures part of an authorization against PayPal',+ vcr: { cassette_name: 'capture_authorization' } do+ # Recording needs an order a sandbox buyer approved and the server+ # authorized; PAYPAL_AUTHORIZED_ORDER_ID names it.+ paypal_order_id = ENV.fetch('PAYPAL_AUTHORIZED_ORDER_ID', order_id)+ partial = Spree::Money.new(BigDecimal('5'), currency: 'USD')++ response = gateway.capture(partial, paypal_order_id, gateway_options)++ expect(response).to be_success+ expect(response.authorization).to eq(paypal_order_id)+ expect(response.params['status']).to eq('COMPLETED')+ end+ end++ describe '#credit' do+ let(:refund) { instance_double(Spree::Refund, prefixed_id: 're_test123') }++ it 'refunds the capture keyed on the refund and answers with the refund id' do+ allow(gateway).to receive(:paypal_order).and_return(paypal_order_data(captures: [paypal_capture]))+ allow(gateway).to receive(:refund_capture).and_return({ 'id' => 'REFUND1234567890A', 'status' => 'COMPLETED' })++ response = gateway.credit(money, order_id, originator: refund)++ expect(response.authorization).to eq('REFUND1234567890A')+ expect(gateway).to have_received(:refund_capture).+ with('CAPTURE123456789A', money, request_id: 'spree-re_test123-refund')+ end++ it 'raises when the order has no capture' do+ allow(gateway).to receive(:paypal_order).and_return(paypal_order_data(authorizations: [paypal_authorization]))++ expect { gateway.credit(money, order_id, originator: refund) }.+ to raise_error(Spree::Core::GatewayError, 'This PayPal order has no capture to refund.')+ end++ it 'refunds a capture against PayPal', vcr: { cassette_name: 'refund_capture' } do+ # Recording needs a captured sandbox order; PAYPAL_CAPTURED_ORDER_ID names it.+ paypal_order_id = ENV.fetch('PAYPAL_CAPTURED_ORDER_ID', order_id)++ response = gateway.credit(Spree::Money.new(BigDecimal('1'), currency: 'USD'), paypal_order_id, originator: refund)++ expect(response).to be_success+ expect(response.params['status']).to eq('COMPLETED')+ end+ end++ describe '#void' do+ subject(:void) { gateway.void(order_id, gateway_options) }++ it 'voids the authorization, keyed on the payment, and answers with the order id' do+ allow(gateway).to receive(:paypal_order).and_return(paypal_order_data(authorizations: [paypal_authorization]))+ allow(gateway).to receive(:void_authorization).and_return({ 'status' => 'VOIDED' })++ expect(void.authorization).to eq(order_id)+ expect(gateway).to have_received(:void_authorization).+ with('AUTHORIZ123456789', request_id: 'spree-py_test123-void')+ end++ it 'succeeds without a call for an uncaptured CAPTURE order' do+ allow(gateway).to receive(:paypal_order).and_return(paypal_order_data(status: 'APPROVED'))+ allow(gateway).to receive(:void_authorization)++ expect(void).to be_success+ expect(gateway).not_to have_received(:void_authorization)+ end++ it 'raises while a capture is pending' do+ allow(gateway).to receive(:paypal_order).+ and_return(paypal_order_data(captures: [paypal_capture(status: 'PENDING', reason: 'ECHECK')]))++ expect { void }.to raise_error(+ described_class::PaypalError,+ 'PayPal is still holding a capture on this payment; refund it once it completes.'+ )+ end++ it 'raises for a captured order' do+ allow(gateway).to receive(:paypal_order).and_return(paypal_order_data(captures: [paypal_capture]))++ expect { void }.to raise_error(Spree::Core::GatewayError, /refund it instead/)+ end++ it 'voids an authorization against PayPal', vcr: { cassette_name: 'void_authorization' } do+ # Recording needs another authorized sandbox order; PAYPAL_VOIDABLE_ORDER_ID names it.+ paypal_order_id = ENV.fetch('PAYPAL_VOIDABLE_ORDER_ID', order_id)++ response = gateway.void(paypal_order_id, gateway_options)++ expect(response).to be_success+ expect(response.authorization).to eq(paypal_order_id)+ end+ end++ describe '#cancel' do+ let!(:refund_reason) { Spree::RefundReason.first || create(:default_refund_reason) }+ let(:order) { create(:order, store: store, total: 10) }++ context 'when the payment is completed' do+ let!(:payment) do+ create(:payment, status: 'completed', order: order, payment_method: gateway, amount: 10, response_code: order_id)+ end++ # The refund workflow credits through the payment's own copy of the gateway.+ before do+ allow_any_instance_of(described_class).to receive(:paypal_order).+ and_return(paypal_order_data(captures: [paypal_capture]))+ allow_any_instance_of(described_class).to receive(:refund_capture).+ and_return({ 'id' => 'REFUND1234567890A', 'status' => 'COMPLETED' })+ end++ it 'refunds what is left and keeps the order id as the authorization' do+ response = nil+ expect { response = gateway.cancel(order_id, payment) }.to change(Spree::Refund, :count).by(1)++ expect(payment.refunds.last.transaction_id).to eq('REFUND1234567890A')+ expect(response.authorization).to eq(order_id)+ end++ it 'leaves the money when the caller asked to keep it' do+ expect { gateway.cancel(order_id, payment, refund: false) }.not_to change(Spree::Refund, :count)+ end+ end++ context 'when the payment is not completed' do+ let!(:payment) { create(:payment, order: order, payment_method: gateway, amount: 10, response_code: order_id) }++ it 'voids the authorization' do+ allow(gateway).to receive(:paypal_order).and_return(paypal_order_data(authorizations: [paypal_authorization]))+ allow(gateway).to receive(:void_authorization).and_return({ 'status' => 'VOIDED' })++ expect(gateway.cancel(order_id, payment).authorization).to eq(order_id)+ expect(gateway).to have_received(:void_authorization).+ with('AUTHORIZ123456789', request_id: "spree-#{payment.prefixed_id}-void")+ end+ end+ endenddiff --git a/spree/providers/paypal/spec/support/paypal_helpers.rb b/spree/providers/paypal/spec/support/paypal_helpers.rbnew file mode 100644index 0000000000..6da1553537--- /dev/null+++ b/spree/providers/paypal/spec/support/paypal_helpers.rb@@ -0,0 +1,45 @@+module PaypalHelpers+ PaypalResponse = Struct.new(:status_code, :raw_body, :headers)++ # An error PayPal answers with, as the SDK raises it.+ def paypal_error(issue, description = 'PayPal refused the request.', status: 422)+ body = {+ name: 'UNPROCESSABLE_ENTITY',+ message: 'The requested action could not be performed.',+ details: [{ issue: issue, description: description }]+ }.to_json+ PaypalServerSdk::ErrorException.new('refused', PaypalResponse.new(status, body, {}))+ end++ # A PayPal order as PaypalServerSdk models serialize it.+ def paypal_order_data(id: 'ORDER1234567890AB', status: 'COMPLETED', captures: nil, authorizations: nil, extra: {})+ payments = { 'captures' => captures, 'authorizations' => authorizations }.compact+ {+ 'id' => id,+ 'status' => status,+ 'purchase_units' => [+ {+ 'amount' => { 'currency_code' => 'USD', 'value' => '10.00' },+ 'payments' => payments.presence+ }.compact+ ]+ }.merge(extra)+ end++ def paypal_capture(id: 'CAPTURE123456789A', status: 'COMPLETED', reason: nil, value: '10.00')+ {+ 'id' => id,+ 'status' => status,+ 'status_details' => (reason ? { 'reason' => reason } : nil),+ 'amount' => { 'currency_code' => 'USD', 'value' => value }+ }.compact+ end++ def paypal_authorization(id: 'AUTHORIZ123456789', status: 'CREATED', value: '10.00')+ { 'id' => id, 'status' => status, 'amount' => { 'currency_code' => 'USD', 'value' => value } }+ end+end++RSpec.configure do |config|+ config.include PaypalHelpers+enddiff --git a/spree/providers/paypal/spec/support/vcr.rb b/spree/providers/paypal/spec/support/vcr.rbindex 1f87c8cf39..bb7ebdde74 100644--- a/spree/providers/paypal/spec/support/vcr.rb+++ b/spree/providers/paypal/spec/support/vcr.rb@@ -13,7 +13,18 @@ VCR.configure do |c|# Offline by default: a missing cassette fails the example rather than quietly# recording one against whatever credentials happen to be in the environment.# Opt in with RECORD_VCR=1 when you genuinely intend to capture new interactions.- c.default_cassette_options = { record: ENV['RECORD_VCR'] ? :new_episodes : :none }+ c.default_cassette_options = {+ record: ENV['RECORD_VCR'] ? :new_episodes : :none,+ match_requests_on: %i[method paypal_route]+ }++ # PayPal ids in the path (orders, captures, authorizations, webhooks) differ+ # between the sandbox objects a recording used and the placeholders a replay+ # passes, so they are matched as one segment.+ c.register_request_matcher :paypal_route do |recorded, replayed|+ route = ->(request) { URI(request.uri).path.gsub(%r{/(?=[A-Z0-9-]*\d)[A-Z0-9-]{10,}(?=/|\z)}, '/:id') }+ route.call(recorded) == route.call(replayed)+ endc.filter_sensitive_data('<PAYPAL_CLIENT_ID>') { ENV['PAYPAL_CLIENT_ID'] }c.filter_sensitive_data('<PAYPAL_CLIENT_SECRET>') { ENV['PAYPAL_CLIENT_SECRET'] }