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
Changed payment gateways to receive amounts with their currency
Damian Legawieca7252c64ea8e
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdxindex ea1d6a5fc9..1840e91ee0 100644--- a/docs/developer/upgrades/5.6-to-6.0.mdx+++ b/docs/developer/upgrades/5.6-to-6.0.mdx@@ -822,7 +822,8 @@ Other changes that come with it:- **Numbers are no longer parsed by locale.** Price, variant, payment, refund, store credit, gift card, discount and fee amounts take a number or a canonical decimal string (`"1234.56"`); any other text raises `Spree::Money::InvalidFormat`, which the API answers with `invalid_money_format`. Before 6.0 they were re-read under the request's language, so a store whose language writes a comma decimal (Dutch, German, French) saved the dashboard's `49.50` as 4950, and an unchanged price grew tenfold on each save. Send canonical decimal strings (`"1234.56"`) and convert localized input in the client. `Spree::LocalizedNumber` still works with a warning until 6.1. If your prices were saved in a comma-decimal store before upgrading, check them.- **Rounding follows the currency.** Taxes, percentage discounts, promotion splits and shipping markups round to the currency's own decimal places from the ISO 4217 table: whole yen, three decimals for dinar. Two-decimal currencies are unchanged. Open carts in other currencies may change by less than one minor unit the next time they are recalculated. Placed orders do not change. Spree now gives the Hungarian forint two decimal places, as ISO 4217 does.-- **Capture records in yen and dinar may be wrong.** An admin capture in a currency without two decimals is recorded in the wrong unit: 100 times too much in yen, a tenth in dinar. This is fixed when gateways start receiving amounts with their currency, later in 6.0. To list the affected records, writing nothing, run:+- **Payment gateways receive the amount with its currency.** `authorize`, `purchase`, `capture` and `credit` are called with a `Spree::Money` (amount and currency) instead of an integer in hundredths, which was wrong for yen and dinar. A gateway opts in with `self.accepts_money_amounts = true` and converts the amount to its provider's unit (Stripe's rules live in `SpreeStripe::Units`). A gateway that has not opted in still receives hundredths, with a deprecation warning, until 6.1. `Spree.payment_capture_workflow.call(amount:)` takes the amount in the currency's own units; an Integer is still read as hundredths, with a warning.+- **Capture records in yen and dinar written before 6.0 may be wrong.** A capture in a currency without two decimals could be recorded in the wrong unit: 100 times too much in yen, a tenth in dinar. New captures are recorded exactly. To list the old records, writing nothing, run:<CodeGroup>@@ -896,6 +897,8 @@ Before 6.0 a cart was an incomplete order, so extensions written for 5.x (paymen| `Spree.metafields` | `Spree.custom_fields` || `Spree.t`, `Spree.translate` | `I18n.t` with the full key, e.g. `I18n.t('spree.free')` || `Spree::LocalizedNumber.parse` | `BigDecimal(value)` on a canonical decimal string; Spree no longer parses numbers by locale |+| Gateway methods receiving an integer amount in hundredths | `self.accepts_money_amounts = true` and a `Spree::Money` argument |+| `Spree.payment_capture_workflow.call(amount: Integer)` (hundredths) | `amount:` as a `BigDecimal` in the currency's own units || `CustomFieldDefinition#name`, `#metafield_type`, `#display_on` | `#label`, `#field_type`, `#storefront_visible` (columns renamed) || `Spree::SearchProvider::Meilisearch` | `SpreeMeilisearch::SearchProvider` (moved to the `spree_meilisearch` gem) || `Spree::SearchProvider::ProductPresenter` | `SpreeMeilisearch::ProductPresenter` (moved to the `spree_meilisearch` gem) |diff --git a/docs/plans/6.0-money-correctness.md b/docs/plans/6.0-money-correctness.mdindex befdca0764..8d7a3d3dd5 100644--- a/docs/plans/6.0-money-correctness.md+++ b/docs/plans/6.0-money-correctness.md@@ -1,6 +1,6 @@# Money Correctness-**Status:** In Progress — building PR A (floats out); A2 (gateway amounts), B (wire contract) and C (precision) follow+**Status:** In Progress — A (floats out) and A2 (gateway amounts) built on spree/spree#14852; B (wire contract) and C (precision) in progress on the same pull request**Target:** Spree 6.0**Depends on:** `5.5-client-side-money-normalization.md` (canonical decimal-string contract), `6.0-6.1-split-adjustments.md` (typed `spree_tax_lines` / `spree_discounts` / `spree_fees` — landed, so they are in scope), `6.0-json-preferences.md` (decimal preferences are exact strings), `6.0-payment-gateways-monorepo.md` (Stripe lives in the monorepo; Adyen and PayPal Checkout are separate gems patched in the same release)**Author:** Damian + Claude@@ -32,6 +32,8 @@ All decided 2026-10-08; the ones marked *review* were changed or added after the- **Open carts in zero- and three-decimal currencies change on their next recalculation.** Accepted trade-off: a yen total can move by under one yen mid-checkout. Completed orders are frozen and do not change.- **Spree stops parsing numbers by locale** (decided 2026-10-09; supersedes the 5.5 plan's "`LocalizedNumber` is not removed" and this plan's first-pass "out of scope"). The model setters that re-parsed strings with `Spree::LocalizedNumber` under the request locale are replaced by strict ones (`Spree::CanonicalDecimals`): a number or canonical decimal text is stored exactly, and any other text raises `Spree::Money::InvalidFormat` (422 `invalid_money_format` from the API) instead of Rails' lenient cast reading `"1,599.99"` as 1. Why: the legacy admin they served is gone, and under a store whose language writes a comma decimal they misread the dashboard's canonical `"49.50"` as 4950 and grew an untouched `"99.0"` tenfold on every save (a reported bug). `Spree::LocalizedNumber.parse` stays one release as a deprecated method nothing in Spree calls, and is removed in 6.1. The variant's `cost_price`/`weight`/`width`/`height`/`depth` writers keep ignoring a blank value. Ships in PR A.- **The dashboard shows and reads money in the admin's own number format** (decided 2026-10-09, following Shopify; supersedes the 5.5 plan's "currency's market locale"). `useMoneyLocale()` returns the dashboard language; every money field formats and normalizes through it, whatever the currency or market. Why: a store can have several markets with one currency and different conventions (EUR in Germany and Ireland), so the market-based format depended on which market loaded first; the person typing knows their own convention, and the old reason against it, server re-parsing, is gone. Accepted trade-off: a German-speaking admin of a US store sees `1234,56` for dollars. Ships in PR A.+- **All four parts ship on one pull request** (decided 2026-10-09; supersedes "four pull requests"). A2, B and C land as their own commit series on spree/spree#14852, so nothing ships half-done; A2 is still revertible by its commits.+- **`spree_adyen` and `spree_paypal_checkout` are not patched in their Spree 5 repositories** (decided 2026-10-09; amends "patch the gems you own in the same release"). Their `main` branches still target Spree 5 (`spree_admin`), where this API does not exist. Adyen takes money amounts when it is ported into `spree/providers` (constraint added to `6.0-payment-gateways-monorepo.md`); PayPal and third-party gateways keep working through the hundredths bridge until 6.1.- **PR A applies the ISO table to Spree's own rounding only; registering it over the Money gem moves to A2** (decided 2026-10-09). Registering changes `Money#cents` for HUF, which Stripe payment sessions read, and A2 is the only PR that may change what a gateway receives.## Design Detailsdiff --git a/docs/plans/6.0-payment-gateways-monorepo.md b/docs/plans/6.0-payment-gateways-monorepo.mdindex 41358671ed..cb3db96e82 100644--- a/docs/plans/6.0-payment-gateways-monorepo.md+++ b/docs/plans/6.0-payment-gateways-monorepo.md@@ -250,6 +250,7 @@ admin" with no conditional-SDK logic. Webhook endpoints are the core v3 ones## Constraints on Current Work+- **The Adyen port takes amounts as `Spree::Money`** (`self.accepts_money_amounts = true`) and converts them to Adyen's own minor units in the adapter, as `SpreeStripe::Units` does for Stripe (`6.0-money-correctness.md`, 2026-10-09). Gateways that have not opted in still receive hundredths, with a deprecation warning, until 6.1.- **No new feature work in the standalone `spree_stripe`/`spree_adyen` repos**— critical fixes only. New gateway capability lands in the monorepo port.- **Don't rename the `SpreeStripe`/`SpreeAdyen` namespaces** anywhere (docs,diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rbindex ff38b903f2..34b9ec99c8 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rb@@ -56,9 +56,6 @@ module Spreeunless amount.nil? || amount.positive?raise Spree::Money::InvalidFormat.new('must be greater than 0', field: :amount)end- amount = Spree::Money::Rounding.to_hundredths(amount) if amount- # A thousandth of a dinar is below what gateways are sent in.- raise Spree::Money::InvalidFormat.new('is too small to capture', field: :amount) if amount&.zero?result = Spree.payment_capture_workflow.call(payment: @resource, amount: amount)diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rbindex 2c30f0b534..1a15a6839e 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb@@ -177,13 +177,13 @@ RSpec.describe Spree::Api::V3::Admin::Orders::PaymentsController, type: :controlcontext 'with a partial amount' doit 'still accepts a JSON number' do- expect(Spree.payment_capture_workflow).to receive(:call).with(payment: payment, amount: 115).and_call_original+ expect(Spree.payment_capture_workflow).to receive(:call).with(payment: payment, amount: BigDecimal('1.15')).and_call_originalpatch :capture, params: { order_id: order_with_payment.prefixed_id, id: payment.prefixed_id, amount: 1.15 }, as: :jsonend- it 'hands the gateway exact hundredths' do- expect(Spree.payment_capture_workflow).to receive(:call).with(payment: payment, amount: 115).and_call_original+ it 'hands the workflow the exact amount' do+ expect(Spree.payment_capture_workflow).to receive(:call).with(payment: payment, amount: BigDecimal('1.15')).and_call_originalpatch :capture, params: {order_id: order_with_payment.prefixed_id,@@ -192,16 +192,6 @@ RSpec.describe Spree::Api::V3::Admin::Orders::PaymentsController, type: :control}, as: :jsonend- it 'refuses a dinar amount too small to send to a gateway' do- order_with_payment.update_columns(currency: 'KWD')- expect(Spree.payment_capture_workflow).not_to receive(:call)-- patch :capture, params: { order_id: order_with_payment.prefixed_id, id: payment.prefixed_id, amount: '0.001' }, as: :json-- expect(response).to have_http_status(:unprocessable_content)- expect(json_response['error']['code']).to eq('invalid_money_format')- end-['1,15', '1.155', '-5.00', '0', 'abc'].each do |amount|it "refuses #{amount.inspect} with invalid_money_format" doexpect(Spree.payment_capture_workflow).not_to receive(:call)diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rbindex 39ba5bf3b7..ec118c3932 100644--- a/spree/core/app/models/spree/fulfillment.rb+++ b/spree/core/app/models/spree/fulfillment.rb@@ -895,10 +895,7 @@ module Spreedef capture_at_gateway(payment, amount)return 0 if amount <= 0- # The Money gem's minor units, as gateways have always been sent from- # here; amounts that carry their currency replace this (money plan, A2).- units = ::Money.from_amount(amount, payment.currency).cents- result = Spree.payment_capture_workflow.call(payment: payment, amount: units)+ result = Spree.payment_capture_workflow.call(payment: payment, amount: amount)raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?amountdiff --git a/spree/core/app/models/spree/gateway/bogus.rb b/spree/core/app/models/spree/gateway/bogus.rbindex 65ddfd543e..ed0c8b0e80 100644--- a/spree/core/app/models/spree/gateway/bogus.rb+++ b/spree/core/app/models/spree/gateway/bogus.rb@@ -1,5 +1,7 @@module Spreeclass Gateway::Bogus < Gateway+ self.accepts_money_amounts = true+TEST_VISA = ['4111111111111111', '4012888888881881', '4222222222222']TEST_MC = ['5500000000000004', '5555555555554444', '5105105105105100', '2223000010309703']TEST_AMEX = ['378282246310005', '371449635398431', '378734493671000', '340000000000009']diff --git a/spree/core/app/models/spree/payment_method.rb b/spree/core/app/models/spree/payment_method.rbindex 8871ab5bbe..e02e1e9ae8 100644--- a/spree/core/app/models/spree/payment_method.rb+++ b/spree/core/app/models/spree/payment_method.rb@@ -20,6 +20,13 @@ module Spreeinclude Spree::Security::PaymentMethodsend+ # Whether authorize, purchase, capture and credit take the amount as a+ # Spree::Money (amount and currency) and convert it to the provider's own+ # unit. Methods that have not opted in receive an integer in hundredths of+ # the currency, which is wrong for yen and dinar; that bridge is removed in+ # Spree 6.1.+ class_attribute :accepts_money_amounts, default: false, instance_writer: false+# Blank falls back to the store, so a method only overrides when a merchant# deliberately picks one — the meaning the auto_capture boolean already had.normalizes :capture_method, with: ->(value) { value.presence }@@ -339,6 +346,20 @@ module Spreeself.storefront_visible = value.to_s != 'back_end'end++ # The amount in the form this payment method's gateway calls take.+ #+ # @param amount [BigDecimal] in the currency's own units ("19.99")+ # @param currency [String]+ # @return [Spree::Money, Integer] a Spree::Money for methods that accept+ # money amounts, otherwise hundredths of the currency (deprecated)+ def gateway_amount(amount, currency)+ return Spree::Money.new(amount, currency: currency) if accepts_money_amounts++ warn_about_hundredths+ Spree::Money::Rounding.to_hundredths(amount)+ end+protecteddef public_preference_keys@@ -348,5 +369,16 @@ module Spreedef set_nameself.name ||= default_nameend++ def warn_about_hundredths+ return if self.class.instance_variable_get(:@warned_about_hundredths)++ self.class.instance_variable_set(:@warned_about_hundredths, true)+ Spree::Deprecation.warn(+ "#{self.class.name} receives amounts as an integer in hundredths, which is wrong for currencies " \+ 'without two decimals. Set `self.accepts_money_amounts = true` and take a Spree::Money ' \+ '(amount and currency); hundredths are removed in Spree 6.1.'+ )+ endendenddiff --git a/spree/core/app/models/spree/payment_method/check.rb b/spree/core/app/models/spree/payment_method/check.rbindex a3830b5e18..b08fb20f44 100644--- a/spree/core/app/models/spree/payment_method/check.rb+++ b/spree/core/app/models/spree/payment_method/check.rb@@ -1,5 +1,7 @@module Spreeclass PaymentMethod::Check < ::Spree::PaymentMethod+ self.accepts_money_amounts = true+def actions%w{capture void}enddiff --git a/spree/core/app/models/spree/payment_method/store_credit.rb b/spree/core/app/models/spree/payment_method/store_credit.rbindex 0c67769240..11e5d88f65 100644--- a/spree/core/app/models/spree/payment_method/store_credit.rb+++ b/spree/core/app/models/spree/payment_method/store_credit.rb@@ -1,5 +1,7 @@module Spreeclass PaymentMethod::StoreCredit < ::Spree::PaymentMethod+ self.accepts_money_amounts = true+def payment_source_class::Spree::StoreCreditend@@ -20,13 +22,13 @@ module Spreepayment.pending?end- def authorize(amount_in_cents, store_credit, gateway_options = {})+ def authorize(money, store_credit, gateway_options = {})if store_credit.nil?Spree::PaymentResponse.new(false, I18n.t('spree.store_credit_payment_method.unable_to_find'), {}, {})elseaction = lambda do |store_credit|store_credit.authorize(- Spree::Money::Rounding.from_hundredths(amount_in_cents),+ money.to_d,gateway_options[:currency],action_originator: gateway_options[:originator])@@ -35,10 +37,10 @@ module Spreeendend- def capture(amount_in_cents, auth_code, gateway_options = {})+ def capture(money, auth_code, gateway_options = {})action = lambda do |store_credit|store_credit.capture(- Spree::Money::Rounding.from_hundredths(amount_in_cents),+ money.to_d,auth_code,gateway_options[:currency],action_originator: gateway_options[:originator]@@ -47,9 +49,9 @@ module Spreehandle_action(action, :capture, auth_code)end- def purchase(amount_in_cents, store_credit, gateway_options = {})+ def purchase(money, store_credit, gateway_options = {})eligible_events = store_credit.store_credit_events.where(- amount: Spree::Money::Rounding.from_hundredths(amount_in_cents),+ amount: money.to_d,action: Spree::StoreCredit::ELIGIBLE_ACTION)event = eligible_events.detect do |eligible_event|@@ -60,7 +62,7 @@ module Spreeif event.blank?Spree::PaymentResponse.new(false, I18n.t('spree.store_credit_payment_method.unable_to_find'), {}, {})else- capture(amount_in_cents, event.authorization_code, gateway_options)+ capture(money, event.authorization_code, gateway_options)endend@@ -71,12 +73,12 @@ module Spreehandle_action(action, :void, auth_code)end- def credit(amount_in_cents, auth_code, gateway_options)+ def credit(money, auth_code, gateway_options)action = lambda do |store_credit|currency = gateway_options[:currency] || store_credit.currencyoriginator = gateway_options[:originator]- store_credit.credit(Spree::Money::Rounding.from_hundredths(amount_in_cents), auth_code, currency, action_originator: originator)+ store_credit.credit(money.to_d, auth_code, currency, action_originator: originator)endhandle_action(action, :credit, auth_code)diff --git a/spree/core/app/models/spree/refund.rb b/spree/core/app/models/spree/refund.rbindex b08a0a31b2..c89f90c21f 100644--- a/spree/core/app/models/spree/refund.rb+++ b/spree/core/app/models/spree/refund.rb@@ -120,9 +120,7 @@ module Spreedef perform!return true if transaction_id.present?- credit_cents = Spree::Money.new(amount, currency: currency).amount_in_cents-- @response = process!(credit_cents)+ @response = process!(payment.payment_method.gateway_amount(amount, currency))self.transaction_id = @response.authorizationupdate_columns(transaction_id: transaction_id)@@ -165,19 +163,20 @@ module Spreeend# return a payment response object if successful or else raise an error- def process!(credit_cents)- refund_total_in_cents = calculate_refund_amount(credit_cents)+ # @param credit_amount [Spree::Money, Integer] as PaymentMethod#gateway_amount returns it+ def process!(credit_amount)+ refund_total = calculate_refund_amount(credit_amount)response = instrument_gateway_call(:credit, payment.payment_method) doif payment.payment_method.payment_profiles_supported?- payment.payment_method.credit(refund_total_in_cents, payment.source, payment.transaction_id, originator: self)+ payment.payment_method.credit(refund_total, payment.source, payment.transaction_id, originator: self)else- payment.payment_method.credit(refund_total_in_cents, payment.transaction_id, originator: self)+ payment.payment_method.credit(refund_total, payment.transaction_id, originator: self)endendif response.success?- track_order_as_refunded(refund_total_in_cents)+ track_order_as_refunded(refund_total)elseRails.logger.error(I18n.t('spree.gateway_error') + " #{response.to_yaml}")text = response.params['message'] || response.params['response_reason_text'] || response.message@@ -190,12 +189,12 @@ module Spreeraise Core::GatewayError, I18n.t('spree.unable_to_connect_to_gateway')end- def calculate_refund_amount(credit_cents)+ def calculate_refund_amount(credit_amount)# Overwrite this for more complex calculations- credit_cents+ credit_amountend- def track_order_as_refunded(credit_cents)+ def track_order_as_refunded(credit_amount)# You can track refunds hereenddiff --git a/spree/core/app/workflows/spree/payments/capture.rb b/spree/core/app/workflows/spree/payments/capture.rbindex 294592db89..764bc61125 100644--- a/spree/core/app/workflows/spree/payments/capture.rb+++ b/spree/core/app/workflows/spree/payments/capture.rb@@ -14,11 +14,13 @@ module Spreehooks :validate, :before_capture, :after_capture# @param payment [Spree::Payment] a completed payment is a no-op- # @param amount [Integer, nil] amount in cents; nil captures in full,- # a smaller amount splits the remainder into a new pending payment+ # @param amount [BigDecimal, nil] in the currency's own units; nil+ # captures in full, a smaller amount splits the remainder into a new+ # pending payment. An Integer is read as hundredths of the currency,+ # the pre-6.0 contract (deprecated, removed in 6.1).def perform(payment:, amount: nil)super- @amount = amount || payment.money.amount_in_cents+ @amount = capture_amount(amount)step :ensure_capturable# Veto point — fraud holds, manual review. Before any money moves.@@ -44,6 +46,17 @@ module Spreeattr_reader :response, :remainder+ def capture_amount(amount)+ return payment.amount if amount.nil?+ return BigDecimal(amount.to_s) unless amount.is_a?(Integer)++ Spree::Deprecation.warn(+ 'Passing an Integer amount to the payment capture workflow is deprecated and is read as hundredths of ' \+ 'the currency. Pass the amount in the currency\'s own units as a BigDecimal; removed in Spree 6.1.'+ )+ Spree::Money::Rounding.from_hundredths(amount)+ end+# An already-captured payment returns success rather than failing:# capture is naturally idempotent and double-submitted admin actions# must not surface as errors. A failed payment is capturable — the@@ -65,7 +78,9 @@ module Spreedef capture_at_gateway@response = payment.protect_from_connection_error doinstrument_gateway_call(:capture, payment.payment_method) do- payment.payment_method.capture(@amount, payment.response_code, payment.gateway_options)+ payment.payment_method.capture(+ payment.payment_method.gateway_amount(@amount, payment.currency), payment.response_code, payment.gateway_options+ )endend@@ -86,9 +101,7 @@ module Spreeif Spree::Payment.where(id: payment.id, status: 'completed').exists?already_captured = trueelse- # Read in the Money gem's minor units, as before; the gateway amount- # carries its currency once A2 lands (money plan).- payment.capture_events.create!(amount: ::Money.new(@amount, payment.currency).to_d)+ payment.capture_events.create!(amount: @amount)# Split before completing, so payment.completed publishes with# the captured amount and the order recomputes from correct rows.@remainder = payment.split_uncaptured_amountdiff --git a/spree/core/app/workflows/spree/payments/process.rb b/spree/core/app/workflows/spree/payments/process.rbindex ba50cc74d0..5cde8acea7 100644--- a/spree/core/app/workflows/spree/payments/process.rb+++ b/spree/core/app/workflows/spree/payments/process.rb@@ -57,7 +57,9 @@ module Spreeresponse = payment.protect_from_connection_error doinstrument_gateway_call(verb, payment.payment_method) do- payment.payment_method.public_send(verb, payment.money.amount_in_cents, payment.source, payment.gateway_options)+ payment.payment_method.public_send(+ verb, payment.payment_method.gateway_amount(payment.amount, payment.currency), payment.source, payment.gateway_options+ )endenddiff --git a/spree/core/lib/spree/money.rb b/spree/core/lib/spree/money.rbindex ee6e8edeab..a43266670f 100644--- a/spree/core/lib/spree/money.rb+++ b/spree/core/lib/spree/money.rb@@ -223,8 +223,28 @@ module Spreedef from_minor_units(units, currency)BigDecimal(units) / (10**precision(currency))end++ # Makes the Money gem agree with {EXPONENTS}, so formatting, `cents`+ # and anything else built on it use ISO 4217 decimals too.+ def register_with_money_gem!+ EXPONENTS.each do |code, exponent|+ subunit_to_unit = 10**exponent+ currency = ::Money::Currency.find(code)++ if currency.nil?+ ::Money::Currency.register(+ iso_code: code, name: code, symbol: code, subunit: nil, subunit_to_unit: subunit_to_unit,+ priority: 100, symbol_first: false, thousands_separator: ',', decimal_mark: '.'+ )+ elsif currency.subunit_to_unit != subunit_to_unit+ ::Money::Currency.inherit(code.downcase.to_sym, subunit_to_unit: subunit_to_unit)+ end+ end+ endend+ Rounding.register_with_money_gem!+include Comparableclass << selfdiff --git a/spree/core/spec/models/spree/payment_method/store_credit_spec.rb b/spree/core/spec/models/spree/payment_method/store_credit_spec.rbindex a825e89316..bc20cc29eb 100644--- a/spree/core/spec/models/spree/payment_method/store_credit_spec.rb+++ b/spree/core/spec/models/spree/payment_method/store_credit_spec.rb@@ -6,19 +6,23 @@ describe Spree::PaymentMethod::StoreCredit dolet(:payment) { create(:payment, order: order) }let(:gateway_options) { payment.gateway_options }+ def money(amount)+ Spree::Money.new(BigDecimal(amount.to_s), currency: 'USD')+ end+context '#authorize' dosubject dodescribed_class.new.authorize(auth_amount, store_credit, gateway_options)end- let(:auth_amount) { store_credit.amount_remaining * 100 }+ let(:auth_amount) { money(store_credit.amount_remaining) }let(:store_credit) { create(:store_credit, store: store) }let(:gateway_options) { super().merge(originator: originator) }let(:originator) { nil }context 'without an invalid store credit' dolet(:store_credit) { nil }- let(:auth_amount) { 10 }+ let(:auth_amount) { money(10) }it 'declines an unknown store credit' doexpect(subject.success?).to be false@@ -27,7 +31,7 @@ describe Spree::PaymentMethod::StoreCredit doendcontext 'with insuffient funds' do- let(:auth_amount) { (store_credit.amount_remaining * 100) + 1 }+ let(:auth_amount) { money(store_credit.amount_remaining + BigDecimal('0.01')) }it 'declines a store credit' doexpect(subject.success?).to be false@@ -64,14 +68,14 @@ describe Spree::PaymentMethod::StoreCredit docontext '#capture' dosubject do- described_class.new.capture(capture_amount, auth_code, gateway_options)+ described_class.new.capture(money(capture_amount), auth_code, gateway_options)end- let(:capture_amount) { 10_00 }+ let(:capture_amount) { BigDecimal('10') }let(:auth_code) { auth_event.authorization_code }let(:gateway_options) { super().merge(originator: originator) }- let(:authorized_amount) { capture_amount / 100.0 }+ let(:authorized_amount) { capture_amount }let(:auth_event) { create(:store_credit_auth_event, store_credit: store_credit, amount: authorized_amount) }let(:store_credit) { create(:store_credit, amount_authorized: authorized_amount, store: store) }let(:originator) { nil }@@ -86,7 +90,7 @@ describe Spree::PaymentMethod::StoreCredit doendcontext 'when unable to authorize the amount' do- let(:authorized_amount) { (capture_amount - 1) / 100 }+ let(:authorized_amount) { capture_amount - BigDecimal('0.01') }before doallow_any_instance_of(Spree::StoreCredit).to receive_messages(authorize: true)@@ -180,7 +184,7 @@ describe Spree::PaymentMethod::StoreCredit dostore_credit.store_credit_events.create!(action: Spree::StoreCredit::CAPTURE_ACTION,amount: amount, authorization_code: auth_code)- response = subject.purchase(amount * 100.0, store_credit, gateway_options)+ response = subject.purchase(money(amount), store_credit, gateway_options)expect(response.success?).to be falseexpect(response.message).to include I18n.t('spree.store_credit_payment_method.unable_to_find')end@@ -192,7 +196,7 @@ describe Spree::PaymentMethod::StoreCredit dostore_credit.store_credit_events.create!(action: Spree::StoreCredit::ELIGIBLE_ACTION,amount: amount, authorization_code: auth_code)- response = subject.purchase(amount * 100.0, store_credit, gateway_options)+ response = subject.purchase(money(amount), store_credit, gateway_options)expect(response.success?).to be trueexpect(response.message).to include I18n.t('spree.store_credit_payment_method.successful_action',action: Spree::StoreCredit::CAPTURE_ACTION)@@ -201,10 +205,10 @@ describe Spree::PaymentMethod::StoreCredit docontext '#credit' dosubject do- described_class.new.credit(credit_amount, auth_code, gateway_options)+ described_class.new.credit(money(credit_amount), auth_code, gateway_options)end- let(:credit_amount) { 100.0 }+ let(:credit_amount) { BigDecimal('1') }let(:auth_code) { auth_event.authorization_code }let(:gateway_options) { super().merge(originator: originator) }let(:auth_event) { create(:store_credit_auth_event) }diff --git a/spree/core/spec/models/spree/payment_method_spec.rb b/spree/core/spec/models/spree/payment_method_spec.rbindex 80bd883fb2..ca0fa80fbb 100644--- a/spree/core/spec/models/spree/payment_method_spec.rb+++ b/spree/core/spec/models/spree/payment_method_spec.rb@@ -117,6 +117,22 @@ describe Spree::PaymentMethod, type: :model doendend+ describe '#gateway_amount' do+ it 'hands a method that takes money amounts the amount with its currency' do+ method = Spree::Gateway::Bogus.new++ expect(method.gateway_amount(BigDecimal('1000'), 'JPY')).to eq(Spree::Money.new(BigDecimal('1000'), currency: 'JPY'))+ end++ it 'hands any other method hundredths, warning once that the bridge is going' do+ legacy = Class.new(Spree::PaymentMethod) { def self.name = 'LegacyGateway' }.new+ expect(Spree::Deprecation).to receive(:warn).once.with(/accepts_money_amounts/)++ expect(legacy.gateway_amount(BigDecimal('19.99'), 'USD')).to eq(1999)+ expect(legacy.gateway_amount(BigDecimal('1000'), 'JPY')).to eq(100_000)+ end+ end+describe '#auto_capture?' doclass TestGateway < Spree::Gatewaydef provider_classdiff --git a/spree/core/spec/models/spree/payment_spec.rb b/spree/core/spec/models/spree/payment_spec.rbindex 944d720e09..d55a474c8e 100644--- a/spree/core/spec/models/spree/payment_spec.rb+++ b/spree/core/spec/models/spree/payment_spec.rb@@ -27,7 +27,7 @@ describe Spree::Payment, type: :model dopaymentend- let(:amount_in_cents) { (payment.amount * 100).round }+ let(:gateway_amount) { Spree::Money.new(payment.amount, currency: payment.currency) }let!(:success_response) doSpree::PaymentResponse.new(true, '', {}, authorization: '123',@@ -321,7 +321,7 @@ describe Spree::Payment, type: :model dodescribe '#authorize!' doit 'calls authorize on the gateway with the payment amount' do- expect(payment.payment_method).to receive(:authorize).with(amount_in_cents,+ expect(payment.payment_method).to receive(:authorize).with(gateway_amount,card,anything).and_return(success_response)payment.authorize!@@ -329,7 +329,7 @@ describe Spree::Payment, type: :model doit 'calls authorize on the gateway with the currency code' doallow(payment).to receive_messages currency: 'GBP'- expect(payment.payment_method).to receive(:authorize).with(amount_in_cents,+ expect(payment.payment_method).to receive(:authorize).with(gateway_amount,card,hash_including(currency: 'GBP')).and_return(success_response)payment.authorize!@@ -337,7 +337,7 @@ describe Spree::Payment, type: :model docontext 'if successful' dobefore do- expect(payment.payment_method).to receive(:authorize).with(amount_in_cents,+ expect(payment.payment_method).to receive(:authorize).with(gateway_amount,card,anything).and_return(success_response)end@@ -415,13 +415,13 @@ describe Spree::Payment, type: :model dodescribe '#purchase!' doit 'calls purchase on the gateway with the payment amount' do- expect(gateway).to receive(:purchase).with(amount_in_cents, card, anything).and_return(success_response)+ expect(gateway).to receive(:purchase).with(gateway_amount, card, anything).and_return(success_response)payment.purchase!endcontext 'if successful' dobefore do- expect(payment.payment_method).to receive(:purchase).with(amount_in_cents,+ expect(payment.payment_method).to receive(:purchase).with(gateway_amount,card,anything).and_return(success_response)end@@ -608,7 +608,7 @@ describe Spree::Payment, type: :model docontext 'if successful' docontext 'for entire amount' dobefore do- expect(payment.payment_method).to receive(:capture).with(payment.display_amount.amount_in_cents, payment.response_code, anything).and_return(success_response)+ expect(payment.payment_method).to receive(:capture).with(gateway_amount, payment.response_code, anything).and_return(success_response)endit 'makes payment complete' do@@ -640,12 +640,13 @@ describe Spree::Payment, type: :model doendcontext 'for partial amount' do- let(:original_amount) { payment.money.amount_in_cents }- let(:capture_amount) { original_amount - 100 }+ let(:capture_amount) { payment.amount - 1 }before doallow_any_instance_of(Spree::Payment).to receive(:payment_method_available_for_order).and_return(nil)- expect(payment.payment_method).to receive(:capture).with(capture_amount, payment.response_code, anything).and_return(success_response)+ expect(payment.payment_method).to receive(:capture)+ .with(Spree::Money.new(capture_amount, currency: payment.currency), payment.response_code, anything)+ .and_return(success_response)endit 'makes payment complete & create pending payment for remaining amount' do@@ -657,14 +658,14 @@ describe Spree::Payment, type: :model doexpect(payments.size).to eq 2expect(payments.pending.first.amount).to eq 1# Payment stays processing for spec because of receive(:complete!) stub.- expect(payments.processing.first.amount).to eq(capture_amount / 100)+ expect(payments.processing.first.amount).to eq(capture_amount)expect(payments.processing.first.source).to eq(payments.pending.first.source)endit 'logs capture events' dopayment.capture!(capture_amount)expect(payment.capture_events.count).to eq(1)- expect(payment.capture_events.first.amount).to eq(capture_amount / 100)+ expect(payment.capture_events.first.amount).to eq(capture_amount)endendenddiff --git a/spree/core/spec/models/spree/refund_spec.rb b/spree/core/spec/models/spree/refund_spec.rbindex 39bb1e3537..ad63fef929 100644--- a/spree/core/spec/models/spree/refund_spec.rb+++ b/spree/core/spec/models/spree/refund_spec.rb@@ -25,7 +25,7 @@ describe Spree::Refund, type: :model dolet(:refund) { create(:refund, payment: payment, amount: amount, reason: refund_reason, transaction_id: nil) }let(:amount) { 100.0 }- let(:amount_in_cents) { amount * 100 }+ let(:gateway_amount) { Spree::Money.new(BigDecimal(amount.to_s), currency: payment.currency) }let(:authorization) { generate(:refund_transaction_id) }@@ -51,18 +51,17 @@ describe Spree::Refund, type: :model dobefore doallow(payment.payment_method).to receive(:credit).- with(amount_in_cents, payment.source, payment.transaction_id, originator: an_instance_of(Spree::Refund)).+ with(gateway_amount, payment.source, payment.transaction_id, originator: an_instance_of(Spree::Refund)).and_return(gateway_response)endcontext 'with an amount a float cannot hold exactly' dolet(:amount) { BigDecimal('1.15') }- let(:amount_in_cents) { 115 }- it 'credits the exact hundredths at the gateway' do+ it 'credits the exact amount at the gateway' dosubject- expect(payment.payment_method).to have_received(:credit).with(115, any_args)+ expect(payment.payment_method).to have_received(:credit).with(Spree::Money.new(BigDecimal('1.15'), currency: 'USD'), any_args)endend@@ -139,7 +138,7 @@ describe Spree::Refund, type: :model doit 'does not supply the payment source' doexpect(payment.payment_method).to receive(:credit).- with(amount * 100, payment.transaction_id, originator: an_instance_of(Spree::Refund)).+ with(gateway_amount, payment.transaction_id, originator: an_instance_of(Spree::Refund)).and_return(gateway_response)subject@@ -154,7 +153,7 @@ describe Spree::Refund, type: :model doit 'supplies the payment source' doexpect(payment.payment_method).to receive(:credit).- with(amount_in_cents, payment.source, payment.transaction_id, originator: an_instance_of(Spree::Refund)).+ with(gateway_amount, payment.source, payment.transaction_id, originator: an_instance_of(Spree::Refund)).and_return(gateway_response)subject@@ -164,7 +163,7 @@ describe Spree::Refund, type: :model docontext 'with a gateway connection error' dobefore doexpect(payment.payment_method).to receive(:credit).with(- amount_in_cents,+ gateway_amount,payment.source,payment.transaction_id,originator: an_instance_of(Spree::Refund)diff --git a/spree/core/spec/workflows/spree/payments/capture_spec.rb b/spree/core/spec/workflows/spree/payments/capture_spec.rbindex 12735fd4a7..c6fe3acf78 100644--- a/spree/core/spec/workflows/spree/payments/capture_spec.rb+++ b/spree/core/spec/workflows/spree/payments/capture_spec.rb@@ -18,12 +18,16 @@ RSpec.describe Spree::Payments::Capture doendlet(:failed_response) { Spree::PaymentResponse.new(false, 'card declined') }+ def money(amount, currency = 'USD')+ Spree::Money.new(BigDecimal(amount.to_s), currency: currency)+ end+before { Spree.hooks.clear! }after { Spree.hooks.clear! }describe 'capturing' doit 'captures at the gateway, records the capture event and publishes' do- expect(gateway).to receive(:capture).with(4575, '123', anything).and_return(success_response)+ expect(gateway).to receive(:capture).with(money('45.75'), '123', anything).and_return(success_response)expect(payment).to receive(:publish_event).with('payment.completed')expect(payment).to receive(:publish_event).with('payment.captured')@@ -35,11 +39,11 @@ RSpec.describe Spree::Payments::Capture doendit 'splits a partial capture into a pending remainder and re-authorizes it' do- expect(gateway).to receive(:capture).with(1000, '123', anything).and_return(success_response)+ expect(gateway).to receive(:capture).with(money('10'), '123', anything).and_return(success_response)expect(gateway).to receive(:authorize).and_return(Spree::PaymentResponse.new(true, nil, {}, authorization: '456'))- result = described_class.call(payment: payment, amount: 1000)+ result = described_class.call(payment: payment, amount: BigDecimal('10'))expect(result).to be_successexpect(payment.reload).to be_completed@@ -50,17 +54,46 @@ RSpec.describe Spree::Payments::Capture doendcontext 'with exact amounts' do- { '0.29' => 29, '1.15' => 115, '1234567.89' => 123_456_789 }.each do |amount, hundredths|+ %w[0.29 1.15 1234567.89].each do |amount|it "records a capture of #{amount} to the cent" dopayment.update_columns(amount: BigDecimal(amount))order.update_columns(total: BigDecimal(amount))- expect(gateway).to receive(:capture).with(hundredths, '123', anything).and_return(success_response)+ expect(gateway).to receive(:capture).with(money(amount), '123', anything).and_return(success_response)described_class.call(payment: payment)expect(payment.reload.captured_amount).to eq(BigDecimal(amount))endend++ it 'records a yen capture in yen and hands the gateway yen' do+ payment.update_columns(amount: BigDecimal('1000'))+ order.update_columns(currency: 'JPY', total: BigDecimal('1000'))+ expect(gateway).to receive(:capture).with(money('1000', 'JPY'), '123', anything).and_return(success_response)++ expect(described_class.call(payment: payment)).to be_success++ expect(payment.reload.captured_amount).to eq(BigDecimal('1000'))+ expect(payment.amount).to eq(BigDecimal('1000'))+ end++ it 'records a dinar capture to the thousandth' do+ payment.update_columns(amount: BigDecimal('1.5'))+ order.update_columns(currency: 'KWD', total: BigDecimal('1.5'))+ expect(gateway).to receive(:capture).with(money('1.5', 'KWD'), '123', anything).and_return(success_response)++ described_class.call(payment: payment)++ expect(payment.reload.captured_amount).to eq(BigDecimal('1.5'))+ end++ it 'still reads an Integer amount as hundredths, with a deprecation warning' do+ expect(Spree::Deprecation).to receive(:warn).with(/Integer amount/)+ expect(gateway).to receive(:capture).with(money('10'), '123', anything).and_return(success_response)+ allow(gateway).to receive(:authorize).and_return(Spree::PaymentResponse.new(true, nil, {}, authorization: '456'))++ described_class.call(payment: payment, amount: 1000)+ endendit 'is a no-op for an already-captured payment' do@@ -72,7 +105,7 @@ RSpec.describe Spree::Payments::Capture doit 'retries a failed capture — a failure can be a transient gateway outage' dopayment.update_column(:status, 'failed')- expect(gateway).to receive(:capture).with(4575, '123', anything).and_return(success_response)+ expect(gateway).to receive(:capture).with(money('45.75'), '123', anything).and_return(success_response)result = described_class.call(payment: payment)diff --git a/spree/providers/stripe/app/models/spree_stripe/gateway.rb b/spree/providers/stripe/app/models/spree_stripe/gateway.rbindex 62a35d2f1b..15b8dfb455 100644--- a/spree/providers/stripe/app/models/spree_stripe/gateway.rb+++ b/spree/providers/stripe/app/models/spree_stripe/gateway.rb@@ -3,6 +3,8 @@ module SpreeStripe# created and confirmed through sessions; core's payment lifecycle then drives# capture, refund and cancellation against the resulting intent.class Gateway < ::Spree::Gateway+ self.accepts_money_amounts = true+include SpreeStripe::Gateway::PaymentSessionsinclude SpreeStripe::Gateway::PaymentSetupSessionsinclude SpreeStripe::Gateway::Webhooks@@ -86,26 +88,26 @@ module SpreeStripe# is already confirmed client-side in the session flow, so this reads back the# intent rather than initiating a charge.#- # @param amount_in_cents [Integer]+ # @param money [Spree::Money]# @param payment_source [Spree::PaymentSource, Spree::CreditCard]# @param gateway_options [Hash] Spree::Payment::GatewayOptions#to_hash# @return [Spree::PaymentResponse]- def authorize(amount_in_cents, payment_source, gateway_options = {})- handle_authorize_or_purchase(amount_in_cents, payment_source, gateway_options)+ def authorize(money, payment_source, gateway_options = {})+ handle_authorize_or_purchase(money, payment_source, gateway_options)end# @see #authorize — capture vs authorize is decided by the intent's capture# method, so both resolve the same way.- def purchase(amount_in_cents, payment_source, gateway_options = {})- handle_authorize_or_purchase(amount_in_cents, payment_source, gateway_options)+ def purchase(money, payment_source, gateway_options = {})+ handle_authorize_or_purchase(money, payment_source, gateway_options)end- def capture(amount_in_cents, payment_intent_id, _gateway_options = {})+ def capture(money, payment_intent_id, _gateway_options = {})protect_from_error dostripe_payment_intent = retrieve_payment_intent(payment_intent_id)response = if payment_intent_requires_capture?(stripe_payment_intent)- capture_payment_intent(payment_intent_id, amount_in_cents)+ capture_payment_intent(payment_intent_id, SpreeStripe::Units.to_stripe(money, money.currency))elsif stripe_payment_intent.status == 'succeeded'stripe_payment_intentelse@@ -116,10 +118,10 @@ module SpreeStripeendend- def credit(amount_in_cents, _source, payment_intent_id, _gateway_options = {})+ def credit(money, _source, payment_intent_id, _gateway_options = {})protect_from_error doresponse = send_request do |opts|- Stripe::Refund.create({ amount: amount_in_cents, payment_intent: payment_intent_id }, opts)+ Stripe::Refund.create({ amount: SpreeStripe::Units.to_stripe(money, money.currency), payment_intent: payment_intent_id }, opts)endsuccess(response.id, response)@@ -269,7 +271,7 @@ module SpreeStripeprivate- def handle_authorize_or_purchase(amount_in_cents, _payment_source, gateway_options)+ def handle_authorize_or_purchase(_money, _payment_source, gateway_options)# Scoped through this gateway's own payments — a cart-owned payment# (checkout is still in flight) has no order to join through, and the# payment method already belongs to exactly one store. Found by thediff --git a/spree/providers/stripe/app/models/spree_stripe/gateway/payment_sessions.rb b/spree/providers/stripe/app/models/spree_stripe/gateway/payment_sessions.rbindex e8f03c3917..a5db98ea2e 100644--- a/spree/providers/stripe/app/models/spree_stripe/gateway/payment_sessions.rb+++ b/spree/providers/stripe/app/models/spree_stripe/gateway/payment_sessions.rb@@ -48,9 +48,9 @@ module SpreeStripe# paid, or an earlier one could not be canceleddef create_payment_session(order:, amount: nil, external_data: {})total = amount.presence || order.total_minus_store_credits- amount_in_cents = Spree::Money.new(total, currency: order.currency).cents+ stripe_amount = SpreeStripe::Units.to_stripe(total, order.currency)- raise Spree::Core::GatewayError, I18n.t('spree.stripe.payment_session_errors.zero_amount') if amount_in_cents.zero?+ raise Spree::Core::GatewayError, I18n.t('spree.stripe.payment_session_errors.zero_amount') if stripe_amount.zero?stripe_payment_method_id = external_data[:stripe_payment_method_id] || external_data['stripe_payment_method_id']@@ -59,7 +59,7 @@ module SpreeStripegateway_customer = fetch_or_create_customer(order: order)response = create_payment_intent(- amount_in_cents, order,+ stripe_amount, order,payment_method_id: stripe_payment_method_id,customer_profile_id: gateway_customer&.profile_id)@@ -85,18 +85,18 @@ module SpreeStripedef update_payment_session(payment_session:, amount: nil, external_data: {})attrs = {}- amount_in_cents = nil+ stripe_amount = nilif amount.present?attrs[:amount] = amount- amount_in_cents = Spree::Money.new(amount, currency: payment_session.currency).cents+ stripe_amount = SpreeStripe::Units.to_stripe(amount, payment_session.currency)endstripe_payment_method_id = external_data[:stripe_payment_method_id] || external_data['stripe_payment_method_id']update_payment_intent(payment_session.external_id,- amount_in_cents || payment_session.amount_in_cents,+ stripe_amount || SpreeStripe::Units.to_stripe(payment_session.amount, payment_session.currency),payment_session.owner,stripe_payment_method_id)@@ -165,8 +165,8 @@ module SpreeStripesend_request { |opts| Stripe::PaymentIntent.confirm(payment_intent_id, {}, opts) }end- def capture_payment_intent(payment_intent_id, amount_in_cents)- send_request { |opts| Stripe::PaymentIntent.capture(payment_intent_id, { amount_to_capture: amount_in_cents }, opts) }+ def capture_payment_intent(payment_intent_id, stripe_amount)+ send_request { |opts| Stripe::PaymentIntent.capture(payment_intent_id, { amount_to_capture: stripe_amount }, opts) }enddef cancel_payment_intent(payment_intent_id)@@ -273,9 +273,9 @@ module SpreeStripe# @param order [Spree::Cart, Spree::Order]# @return [Spree::PaymentResponse]- def create_payment_intent(amount_in_cents, order, payment_method_id: nil, customer_profile_id: nil)+ def create_payment_intent(stripe_amount, order, payment_method_id: nil, customer_profile_id: nil)payload = {- amount: amount_in_cents,+ amount: stripe_amount,currency: order.currency,customer: customer_profile_id,payment_method: payment_method_id,@@ -304,10 +304,10 @@ module SpreeStripeend# Only the fields that can legitimately change while a session is pending.- def update_payment_intent(payment_intent_id, amount_in_cents, order, payment_method_id = nil)+ def update_payment_intent(payment_intent_id, stripe_amount, order, payment_method_id = nil)protect_from_error dopayload = {- amount: amount_in_cents,+ amount: stripe_amount,currency: order.currency,customer: fetch_or_create_customer(order: order)&.profile_id,payment_method: payment_method_id,diff --git a/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb b/spree/providers/stripe/app/models/spree_stripe/payout_provider.rbindex dc00ba561b..4c3167556d 100644--- a/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb+++ b/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb@@ -258,7 +258,7 @@ module SpreeStripewanted = currency.to_s.downcaseminor = balance.available.select { |entry| entry.currency == wanted }.sum(&:amount)- Spree::Money::Rounding.from_minor_units(minor, currency)+ SpreeStripe::Units.from_stripe(minor, currency)rescue *AMBIGUOUS_ERRORS => e# The sweep must not read silence as "nothing to send" and settle a# smaller batch than the seller is owed, nor as "no limit" and ask for@@ -290,8 +290,7 @@ module SpreeStripereturn {} if balance_transaction.blank? || balance_transaction.try(:currency).blank?{- settled_amount: Spree::Money::Rounding.from_minor_units(balance_transaction.amount,- balance_transaction.currency),+ settled_amount: SpreeStripe::Units.from_stripe(balance_transaction.amount, balance_transaction.currency),settled_currency: balance_transaction.currency.upcase}end@@ -322,7 +321,7 @@ module SpreeStripeenddef minor_units(record)- Spree::Money::Rounding.to_minor_units(record.amount.abs, record.currency)+ SpreeStripe::Units.to_stripe(record.amount.abs, record.currency)end# Ties transfers paid from the platform balance to the checkout theydiff --git a/spree/providers/stripe/app/models/spree_stripe/units.rb b/spree/providers/stripe/app/models/spree_stripe/units.rbnew file mode 100644index 0000000000..820e4438e6--- /dev/null+++ b/spree/providers/stripe/app/models/spree_stripe/units.rb@@ -0,0 +1,35 @@+module SpreeStripe+ # Stripe's integer amounts. Mostly the currency's ISO minor unit, with+ # Stripe's own exceptions (https://docs.stripe.com/currencies): its+ # zero-decimal currencies are sent in whole units, and ISK and UGX, zero-decimal+ # since, are still sent as two-decimal values ending in 00.+ module Units+ module_function++ ZERO_DECIMAL = %w[BIF CLP DJF GNF JPY KMF KRW MGA PYG RWF VND VUV XAF XOF XPF].freeze+ WHOLE_IN_HUNDREDTHS = %w[ISK UGX].freeze++ # @param amount [BigDecimal, Spree::Money]+ # @param currency [String]+ # @return [Integer]+ def to_stripe(amount, currency)+ amount = amount.to_d if amount.respond_to?(:to_d)+ code = currency.to_s.upcase+ return Spree::Money::Rounding.quantize(amount, 0).to_i if ZERO_DECIMAL.include?(code)+ return Spree::Money::Rounding.quantize(amount, 0).to_i * 100 if WHOLE_IN_HUNDREDTHS.include?(code)++ Spree::Money::Rounding.to_minor_units(amount, code)+ end++ # @param units [Integer] as Stripe reports it+ # @param currency [String]+ # @return [BigDecimal]+ def from_stripe(units, currency)+ code = currency.to_s.upcase+ return BigDecimal(units) if ZERO_DECIMAL.include?(code)+ return BigDecimal(units) / 100 if WHOLE_IN_HUNDREDTHS.include?(code)++ Spree::Money::Rounding.from_minor_units(units, code)+ end+ end+enddiff --git a/spree/providers/stripe/spec/models/spree_stripe/gateway_spec.rb b/spree/providers/stripe/spec/models/spree_stripe/gateway_spec.rbindex 804e13601c..0ae208d6db 100644--- a/spree/providers/stripe/spec/models/spree_stripe/gateway_spec.rb+++ b/spree/providers/stripe/spec/models/spree_stripe/gateway_spec.rb@@ -466,7 +466,7 @@ RSpec.describe SpreeStripe::Gateway doenddescribe '#credit' do- subject { gateway.credit(amount_in_cents, nil, payment_intent_id, {}) }+ subject { gateway.credit(Spree::Money.new(BigDecimal(amount_in_cents) / 100, currency: 'USD'), nil, payment_intent_id, {}) }let(:amount_in_cents) { 800 }let(:payment_intent_id) { 'pi_3QXmL12ESifGlJez0v0B8tUn' }@@ -510,7 +510,7 @@ RSpec.describe SpreeStripe::Gateway doenddescribe '#capture' do- subject { gateway.capture(amount_in_cents, payment_intent_id) }+ subject { gateway.capture(Spree::Money.new(BigDecimal(amount_in_cents) / 100, currency: 'USD'), payment_intent_id) }let(:amount_in_cents) { 1000 }diff --git a/spree/providers/stripe/spec/models/spree_stripe/units_spec.rb b/spree/providers/stripe/spec/models/spree_stripe/units_spec.rbnew file mode 100644index 0000000000..b1d0dc5fe1--- /dev/null+++ b/spree/providers/stripe/spec/models/spree_stripe/units_spec.rb@@ -0,0 +1,21 @@+require 'spec_helper'++RSpec.describe SpreeStripe::Units do+ {+ ['19.99', 'USD'] => 1999,+ ['1000', 'JPY'] => 1000,+ ['1.505', 'KWD'] => 1505,+ ['5', 'ISK'] => 500,+ ['5', 'UGX'] => 500,+ ['1500.50', 'HUF'] => 150_050+ }.each do |(amount, currency), units|+ it "sends #{amount} #{currency} as #{units}" do+ expect(described_class.to_stripe(BigDecimal(amount), currency)).to eq(units)+ expect(described_class.from_stripe(units, currency)).to eq(BigDecimal(amount))+ end+ end++ it 'takes a Spree::Money' do+ expect(described_class.to_stripe(Spree::Money.new(BigDecimal('1000'), currency: 'JPY'), 'JPY')).to eq(1000)+ end+end