Skip to content

plugin-ecommerce: Stripe adapter hardcodes PaymentIntent amount to cart.subtotal #15784

Open

Description

@jhb-dev

Summary

The Stripe payment adapter in @payloadcms/plugin-ecommerce hardcodes the PaymentIntent amount to cart.subtotal:

// packages/plugin-ecommerce/src/payments/stripe/initiatePayment.ts
const amount = cart.subtotal
const paymentIntent = await stripe.paymentIntents.create({ amount, ... })

There is no way to customize this amount, which makes it impossible to include additional costs like shipping fees or apply discounts like gift cards without replacing the entire adapter.

Problem

In a typical e-commerce checkout, the total charged to the customer is:

charge = cart.subtotal + shippingCost - discounts

Since the adapter only uses cart.subtotal, consumers who need to charge shipping or apply gift card discounts are forced to copy the entire Stripe adapter into their project and maintain a custom fork — just to change the amount calculation.

The initiatePayment endpoint already passes through extra fields from the request body to the adapter via data (which accepts [key: string]: any), but the adapter ignores them.

Proposed solution

Add a resolveAmount hook to the adapter config

This lets consumers define how the amount is calculated:

stripeAdapter({
  secretKey: '...',
  resolveAmount: ({ cart, data }) => {
    return (cart.subtotal ?? 0) + (data.shippingCost ?? 0) - (data.giftCardDiscount ?? 0)
  },
})

Use cases

  • Shipping costs: Charge subtotal + shippingCost (shipping is not a cart item)
  • Gift cards / vouchers: Reduce the Stripe charge when a gift card covers part of the order
  • Handling fees, taxes, surcharges: Any cost that isn't a product line item

Current workaround

The only option today is to copy the entire Stripe adapter source into the project and maintain a custom version, which is brittle across plugin updates.

Activity

  1. jentzheng commented on Mar 30, 2026

    @jentzheng

    My temporary solution is to override the entire Stripe adapter using the Checkout API. I would suggest replacing this part of the code (https://github.com/payloadcms/payload/blob/main/packages/plugin-ecommerce/src/endpoints/confirmOrder.ts#L182-L211
    ) with a fulfillment module.

    import { stripeAdapter } from '@payloadcms/plugin-ecommerce/payments/stripe'
    import Stripe from 'stripe'
    
    import type { Cart, Order, OrderStatus, Product, Transaction, Variant } from '@/payload-types'
    
    const myStripeAdapter = stripeAdapter({
      secretKey: process.env.STRIPE_SECRET_KEY!,
      publishableKey: process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!,
      webhookSecret: process.env.STRIPE_WEBHOOKS_SIGNING_SECRET!,
    })
    
    const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!)
    
    myStripeAdapter.initiatePayment = async ({ data, customersSlug, req, transactionsSlug }) => {
      const payload = req.payload
      const user = req.user
      const {
        cart,
        billingAddress,
        currency,
        customerEmail,
        shippingAddress,
        // TODO: shippingCost, shipping cost can be added here if needed
      } = data
    
      const email = user?.email || customerEmail
      const baseUrl = req.headers.get('origin')
      const amount = cart.subtotal
    
      const payloadItems = cart.items.map((item) => {
        return {
          product: item.product,
          variant: item.variant,
          quantity: item.quantity,
        }
      })
    
      const transaction = await payload.create({
        collection: transactionsSlug as 'transactions',
        data: {
          ...(user ? { customer: user.id, customerEmail: email } : { customerEmail: email }),
          paymentMethod: 'stripe',
          cart: cart.id,
          items: payloadItems,
          amount,
          currency: currency as 'HKD',
          status: 'pending',
          billingAddress: billingAddress,
        },
        req,
      })
    
      const order = await payload.create({
        collection: 'orders',
        data: {
          ...(user ? { customer: user.id, customerEmail: email } : { customerEmail: email }),
          status: 'processing',
          items: payloadItems,
          shippingAddress: shippingAddress,
          amount,
          currency: currency as 'HKD',
          transactions: [transaction.id],
        },
        req,
      })
    
      await payload.update({
        collection: transactionsSlug as 'transactions',
        id: transaction.id,
        data: {
          order: order.id,
        },
        req,
      })
    
      const stripeItems: Stripe.Checkout.SessionCreateParams.LineItem[] = cart.items.map((item) => {
        const product = item.product as Product
        const variant = item.variant as Variant | undefined
    
        const title = variant ? (variant.title as string) : (product.title as string)
        const price = variant ? (variant.priceInHKD as number) : (product.priceInHKD as number)
    
        return {
          price_data: {
            currency: data.currency.toLowerCase(),
            unit_amount: price,
            product_data: {
              name: title,
            },
          },
          quantity: item.quantity,
        }
      })
    
      const session = await stripe.checkout.sessions.create({
        mode: 'payment',
        customer_email: email,
        line_items: stripeItems,
        // TODO: shipping can be added here if needed in the future
        // shipping_options: {},
        metadata: {
          transactionId: transaction.id,
          orderId: order.id,
          cartId: cart.id,
        },
        success_url: `${baseUrl}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,
        cancel_url: `${baseUrl}/checkout/cancel?session_id={CHECKOUT_SESSION_ID}`,
      })
    
      return {
        message: 'Payment initiated successfully',
        sessionId: session.id,
        redirectUrl: session.url,
      }
    }
    
    myStripeAdapter.confirmOrder = async ({ data, req, transactionsSlug, ordersSlug, cartsSlug }) => {
      const payload = req.payload
      const { customerEmail, sessionId } = data
    
      const session = await stripe.checkout.sessions.retrieve(sessionId, {
        expand: ['payment_intent'],
      })
    
      const payment_intent = session.payment_intent as Stripe.PaymentIntent | undefined
    
      if (!payment_intent) {
        throw new Error('No payment intent found for session')
      }
    
      if (!session.metadata?.transactionId || !session.metadata?.cartId || !session.metadata?.orderId) {
        throw new Error('No transaction ID, order ID or Cart ID found in session metadata')
      }
    
      const mapTransactionStatus = new Map<Stripe.PaymentIntent.Status, Transaction['status']>([
        ['succeeded', 'succeeded'],
        ['canceled', 'cancelled'],
        ['requires_payment_method', 'pending'],
        ['processing', 'pending'],
        ['requires_action', 'pending'],
        ['requires_capture', 'pending'],
        ['requires_confirmation', 'pending'],
      ])
    
      const transaction = await payload.update({
        collection: transactionsSlug as 'transactions',
        id: session.metadata.transactionId,
        data: {
          ...(req.user ? { customer: req.user.id, customerEmail } : { customerEmail }),
          amount: payment_intent.amount,
          paymentMethod: 'stripe',
          status: mapTransactionStatus.get(payment_intent.status),
          stripe: {
            paymentIntentID: payment_intent.id,
          },
        },
        req,
      })
    
      const mapOrderStatus = new Map<Stripe.PaymentIntent.Status, OrderStatus>([
        ['succeeded', 'processing'],
        ['canceled', 'cancelled'],
        ['requires_payment_method', 'processing'],
        ['processing', 'processing'],
        ['requires_action', 'processing'],
        ['requires_capture', 'processing'],
        ['requires_confirmation', 'processing'],
      ])
    
      const order = await payload.update({
        collection: ordersSlug as 'orders',
        id: session.metadata.orderId,
        data: {
          status: mapOrderStatus.get(payment_intent.status),
          amount: payment_intent.amount,
          currency: payment_intent.currency.toUpperCase() as 'HKD',
        },
        req,
      })
    
      // TODO: Trigger paylaod workflow for fullfillment after order is confirmed
    
      return {
        message: 'Order confirmed successfully',
        transactionID: transaction.id,
        orderID: order.id,
        ...(order.accessToken ? { accessToken: order.accessToken } : {}),
      }
    }
    
    export default myStripeAdapter
  2. Poseidonas commented on Aug 20, 2026

    @Poseidonas

    Confirmed at v3.88.0: stripe/initiatePayment.ts line 21 sets const amount = cart.subtotal and passes it to paymentIntents.create with no seam to adjust it, so shipping, tax and order-level discounts cannot reach the charged total.

    If a hook along these lines would be acceptable — for example an optional modifyAmount({ amount, cart, req }) on the adapter config, defaulting to the current behaviour — I would be glad to open a PR with tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions