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 amount formatting and the order presenter

Łukasz Adamczykc307f9777990
diff --git a/spree/providers/paypal/app/models/spree_paypal_checkout/amounts.rb b/spree/providers/paypal/app/models/spree_paypal_checkout/amounts.rb
new file mode 100644
index 0000000000..0c37614d57
--- /dev/null
+++ b/spree/providers/paypal/app/models/spree_paypal_checkout/amounts.rb
@@ -0,0 +1,55 @@
+module SpreePaypalCheckout
+ # PayPal's decimal-string amounts (https://developer.paypal.com/reference/currency-codes/).
+ # Written in the currency's ISO exponent, except that PayPal takes HUF, JPY
+ # and TWD only in whole units. An amount PayPal would refuse raises here,
+ # naming the rule, rather than being rounded to a sum Spree did not record.
+ module Amounts
+ module_function
+
+ SUPPORTED_CURRENCIES = %w[
+ AUD BRL CAD CHF CNY CZK DKK EUR GBP HKD HUF ILS JPY MXN MYR NOK NZD PHP PLN SEK SGD THB TWD USD
+ ].freeze
+ WHOLE_UNITS = %w[HUF JPY TWD].freeze
+
+ class UnsupportedAmount < Spree::Core::GatewayError; end
+
+ # @param currency [String]
+ # @return [Boolean]
+ def supported_currency?(currency)
+ SUPPORTED_CURRENCIES.include?(currency.to_s.upcase)
+ end
+
+ # @return [Boolean] whether PayPal takes this amount in this currency
+ def payable?(amount, currency)
+ to_paypal(amount, currency)
+ true
+ rescue UnsupportedAmount
+ false
+ end
+
+ # @param amount [BigDecimal, Spree::Money]
+ # @param currency [String]
+ # @return [String] e.g. "19.99", or "2000" for yen
+ # @raise [UnsupportedAmount] when PayPal would refuse the amount
+ def to_paypal(amount, currency)
+ amount = amount.to_d if amount.respond_to?(:to_d)
+ code = currency.to_s.upcase
+ raise UnsupportedAmount, "PayPal does not take #{code}" unless supported_currency?(code)
+
+ places = WHOLE_UNITS.include?(code) ? 0 : Spree::Money::Rounding.precision(code)
+ quantized = Spree::Money::Rounding.quantize(amount, places)
+ if quantized != amount
+ rule = places.zero? ? 'only in whole units' : "only to #{places} decimal places"
+ raise UnsupportedAmount, "PayPal takes #{code} #{rule}, got #{amount.to_s('F')}"
+ end
+ return quantized.to_i.to_s if places.zero?
+
+ Spree::Money::Rounding.format(quantized, code)
+ end
+
+ # @return [PaypalServerSdk::Money]
+ def to_paypal_money(amount, currency)
+ PaypalServerSdk::Money.new(currency_code: currency.to_s.upcase, value: to_paypal(amount, currency))
+ 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 5bfa208838..8bbf22fc0b 100644
--- a/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rb
+++ b/spree/providers/paypal/app/models/spree_paypal_checkout/gateway.rb
@@ -51,5 +51,21 @@ module SpreePaypalCheckout
def payment_profiles_supported?
false
end
+
+ def available_for_order?(order)
+ super && SpreePaypalCheckout::Amounts.supported_currency?(order.currency)
+ end
+
+ # CAPTURE takes the money when the session completes; AUTHORIZE holds it
+ # for Spree to capture on dispatch or by hand.
+ #
+ # @return [String]
+ def paypal_intent
+ if capture_at_checkout?
+ PaypalServerSdk::CheckoutPaymentIntent::CAPTURE
+ else
+ PaypalServerSdk::CheckoutPaymentIntent::AUTHORIZE
+ end
+ end
end
end
diff --git a/spree/providers/paypal/app/presenters/spree_paypal_checkout/order_presenter.rb b/spree/providers/paypal/app/presenters/spree_paypal_checkout/order_presenter.rb
new file mode 100644
index 0000000000..e808f1a6cb
--- /dev/null
+++ b/spree/providers/paypal/app/presenters/spree_paypal_checkout/order_presenter.rb
@@ -0,0 +1,131 @@
+module SpreePaypalCheckout
+ # The PayPal order for a cart, built with the SDK's request models. One
+ # purchase unit carries the amount, the shipping address and, when they
+ # reconcile exactly to that amount, the items and their breakdown: PayPal
+ # refuses an order whose breakdown does not add up, and 6.0 carts carry fees,
+ # line discounts, included tax and store credit a breakdown may not express.
+ class OrderPresenter
+ include PaypalServerSdk
+
+ ITEM_NAME_MAX_LENGTH = 127
+
+ # @param order [Spree::Cart, Spree::Order]
+ # @param amount [BigDecimal] what the session charges
+ # @param intent [String] CheckoutPaymentIntent::CAPTURE or ::AUTHORIZE
+ def initialize(order:, amount:, intent:)
+ @order = order
+ @amount = amount
+ @intent = intent
+ end
+
+ # @return [PaypalServerSdk::OrderRequest]
+ def order_request
+ OrderRequest.new(
+ intent: intent,
+ purchase_units: [purchase_unit],
+ application_context: OrderApplicationContext.new(
+ brand_name: order.store.name.to_s.first(127),
+ shipping_preference: shipping_details ? OrderApplicationContextShippingPreference::SET_PROVIDED_ADDRESS : OrderApplicationContextShippingPreference::NO_SHIPPING
+ )
+ )
+ end
+
+ # @return [PaypalServerSdk::PurchaseUnitRequest]
+ def purchase_unit
+ items = paypal_items
+ breakdown = items && amount_breakdown
+
+ # Every SDK model has its own "not sent" sentinel, so absent fields are
+ # left out of the arguments instead.
+ PurchaseUnitRequest.new(**{
+ amount: AmountWithBreakdown.new(**{
+ currency_code: currency,
+ value: Amounts.to_paypal(amount, currency),
+ breakdown: breakdown
+ }.compact),
+ items: (items if breakdown),
+ custom_id: order.prefixed_id,
+ shipping: shipping_details
+ }.compact)
+ end
+
+ private
+
+ attr_reader :order, :amount, :intent
+
+ def currency
+ order.currency.upcase
+ end
+
+ # nil when the parts do not add up to the amount charged, or any of them
+ # cannot be written in PayPal's precision.
+ def amount_breakdown
+ item_total = line_items.sum { |line_item| line_item.price * line_item.quantity }
+ shipping = order.delivery_total
+ tax_total = order.additional_tax_total
+ handling = order.fee_total
+ discount = -order.discount_total + order.total_applied_store_credit
+
+ parts = [item_total, shipping, tax_total, handling, discount]
+ return if parts.any?(&:negative?)
+ return if item_total != order.item_total
+ return if item_total + shipping + tax_total + handling - discount != amount
+
+ AmountBreakdown.new(
+ item_total: money(item_total),
+ shipping: money(shipping),
+ tax_total: money(tax_total),
+ handling: money(handling),
+ discount: money(discount)
+ )
+ rescue Amounts::UnsupportedAmount
+ nil
+ end
+
+ # nil when a unit price cannot be written in PayPal's precision, such as a
+ # price quoted below the minor unit.
+ def paypal_items
+ line_items.map do |line_item|
+ ItemRequest.new(**{
+ name: line_item.name.to_s.first(ITEM_NAME_MAX_LENGTH),
+ unit_amount: money(line_item.price),
+ quantity: line_item.quantity.to_s,
+ sku: line_item.sku.presence,
+ category: line_item.digital? ? ItemCategory::DIGITAL_GOODS : ItemCategory::PHYSICAL_GOODS
+ }.compact)
+ end
+ rescue Amounts::UnsupportedAmount
+ nil
+ end
+
+ # Only an address the buyer cannot change in PayPal's window, and none at
+ # all when nothing ships, so PayPal never collects one Spree did not price.
+ def shipping_details
+ return @shipping_details if defined?(@shipping_details)
+
+ address = order.ship_address
+ @shipping_details = if address.present? && address.address1.present? && order.shipping_address_required?
+ ShippingDetails.new(
+ name: ShippingName.new(full_name: address.full_name.to_s.first(300)),
+ address: Address.new(**{
+ address_line_1: address.address1,
+ address_line_2: address.address2.presence,
+ admin_area_2: address.city.presence,
+ admin_area_1: address.state_code.presence,
+ postal_code: address.postal_code.presence,
+ country_code: address.country_code
+ }.compact)
+ )
+ end
+ end
+
+ def line_items
+ # Delivery profiles decide whether a line is digital.
+ @line_items ||= order.line_items.includes(variant: [:delivery_profile, { product: :delivery_profile }]).to_a
+ end
+
+ def money(value)
+ Amounts.to_paypal_money(value, currency)
+ end
+ end
+end
diff --git a/spree/providers/paypal/spec/models/spree_paypal_checkout/amounts_spec.rb b/spree/providers/paypal/spec/models/spree_paypal_checkout/amounts_spec.rb
new file mode 100644
index 0000000000..3776e6dfc8
--- /dev/null
+++ b/spree/providers/paypal/spec/models/spree_paypal_checkout/amounts_spec.rb
@@ -0,0 +1,63 @@
+require 'spec_helper'
+
+RSpec.describe SpreePaypalCheckout::Amounts do
+ describe '.to_paypal' do
+ it 'writes two-decimal currencies with both decimals' do
+ expect(described_class.to_paypal(BigDecimal('19.9'), 'USD')).to eq('19.90')
+ expect(described_class.to_paypal(BigDecimal('20'), 'eur')).to eq('20.00')
+ end
+
+ it 'writes HUF, JPY and TWD in whole units' do
+ expect(described_class.to_paypal(BigDecimal('2000'), 'JPY')).to eq('2000')
+ expect(described_class.to_paypal(BigDecimal('1500.00'), 'HUF')).to eq('1500')
+ expect(described_class.to_paypal(BigDecimal('300'), 'TWD')).to eq('300')
+ end
+
+ it 'takes a Spree::Money' do
+ expect(described_class.to_paypal(Spree::Money.new(BigDecimal('12.5'), currency: 'USD'), 'USD')).to eq('12.50')
+ end
+
+ it 'raises for a JPY amount with a fraction instead of rounding it' do
+ expect { described_class.to_paypal(BigDecimal('100.5'), 'JPY') }.
+ to raise_error(described_class::UnsupportedAmount, 'PayPal takes JPY only in whole units, got 100.5')
+ end
+
+ it 'raises for HUF with a fraction, which ISO writes with decimals' do
+ expect { described_class.to_paypal(BigDecimal('99.99'), 'HUF') }.
+ to raise_error(described_class::UnsupportedAmount, /HUF only in whole units/)
+ end
+
+ it 'raises for more decimals than the currency has' do
+ expect { described_class.to_paypal(BigDecimal('10.005'), 'USD') }.
+ to raise_error(described_class::UnsupportedAmount, 'PayPal takes USD only to 2 decimal places, got 10.005')
+ end
+
+ it 'raises for a currency PayPal does not take' do
+ expect { described_class.to_paypal(BigDecimal('10'), 'KWD') }.
+ to raise_error(described_class::UnsupportedAmount, 'PayPal does not take KWD')
+ end
+
+ it 'is a gateway error' do
+ expect(described_class::UnsupportedAmount.ancestors).to include(Spree::Core::GatewayError)
+ end
+ end
+
+ describe '.payable?' do
+ it { expect(described_class.payable?(BigDecimal('1234'), 'TWD')).to be(true) }
+ it { expect(described_class.payable?(BigDecimal('1234.5'), 'TWD')).to be(false) }
+ it { expect(described_class.payable?(BigDecimal('10'), 'INR')).to be(false) }
+ end
+
+ describe '.supported_currency?' do
+ it { expect(described_class.supported_currency?('usd')).to be(true) }
+ it { expect(described_class.supported_currency?('INR')).to be(false) }
+ end
+
+ describe '.to_paypal_money' do
+ it 'builds the SDK money model' do
+ money = described_class.to_paypal_money(BigDecimal('5'), 'usd')
+
+ expect(money.to_hash).to eq('currency_code' => 'USD', 'value' => '5.00')
+ 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 308d8efbaa..01dbadade6 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
@@ -37,4 +37,38 @@ RSpec.describe SpreePaypalCheckout::Gateway do
it 'takes money amounts' do
expect(described_class.accepts_money_amounts).to be(true)
end
+
+ describe '#available_for_order?' do
+ let(:cart) { create(:cart_with_line_items, store: store) }
+
+ it 'is true for a currency PayPal takes' do
+ expect(gateway.available_for_order?(cart)).to be(true)
+ end
+
+ it 'is false for a currency PayPal does not take' do
+ cart.update_columns(currency: 'INR')
+
+ expect(gateway.available_for_order?(cart)).to be(false)
+ end
+ end
+
+ describe '#paypal_intent' do
+ it 'captures for a method that captures at checkout' do
+ gateway.update!(capture_method: 'checkout')
+
+ expect(gateway.paypal_intent).to eq('CAPTURE')
+ end
+
+ it 'authorizes for a method that captures on dispatch' do
+ gateway.update!(capture_method: 'on_dispatch')
+
+ expect(gateway.paypal_intent).to eq('AUTHORIZE')
+ end
+
+ it 'authorizes for a method captured by hand' do
+ gateway.update!(capture_method: 'manual')
+
+ expect(gateway.paypal_intent).to eq('AUTHORIZE')
+ end
+ end
end
diff --git a/spree/providers/paypal/spec/presenters/spree_paypal_checkout/order_presenter_spec.rb b/spree/providers/paypal/spec/presenters/spree_paypal_checkout/order_presenter_spec.rb
new file mode 100644
index 0000000000..3d68eae280
--- /dev/null
+++ b/spree/providers/paypal/spec/presenters/spree_paypal_checkout/order_presenter_spec.rb
@@ -0,0 +1,168 @@
+require 'spec_helper'
+
+RSpec.describe SpreePaypalCheckout::OrderPresenter do
+ subject(:request) { described_class.new(order: cart, amount: amount, intent: intent).order_request.to_hash }
+
+ let(:store) { @default_store }
+ let(:cart) { create(:cart_ready_for_delivery, store: store, line_items_count: 2, line_items_price: BigDecimal('10')) }
+ let(:amount) { cart.total_minus_store_credits }
+ let(:intent) { 'CAPTURE' }
+ let(:purchase_unit) { request['purchase_units'].first }
+
+ it 'charges the amount in PayPal precision with the cart as custom_id' do
+ expect(purchase_unit['amount']['currency_code']).to eq('USD')
+ expect(purchase_unit['amount']['value']).to eq(format('%.2f', amount))
+ expect(purchase_unit['custom_id']).to eq(cart.prefixed_id)
+ expect(purchase_unit).not_to have_key('invoice_id')
+ end
+
+ it 'passes the intent and the store name' do
+ expect(request['intent']).to eq('CAPTURE')
+ expect(request['application_context']['brand_name']).to eq(store.name)
+ end
+
+ context 'when the cart adds up' do
+ it 'sends the items and the breakdown' do
+ breakdown = purchase_unit['amount']['breakdown']
+
+ expect(breakdown['item_total']['value']).to eq('20.00')
+ expect(breakdown['shipping']['value']).to eq(format('%.2f', cart.delivery_total))
+ expect(breakdown['tax_total']['value']).to eq(format('%.2f', cart.additional_tax_total))
+ expect(breakdown['handling']['value']).to eq('0.00')
+ expect(breakdown['discount']['value']).to eq('0.00')
+
+ expect(purchase_unit['items'].size).to eq(2)
+ expect(purchase_unit['items'].first).to include(
+ 'unit_amount' => { 'currency_code' => 'USD', 'value' => '10.00' },
+ 'quantity' => '1',
+ 'category' => 'PHYSICAL_GOODS'
+ )
+ end
+
+ it 'sends fees as handling and promotions and store credit as discount' do
+ cart.update_columns(
+ fee_total: BigDecimal('4'),
+ discount_total: BigDecimal('-3'),
+ total: cart.total + BigDecimal('1')
+ )
+ allow(cart).to receive(:total_applied_store_credit).and_return(BigDecimal('5'))
+ breakdown = described_class.new(order: cart, amount: cart.total - 5, intent: intent).
+ order_request.to_hash['purchase_units'].first['amount']['breakdown']
+
+ expect(breakdown['handling']['value']).to eq('4.00')
+ expect(breakdown['discount']['value']).to eq('8.00')
+ end
+ end
+
+ context 'when the cart does not add up' do
+ shared_examples 'the amount alone' do
+ it 'sends no items or breakdown' do
+ expect(purchase_unit['amount']).not_to have_key('breakdown')
+ expect(purchase_unit).not_to have_key('items')
+ expect(purchase_unit['amount']['value']).to eq(format('%.2f', amount))
+ end
+ end
+
+ context 'with a fee the total does not carry' do
+ before { cart.update_columns(fee_total: BigDecimal('2.5')) }
+
+ it_behaves_like 'the amount alone'
+ end
+
+ context 'with a line discount that leaves the item total apart from the lines' do
+ before { cart.update_columns(item_total: cart.item_total - 2, total: cart.total - 2) }
+
+ it_behaves_like 'the amount alone'
+ end
+
+ context 'with included tax counted on top of the lines' do
+ before { cart.update_columns(included_tax_total: BigDecimal('1.5'), total: cart.total + BigDecimal('1.5')) }
+
+ it_behaves_like 'the amount alone'
+ end
+
+ context 'with store credit that does not account for the amount' do
+ let(:amount) { cart.total - 7 }
+
+ before { allow(cart).to receive(:total_applied_store_credit).and_return(BigDecimal('5')) }
+
+ it_behaves_like 'the amount alone'
+ end
+ end
+
+ context 'with a line price PayPal cannot write' do
+ before { cart.line_items.first.update_columns(price: BigDecimal('10.125')) }
+
+ it 'sends the amount alone' do
+ expect(purchase_unit['amount']).not_to have_key('breakdown')
+ end
+ end
+
+ context 'with unit prices below the minor unit that still add up' do
+ before do
+ first, second = cart.line_items.to_a
+ first.update_columns(price: BigDecimal('10.005'))
+ second.update_columns(price: BigDecimal('9.995'))
+ end
+
+ it 'sends the amount alone instead of refusing the order' do
+ expect(purchase_unit['amount']).not_to have_key('breakdown')
+ expect(purchase_unit).not_to have_key('items')
+ end
+ end
+
+ context 'with an authorizing method' do
+ let(:intent) { 'AUTHORIZE' }
+
+ it { expect(request['intent']).to eq('AUTHORIZE') }
+ end
+
+ context 'with a shipping address' do
+ it 'fixes it so the buyer cannot change it in PayPal' do
+ address = cart.ship_address
+
+ expect(request['application_context']['shipping_preference']).to eq('SET_PROVIDED_ADDRESS')
+ expect(purchase_unit['shipping']).to eq(
+ 'name' => { 'full_name' => address.full_name },
+ 'address' => {
+ 'address_line_1' => address.address1,
+ 'address_line_2' => address.address2,
+ 'admin_area_2' => address.city,
+ 'admin_area_1' => address.state_code,
+ 'postal_code' => address.postal_code,
+ 'country_code' => 'US'
+ }.compact
+ )
+ end
+ end
+
+ context 'with a digital-only cart' do
+ before do
+ allow(cart).to receive(:shipping_address_required?).and_return(false)
+ cart.line_items.each { |line_item| allow(line_item).to receive(:digital?).and_return(true) }
+ end
+
+ it 'asks PayPal to collect no shipping address' do
+ expect(request['application_context']['shipping_preference']).to eq('NO_SHIPPING')
+ expect(purchase_unit).not_to have_key('shipping')
+ end
+ end
+
+ context 'with a long item name' do
+ before { cart.line_items.first.product.update_columns(name: 'x' * 200) }
+
+ it 'cuts it to 127 characters' do
+ expect(purchase_unit['items'].map { |item| item['name'].length }).to include(127)
+ end
+ end
+
+ context 'with a JPY amount with a fraction' do
+ let(:amount) { BigDecimal('100.5') }
+
+ before { cart.update_columns(currency: 'JPY') }
+
+ it 'raises instead of rounding' do
+ expect { request }.to raise_error(SpreePaypalCheckout::Amounts::UnsupportedAmount)
+ end
+ end
+end