Payment Processing¶
BadgerCommerce provides a comprehensive payment processing system built on the PaymentV2 architecture — a pluggable, multi-method payment framework that supports split payments, two-phase authorisation, and extensible payment method processors.
Key Features¶
Payment Methods¶
- Credit/Debit Cards: Process payments via Stripe (Payment Intents API)
- Digital Wallets: Support for Apple Pay, Google Pay via Stripe
- Gift Cards: Checkout redemption: the balance is checked (with the card's number and PIN) at authorisation and deducted at capture (see Gift Cards)
- Split Payments: Use multiple payment methods on a single order (e.g. gift card + Stripe)
- Ways of paying a product refuses: a product can refuse credit cards, card brands or methods such as Klarna; the card is checked before any money is held, on PaymentV2 and the single-page checkout (see Ways of Paying a Product Refuses)
Payment Processing¶
- Two-Phase Flow: Authorise → Capture pattern for all payment methods
- Secure Processing: PCI-compliant via Stripe's tokenisation
- Real-time Authorization: Instant payment verification
- Webhook Processing: Strategy-pattern event handlers for Stripe webhook events
- Automatic Retries: Intelligent handling of failed payment attempts
Integration with Stripe¶
- Stripe Connect: Multi-merchant capability for marketplace scenarios. Connecting a shop creates its Standard account with the shop's name (its siteId in capitals if it has none) and website as the business name and URL, so Stripe lists the account by shop rather than by the person who onboarded it. On a platform running on Stripe test keys (bdgr-demo, local dev) the name ends in
DEMO, e.g.DMRT DEMO - Webhooks: 15+ dedicated event handlers auto-discovered via Spring component scanning
- Payment Intents: Modern payment flow with SCA/3DS authentication support
- Saved Payment Methods: Securely store card details for future use
Order Management¶
- Capture & Settlement: Flexible timing for payment capture via pipeline processors
- Refunds: Full and partial refunds, across every payment method on the order (card first, then gift card)
- Cancellations: Refund what was captured, or release the card hold and drop gift card authorisations
- Payment History: Complete audit trail via PaymentIntent and transaction records
Currencies¶
- One currency per shop: set per site by the
siteCurrencyCodeconfig key. It decides both the currency a shopper is charged in and how every price on the site, in emails and in the admin is written (see Money and currency) - Any ISO currency: amounts are written in the shopper's locale with the currency's own minor unit, so JPY shows no decimals and a German shop writes
1.234,56 € - Orders keep their currency: a submitted order stays in the currency it was charged in if the shop's setting changes later
- Settlement Options: Flexible settlement currency configuration via Stripe Connect
PaymentV2 Architecture¶
Overview¶
PaymentV2 is a pluggable payment framework that decouples payment method logic from the checkout flow. Each payment method (Stripe, gift cards, etc.) has its own PaymentMethodProcessor that handles the full lifecycle.
Core Components¶
PaymentServiceRouter (commerce-core/.../payment/PaymentServiceRouter.java)
- The @Primary PaymentService every caller gets
- Authorisation goes where the site points: PaymentV2 when payment-v2-enabled is on, otherwise the legacy StripePaymentServiceImpl (or a test payment service in test mode)
- Capture, refund and the order-number update follow the order: an order with V2 intents goes to PaymentV2, one without goes to legacy. Turning the flag on or off therefore never strands an order that was authorised before the switch and is waiting to be captured on dispatch
- Unified checkout calls PaymentV2Adapter directly, so its orders always carry V2 intents whatever the flag says
PaymentV2Adapter (commerce-core/.../payment/PaymentV2Adapter.java)
- Implements the legacy PaymentService interface, bridging old and new payment systems
- Routes payment operations to the appropriate PaymentMethodProcessor based on payment method type
- Orchestrates split payment flows (e.g. gift card partial + Stripe remainder)
- Manages PaymentIntent lifecycle on orders
- Records the Stripe intent id on paymentDetails.paymentRequest.paymentIntentId, which is how refunds, voids, the 3DS return and the Stripe webhooks find the order
PaymentMethodProcessor (common/.../payment/paymentV2/service/PaymentMethodProcessor.java)
- Abstract base class for all payment method implementations
- Generic type parameter <T extends PaymentMethod> for type-safe payment method handling
- Required methods:
| Method | Purpose |
|---|---|
createPaymentMethod() |
Initialise the payment method for an order |
authorise() |
Authorise payment (a card holds the funds; a gift card's balance is only checked) |
capture() |
Capture previously authorised payment |
refund() |
Refund a captured payment |
PaymentIntent (common/.../payment/paymentV2/beans/PaymentIntent.java)
- Stored on the Order to track payment state
- Contains the list of PaymentMethod instances used
- Tracks authorisation, capture, and refund status
Payment Method Processors¶
| Processor | Payment Method | Module |
|---|---|---|
StripePaymentMethodProcessor |
StripePaymentMethod |
common |
GiftCardPaymentMethodProcessor |
GiftCardPaymentMethod |
common |
TestPaymentMethodProcessor |
TestPaymentMethod |
common |
Split Payment Flow¶
When a customer uses a gift card + Stripe:
- Gift card applied:
GiftCardPaymentMethodProcessor.authorise()checks the card's number and PIN and that it has a balance. Nothing is reserved - Stripe payment created: Stripe Payment Intent created for the remaining amount
- Customer completes 3DS (if asked): the browser gets the intent's client secret, runs the challenge, and posts back; the adapter confirms the same Stripe intent
- Payment captured (on submit, or on dispatch if the site captures then): the gift card is captured first (an atomic balance deduction) and then the card. Capture stops at the first failure, so a gift card spent elsewhere in the meantime doesn't leave the card charged; anything not captured stays authorised and can be retried
- On failure: the gift card authorisation is abandoned (it never held anything) and the order can be paid again
A repeat confirm on an order that is already authorised (double click, browser retry) reports success without paying again. Changing the basket or the gift card between attempts drops the old authorisations so they are never captured.
Subscriptions and card details¶
A subscription bills the card again later, so its Stripe intent is created against a Stripe customer with setup_future_usage=off_session, and once authorised the card becomes the customer's default for invoices. This is the same in the legacy flow, PaymentV2 and unified checkout. Unified checkout creates its intent when the session starts, so a subscription added to the basket afterwards gets its customer then, and the customer's name and email are filled in at confirmation.
While the unified checkout places an order (from Pay until the payment succeeds or comes to nothing), the form can't be changed: every section, the wallet button and the promo code box are inert, and the card details are read-only through the Payment Element's own readOnly option (readiness.js lockForm). On the old step checkout only the payment step was on screen, so this never came up.
Once a card payment is authorised, its brand, last 4, expiry, checks, 3DS result and live mode are recorded on paymentDetails (StripePaymentServiceImpl.recordAuthorisedIntent), which is what the admin order page shows.
Refunds and cancellation¶
PaymentService.refundOrder(order, amount) refunds through whatever took the payment. For a V2 order it refunds the card intent first and then the gift card, each up to what is still refundable, and never more than was captured. If one part fails, what was refunded is still recorded on the order so it isn't offered again. The charge.refunded webhook updates the card's intent and totals the order across all of its intents.
Cancelling a captured order refunds it the same way. Cancelling an authorised order voids the Stripe hold and marks any gift card or test intents abandoned.
Declines and alerts¶
A declined card tells the shopper why, in their language, in both flows. The message key is stripe.<code>[.<decline code>] from messages.properties (for example stripe.card_declined.insufficient_funds). PaymentV2's StripePaymentMethodProcessor keeps it as the authorisation's error code, PaymentServiceImpl stores it on the failed intent (PaymentIntent.failureCode), and PaymentV2Adapter words the failure with the decline's key, then its general key (stripe.card_declined), then the generic payment.msg.authorisationFailed. A decline is logged at WARN (a card-testing run shouldn't page anyone); other Stripe errors at ERROR.
Both flows send the same admin alerts (StripeAdminAlerts) for a decline, rejected Stripe credentials and any other Stripe error while authorising. They name the order, site and Stripe charge, never the customer.
A V2 intent carries Internal ID and Site ID metadata, plus Order Number when the order already has one; otherwise SetOrderNumber adds it once the order is placed.
Moving a site to PaymentV2¶
Set payment-v2-enabled to true; there's no data to migrate. PaymentServiceRouter routes capture, refunds and the order-number update by the order's own intents, so orders authorised on the legacy path before the switch still settle and refund through it, and orders authorised under V2 keep settling through V2 if the flag is turned off again. Switch at a quiet time: a shopper in the middle of a 3D Secure challenge when the flag changes has to start their payment again.
Checkout UI Integration¶
PaymentExtension (web-mvc/.../extensions/checkout/PaymentExtension.java)
- Renders the payment form on the checkout page
- Handles gift card application AJAX requests (validate card, show balance, apply to order)
- Calculates remaining amount after gift card application
- Integrates with Stripe Elements for card input
Stripe Webhook Handlers¶
Stripe events are processed via a strategy pattern:
StripeEventProcessor (worker/.../payment/stripe/StripeEventProcessor.java)
- Auto-discovers all StripeEventHandler implementations via List<StripeEventHandler> injection
- Maps handlers by event type at startup
- After the handler runs (or straight away, for event types without one), posts the event to Slack
Handler implementations:
- ChargeSucceededHandler, ChargeRefundedHandler, ChargeDisputeCreatedHandler
- PaymentIntentSucceededHandler, PaymentIntentPaymentFailedHandler
- CustomerSubscriptionCreatedHandler, CustomerSubscriptionDeletedHandler
- InvoicePaymentSucceededHandler, InvoicePaymentFailedHandler
- AccountUpdatedHandler, ApplicationFeeCreatedHandler
- PayoutCreatedHandler (the payout email, and keeps the payout)
- PayoutStatusHandler (payout.updated, payout.paid, payout.failed, payout.canceled: the
kept payout's status, see Payouts page)
- DiningRefundUpdatedHandler (charge.refund.updated, refund.updated, refund.failed: settles a
table bill refund Stripe was still sending; other refunds are left alone)
Webhook subscriptions¶
Stripe only sends an endpoint the events it is subscribed to, and that is set on Stripe, not in
code. A handler for an event the endpoint isn't subscribed to never runs. The platform has two
endpoints: /stripeAccountHook (the platform's own account) and /stripeConnectHook (connected
accounts).
StripeWebhookEvents (in common) lists every event the worker handles and which endpoint it must
arrive on. Add the event there when you add a handler: StripeWebhookEventsTest in the worker
fails until the list and the handlers agree.
System, Stripe webhooks (/system/stripe-webhooks, SUPERADMIN) reads the endpoints from Stripe
with the platform's live and test keys and shows, for each one:
- whether it is enabled, and the events it is missing;
- the events it gets that no handler uses (they only go to Slack);
- whether it belongs to this environment, by comparing its host with
badger.stripe.callback-domain.
Add missing events adds the missing ones after a typed confirmation (ADD EVENTS). It keeps
every event the endpoint already has, and never removes events, creates endpoints or changes signing
secrets. It only works on this environment's endpoints. A restricted key needs read access to
Webhook Endpoints to check, and write access to add events. The page also reports a missing or
disabled endpoint for this environment.
The worker's StripeWebhookSubscriptionJob runs the same check five minutes after start-up and
every 12 hours after that. It logs a warning for each endpoint that is missing events
(badger.stripe.webhook-check.enabled=false turns it off).
Payout emails¶
When Stripe schedules a payout to a shop's bank (payout.created on its connected account), the
shop can get Badger's Payout on its way email. It goes to the site's
payout-notification-email (Settings, payments); leave it empty and nothing is sent. It's a
Badger email: Badger's layout, named
Badger Commerce, sent from Badger's own address when platform-email-from-address is set, else the
shop's own address and Mailtrap account.
It shows:
- the amount, the day Stripe expects it in the bank and the last four digits of the account, in the subject line and at the top
- In this payout: how many orders, subscription payments and other payments (a payment link, another system on the same Stripe account) it pays out, leaving out any that are zero
- a button to the payout's page in the admin, Finance › Payouts (
/admin/reports/payouts/{id})
The email deliberately leaves out the money breakdown (sales, refunds, Stripe's fees): that's on the payout's page, so the email is the good news and the button leads to the detail. The one figure it does give is Badger's fees in the payout, VAT included, with a note that the month's fee invoice follows by email (an itemised payout with fees only). There's no link to the Stripe dashboard either: the email keeps shops in Badger.
How it works: PayoutCreatedHandler (worker) calls PayoutNotificationService, which reads the
payout and keeps it (PayoutService.recordPayout, see Payouts page), then emails
each site on the account (SiteManagementService.findByStripeAccount) that wants the email and is
in the same mode as the payout (a test payout never emails a live shop). StripePayoutReader
reads the payout. Stripe lists the balance transactions of an automatic payout,
with each payment's fees split into Stripe's and the application fee; a manual payout has no list,
so its email has the amount and date only. Transactions are sorted by Stripe's reporting category:
charge, refund, fee (Stripe's own charges to the account, in practice Billing's fee on
subscription payments), dispute/dispute_reversal (with their dispute fees); anything else is an
adjustment. A payment whose charge paid a Stripe invoice is a subscription payment. The other
payments are matched to orders by PaymentIntent
(OrderService.findByPaymentIntentIds, on the payment_intent_idx index). A restaurant tab paid in
shares points at one of its intents only, so its other shares show as other payments. The split
into orders, subscriptions and other payments is PayoutBreakdown, which the email and the
Payouts page share, so they always agree.
To see it before a payout is due, a superadmin can use Payout email on System › Tenants ›
{site}: it sends the email for the shop's most recent payout (an automatic one when there is
one) to any address, with the shop's real figures, from the usual sender. It isn't recorded
as sent, so the shop still gets its own email, and it doesn't need payout-notification-email.
Each payout is emailed to a site once: a payoutNotifications record (unique on site and payout)
is saved before sending, so a webhook Stripe sends again is ignored. If the email fails the record
is removed and the handler fails, so Stripe's retry sends it.
Payouts page¶
Finance › Payouts (/admin/reports/payouts, PayoutReportController, Finance, Admin and
Superadmin) lists a shop's payouts newest first, 25 a page, and opens each one at
/admin/reports/payouts/{payoutId} with its breakdown and the orders in it.
Payouts are kept in Badger rather than read from Stripe on each visit: a payout's breakdown never
changes once Stripe creates it, only its status moves on, and reading a busy payout means several
Stripe calls. PayoutService keeps a StoredPayout (collection payouts, unique on site and
payout) per site, so sites sharing a Stripe account each match the payments to their own orders.
It holds the payout's status, dates, account, the breakdown's totals and each payment (its
PaymentIntent, amount and whether it paid a subscription invoice). Orders are matched when the page
is shown. A payout is kept:
- when Stripe creates it (
payout.created, through the payout email's read, whether or not the shop wants the email) - when its status changes (
PayoutStatusHandler), reading the whole payout for a site that doesn't have it yet - by
PayoutSyncJob(worker, hourly at :17, one worker at a time on a Redis lock): for each active shop with Stripe it lists the account's payouts and updates any whose status or dates changed, and reads in full the ones not kept yet, at mostbadger.payouts.sync-max-reads(40) per shop per run. That backfills the payouts from before they were kept, over a few runs for a shop with years of them, and catches anything a webhook missed.badger.payouts.sync-enabledandbadger.payouts.sync-scheduleturn it off and change when it runs - when someone opens a payout that isn't kept yet, read from the shop's own Stripe account (so another shop's payout id isn't found)
The page shows the payouts of the mode the shop is in (a test-mode shop sees test payouts). Kept payouts aren't part of a site export, like orders.
Stripe activity in Slack¶
Every Stripe event is posted to #badger-stripe (live mode) or #badger-stripe-test (test
mode) as part of a thread. There is one thread per thing a person follows:
| Thread | Collects |
|---|---|
| Payment | The PaymentIntent and its charge, refunds and disputes |
| Invoice | The invoice plus its PaymentIntent and charge, so a subscription renewal is one thread |
| Payout, transfer | That payout or transfer's events |
| Balance | One message per account per day |
| Account | Onboarding completed, disconnection |
The thread's first message is its status: state, amount and account, then the order or
invoice, anything needing attention, the site, a link to the object in Stripe, and how many
updates have arrived. It's edited in place as events arrive. Each event is a reply underneath,
so replies don't notify the channel. Stripe sends webhooks out of order, so a late
payment_intent.created can't move a thread from "Paid" back to "Awaiting payment", but a refund
or dispute can follow "Paid".
Handlers don't post to Slack themselves. They add notes to the event context
(context.addSlackNote(...)): the Badger order a payment matched (StripeSlackNote.order),
context (info), or something someone must act on (attention, which stays on the status
message). account.updated only reaches Slack when its handler adds a note.
Thread state is kept in the stripeSlackThreads collection (rows expire after 45 days of quiet).
The code is in worker/.../payment/stripe/slack/: StripeSlackEventInterpreter decides the thread
and status from the event's JSON, StripeSlackMessages renders both message kinds, and
StripeSlackThreadService posts them, using the Badger Slack token
(global setting slackServiceToken). Application fees still go to #badger-fees from
ApplicationFeeCreatedHandler.
Technical Implementation¶
Key Classes¶
| Class | Location | Purpose |
|---|---|---|
PaymentV2Adapter |
commerce-core | Bridges legacy PaymentService → PaymentV2 |
PaymentMethodProcessor |
common | Abstract base for payment method processors |
StripePaymentMethodProcessor |
common | Stripe payment processing |
GiftCardPaymentMethodProcessor |
common | Gift card checkout redemption |
PaymentIntent |
common | Payment state tracking on orders |
PaymentMethod |
common | Abstract payment method base |
StripePaymentMethod |
common | Stripe-specific payment data |
GiftCardPaymentMethod |
common | Gift card payment data |
PaymentExtension |
web-mvc | Checkout UI extension |
SettlePaymentProcessor |
commerce-core | Pipeline processor for payment capture |
StripeEventProcessor |
worker | Webhook event dispatcher |
StripeEventHandler |
worker | Webhook handler interface |
Pipeline Processors¶
Payment-related processors in the order pipeline:
| Processor | Pipeline | Purpose |
|---|---|---|
SettlePaymentProcessor |
submitOrder | Captures payment after order validation |
ConditionalCaptureProcessor |
submitOrder, packOrder, dispatchOrder | Captures if this is the site's capture pipeline |
PaymentStateValidationProcessor |
various | Validates payment state before processing |
RefundOrderChargeProcessor |
refundOrder | Processes refunds via payment service |
SetPaymentToRefundPendingProcessor |
refundOrder | Marks payment for refund |
Where payment is captured¶
paymentCapturePipelineName names the pipeline a site takes payment in — submitOrder (the default), packOrder, or dispatchOrder. An order partly collected and partly delivered, and a sale placed at the till (POS_ORDER), are always captured in submitOrder (OrderCaptureService.isCapturedWhenPlaced), so a part cancelled later is a partial refund and a till sale is never left only authorised; see Fulfilment.
The setting is not only read by the pipeline step. Fulfilment recorded per line — in the fulfiller portal, or by auto-fulfilment at checkout — runs no pipeline, so the line roll-up captures instead, when the order reaches or passes the state the capture pipeline stands for (PACKING for packOrder, DISPATCHED for dispatchOrder). An order can skip PACKING entirely, and a site capturing at pack must still be paid. Both paths go through OrderCaptureService, so there is one definition of when a site takes payment.
Each capture happens once:
- Inside a pipeline, only
ConditionalCaptureProcessorcaptures. The steps that move the lines (setOrderToPackingProcessor,setOrderToDispatchedProcessor) don't capture through the roll-up as well; a second attempt would fail and mark a paid orderPAYMENT_FAILED. - A payment that is already captured, refunded or released (
CAPTURED,PARTIAL_REFUND,PENDING_REFUND,REFUNDED,VOIDED, or any captured amount) is never captured again.
See Fulfilment for what happens when a capture fails after the goods have been packed.
Integration Points¶
The payment system integrates with: - Order System: PaymentIntent stored on Order, captured via pipeline - Gift Card System: Two-phase balance reservation for checkout (see Gift Cards) - Subscription System: Stripe subscription billing (see Subscriptions) - Customer Accounts: Saved payment methods via Stripe Customer objects - Webhook System: Async event processing for payment status updates - Admin UI: Transaction monitoring, refund operations
Administration¶
Payment functionality can be managed through: - Payment method configuration per site - Transaction monitoring via order detail views - Refund and void operations from admin order management - Stripe webhook event logs - Stripe webhook subscriptions (System, Stripe webhooks) - Gift card balance and transaction management
Configuration¶
| Config Key | Default | Category | Purpose |
|---|---|---|---|
siteCurrencyCode |
gbp |
payment-config | The currency the shop charges in and shows prices in |
giftCardService |
savvyGiftCardService |
payment-config | Active gift card provider |
payment-v2-enabled |
false |
payment-config | Route this site's payments through PaymentV2 instead of the legacy Stripe service |
test-payment-enabled |
false |
payment-config | Show a "Simulate Payment" button instead of Stripe when the site has no Stripe account. PaymentV2 only accepts the simulated test_pm_ payment ids while this is on; with it off they are rejected |
stripe-js-on-every-page |
false |
payment-config | Load Stripe.js on every storefront page (more Radar fraud signal) instead of only on pages that take a payment (~1 MB less JavaScript elsewhere) |
Test payment mode¶
Demo and test sites set test-payment-enabled so shoppers can check out without Stripe. The checkout posts a test_pm_success payment method id, which PaymentV2's TestPaymentMethodProcessor authorises and captures without charging anyone.
PaymentServiceRouter sends a test-mode site to the legacy TestPaymentServiceImpl when that bean exists (it only exists when badger.test-payment.enabled=true is set, and no deployed environment sets it) and to PaymentV2 otherwise, so test mode works on the deployed environments without that property. Because the test_pm_ id comes from the browser, PaymentV2Adapter rejects it on any site where test-payment-enabled is off; otherwise a shopper on a live site could post one and get an order without paying.
Adding a New Payment Method¶
To add a new payment method to PaymentV2:
- Create a
PaymentMethodsubclass (e.g.MyPaymentMethod) incommon/.../payment/ - Create a
PaymentMethodProcessor<MyPaymentMethod>implementation - Register it as a Spring
@Service - Wire it into
PaymentV2Adapteralongside existing processors - Add checkout UI support in
PaymentExtensionand payment templates - Create webhook handlers if the provider sends async events (for Stripe, add each event to
StripeWebhookEvents)