Skip to Content
Docs

Express checkout and beforePay

Place Apple Pay and Google Pay buttons on product and cart pages with shipping callbacks, and stop or approve every payment with a beforePay hook.

checkout.express() places Apple Pay and Google Pay buttons anywhere on your site, such as a product page or the cart, outside Universal checkout. The customer picks a shipping address and option in the wallet sheet, you return the shipping options and totals, and you create the order in beforePay. The SDK pays only when the session charges exactly the total the customer approved.

beforePay is a checkout option that runs right before money moves, for almost every payment method, not only express checkout.

A Google Pay express checkout button under a product price

Your page shows the product name and price. Google Pay renders the button.

Add express checkout

Pass beforePay to pay.checkout(), then call checkout.express() with the container, the line items, the total, and the shipping callbacks:

const checkout = pay.checkout({
  clientSecret,
  onSuccess: (payment) => showConfirmation(payment),
  onFailure: (error) => showError(error.message),
  beforePay: async ({ express, payer }) => {
    // Create the order and set the session amount to the approved total, on your server.
    const order = await createOrder({ payer })
    return order.ok ? true : { proceed: false, message: 'This item just sold out.' }
  },
})

const buttons = checkout.express({
  container: '#express-checkout',
  request: { shipping: true, email: true },
  lineItems: [{ label: 'Coffee beans', amount: '18.00' }],
  total: { amount: '18.00' },
  onShippingAddressChange: async (address) => {
    const rates = await getShippingRates(address)
    if (!rates.length) {
      return { error: { reason: 'address_unserviceable', message: "We don't ship there yet." } }
    }
    return {
      shippingOptions: rates,                       // The first option is preselected
      total: { amount: addAmounts('18.00', rates[0].amount) },
    }
  },
  onShippingOptionChange: async (option) => ({
    total: { amount: addAmounts('18.00', option.amount) },
  }),
})

const wallets = await buttons.ready   // ['applepay', 'googlepay'], or [] when neither can show

Express checkout amounts are decimal strings in major units, such as '18.00', because that's what the wallet sheets show. Pay.com API amounts are in minor units, so the same $18.00 is 1800.

For every option, the button style, and what checkout.express() returns, see checkout.express().

When buttons don't show

A wallet's button renders only when the session offers that wallet and the browser can pay with it. Apple Pay also needs the page on HTTPS, and a browser where ApplePaySession.supportsVersion(11) is true. Express checkout needs a payment session. With a setup session, ready resolves with no wallets.

ready rejects when container matches nothing or the session can't load. The SDK only logs a console warning, so catch the rejection, for example to hide the area the buttons would fill.

How a payment runs

An express payment goes through five steps, from the tap to the charge:

  1. 1

    The customer taps a button

    onClick runs synchronously, because wallets open their sheet only inside the tap. Return false to keep the sheet closed, or return an update for the sheet to open with. A promise returned from onClick is ignored.

  2. 2

    The sheet opens

    It shows total and lineItems, including any changes from update() calls and from what onClick returned. By default the total is the session amount and its label is your merchant name.

  3. 3

    The customer picks shipping

    onShippingAddressChange gets the address and returns the shipping options and the new total, or an error for the sheet to show. While the sheet is open, the address is partial. Apple Pay hides the street and the name until the customer approves. onShippingOptionChange returns the total for the option the customer picked.

  4. 4

    The customer approves

    beforePay runs with express: true and the payer the sheet collected. Create the order here, and update the session amount on your server with Update a payment session to the approved total, in minor units.

  5. 5

    The SDK checks the amount and pays

    The SDK reads the session again. If its currency or amount differs from the total the customer approved, it refuses to pay and the sheet shows "The amount to pay changed. Please review your order and try again". This refusal calls onFailure and emits payment_failure, with data.code set to 'amount_changed'. Otherwise it pays, and calls onSuccess (or onPending) and emits payment_success (or payment_pending), as for any other method. A failure calls onFailure.

    The payment stays with the session the sheet opened for. If your page moves the checkout to another session before the charge, for example by calling pay.checkout() again, nothing is paid.

If you don't set beforePay, update the session amount in onShippingAddressChange and onShippingOptionChange instead, so it matches the total the customer sees.

Apple Pay times out the sheet about 30 seconds after the customer approves. To stay inside that window, beforePay gets 15 seconds for Apple Pay (wherever the button is) and for Google Pay in express checkout. An Apple Pay payment must also start within 20 seconds of approval. Google Pay elsewhere has no limit, because its sheet has closed by the time beforePay runs. Past either limit, nothing is charged and the sheet tells the customer to try again, so make beforePay safe to run twice for the same order. A beforePay that runs out of time stops the payment as if it returned { proceed: false }, so onFailure isn't called. A missed Apple Pay start calls onFailure and emits payment_failure, with data.code set to 'timed_out'.

Use beforePay

beforePay is a pay.checkout() option. It runs once per payment attempt, right before money moves, for every method: card forms, saved sources, Click to Pay, wallets, alternative payment method buttons, checkout.headless() calls, and express checkout. On PayPal's own button, from checkout.paypal(), it runs before PayPal creates the order. Use it to create the order, or to stop the payment.

const checkout = pay.checkout({
  clientSecret,
  beforePay: async (data) => {
    const ok = await reserveStock(data.paymentMethodType)
    return ok ? true : { proceed: false, message: 'Some items are no longer available.' }
  },
})

Return true to let the payment go ahead, or { proceed: false, message } to stop it before any money moves. Express checkout sheets show message to the customer. A payment that beforePay stopped isn't a declined payment, so onFailure isn't called. An approval counts only for the session the checkout was on when beforePay ran. If pay.checkout() moves to another session in the meantime, nothing is paid. See beforePay.

With beforePay set, checkout.pay() and checkout.headless() for cards, alternative payment methods, and Click to Pay emit payment_processing only after beforePay lets the payment go ahead. Without it, they emit payment_processing when the payment starts. Express checkout emits it only after beforePay lets the payment go ahead.

For the data beforePay receives, every value it can return, and how a stop reaches checkout.headless() and checkout.pay(), see beforePay.

Was this page helpful?