Skip to content

Payments

Shoppable is the merchant of record, so payments run on Shoppable’s Stripe account. You render Stripe Elements on your page; card details go straight from the shopper’s browser to Stripe and never touch your servers or Shoppable’s. This guide assumes you already have a priced checkout from Cart and pricing.

placeOrder does the payment in one call:

  1. Authorize. Shoppable creates a Stripe PaymentIntent for the checkout’s server-priced amount, with manual capture.
  2. Confirm. Your confirmPayment callback confirms it with Stripe.js, including any 3-D Secure challenge.
  3. Complete. Shoppable re-checks prices and places the order, then returns its number.

What the order needs

Shoppable reads the shopper’s details from the confirmed payment. The order is refused (and the card not charged) unless the payment carries:

  • A shipping address with the recipient’s first and last name, street, city, state, postal code and country. Pass it as confirmParams.shipping; see why.
  • Billing details: name and address.
  • A phone number, on the shipping address or the billing details.
  • An email address, saved on the checkout with updateCheckout or included in the billing details.

The code below collects all of it with one Address Element and an email field.

Install

Terminal window
npm install https://developer.shoppable.com/sdk/shoppable-checkout-0.2.1.tgz @stripe/stripe-js@^7

Set up Stripe Elements

Load Stripe with the key from your cart configuration. It matches your token’s mode: a test token gets Stripe’s test key, so test cards work and nothing is charged.

Elements runs in deferred-intent mode: you create it with the amount and currency, and the PaymentIntent is created later, when the shopper pays. captureMethod: "manual" is required because Shoppable authorizes first and captures when the order is placed. Use the checkout’s total for the amount, in the currency’s smallest unit, and update it whenever the checkout is re-priced. Stripe shows its fields in the shopper’s browser language; to limit addresses to your store’s market, add allowedCountries: [config.country] to the Address Element options.

import { loadStripe } from "@stripe/stripe-js";
if (!config.stripePublishableKey) throw new Error("This cart has no payment key yet.");
const stripe = await loadStripe(config.stripePublishableKey);
if (!stripe) throw new Error("Stripe.js failed to load.");
const elements = stripe.elements({
mode: "payment",
amount: Math.round(priced.total * 100),
currency: config.currency,
captureMethod: "manual",
});
// Shipping address, with the phone number the order needs.
const addressElement = elements.create("address", {
mode: "shipping",
fields: { phone: "always" },
validation: { phone: { required: "always" } },
});
addressElement.mount("#shipping-address");
// Card and wallets. Billing details come from the shipping address (below).
const paymentElement = elements.create("payment", {
fields: {
billingDetails: { name: "never", email: "never", phone: "never", address: "never" },
},
});
paymentElement.mount("#payment");
// After every re-price:
elements.update({ amount: Math.round(priced.total * 100) });

If the shopper’s billing address can differ from shipping, add a second Address Element with mode: "billing" and pass its value as billing_details instead.

Validate the address

Before taking payment, check the shipping address with validateAddress. It normalizes the address and catches ones that would fail at fulfillment. It never throws for a bad address: it resolves with valid: false and a message you can show the shopper.

fromStripeAddress converts the Address Element’s value to the shape validateAddress takes. Pass config.country so the address is checked against your store’s market.

import { fromStripeAddress } from "@shoppable/checkout";
const { value: shipping } = await addressElement.getValue();
const result = await client.validateAddress(fromStripeAddress(shipping, config.country));
if (!result.valid) return showError(result.message);

Save the email

Collect the email in your own field and save it on the checkout before paying. Shoppable sends the order confirmation to it.

await client.updateCheckout(priced._id, { email });

Next to your Place order button, show config.checkoutTermsAndPrivacyCopyText: the terms and privacy text from your Cart Builder settings. It is HTML written by your team in the customer portal, so treat it like content from your own CMS (content management system): sanitize it, for example with DOMPurify, before inserting it into the page. The same applies to config.marketingOptInCopyText.

Place the order

The full submit handler: let Stripe validate its fields, validate the address, save the email, then placeOrder.

import {
ShoppableApiError,
ShoppablePaymentError,
fromStripeAddress,
toStripeShipping,
} from "@shoppable/checkout";
async function submitOrder(email) {
// Stripe shows inline errors for incomplete fields.
const { error: submitError } = await elements.submit();
if (submitError) return;
const { value } = await addressElement.getValue();
const check = await client.validateAddress(fromStripeAddress(value, config.country));
if (!check.valid) return showError(check.message);
const shipping = toStripeShipping(value);
try {
await client.updateCheckout(priced._id, { email });
const order = await client.placeOrder(priced._id, {
confirmPayment: (clientSecret) =>
stripe.confirmPayment({
elements,
clientSecret,
confirmParams: {
return_url: window.location.href,
shipping,
payment_method_data: {
billing_details: {
name: shipping.name,
email,
phone: shipping.phone,
address: shipping.address,
},
},
},
redirect: "if_required",
}),
});
showConfirmation(order.orderNumber);
} catch (err) {
if (err instanceof ShoppablePaymentError) {
showError(err.message);
} else if (err instanceof ShoppableApiError) {
showError("We couldn't complete your order and your card was not charged.", err.ref);
} else {
throw err;
}
}
}

placeOrder resolves with { status, orderNumber }. Show the order number on your confirmation screen; it is what the shopper quotes to support.

Why confirmParams.shipping is required

Shoppable places the order from the shipping address on the PaymentIntent, not from anything stored on the checkout. If you leave out confirmParams.shipping, the card is authorized, the order is refused for missing shipping fields, and the authorization is released. The shopper sees an error after entering a valid card, so always pass it.

The recipient name is split into first and last name at the last space, so a name with a single word fails with a missing firstName. The Address Element collects a full name; consider telling shoppers to enter both names.

3-D Secure

With redirect: "if_required", Stripe shows the bank’s 3-D Secure (3DS) challenge in a dialog on your page when the card needs one, and confirmPayment resolves after the shopper completes it. Stripe requires a return_url even so; the current page is fine.

When payment or the order fails

placeOrder throws one of two kinds of error. In neither case is the shopper charged.

ErrorMeaningWhat to show
ShoppablePaymentErrorStripe did not confirm the payment: the card was declined, 3DS failed, or the shopper closed the wallet. No order exists.err.message, which is Stripe’s shopper-facing text. err.code has Stripe’s error code. Let the shopper try another card.
ShoppableApiError (or a subclass)Shoppable could not authorize or place the order: for example an item sold out or a price rose since pricing. Any authorization is released.”We couldn’t complete your order and your card was not charged.” plus Reference: <err.ref> when err.ref is set.

err.ref is an encrypted reference Shoppable support can decode to see exactly what went wrong. err.message on API (application programming interface) errors is for your logs; it can be technical.

After either error the checkout is still usable. If the cause was the cart (a sold out item or a new price), call prepareCheckout again so the shopper sees the current cart, then let them pay again. See Errors & reliability for retries and the full list of error classes.

Express wallets

Apple Pay and Google Pay go through Stripe’s Express Checkout Element. The wallet collects the email, phone, shipping and billing addresses, and Stripe attaches the shipping address to the payment for you, so confirmParams.shipping is not needed here.

Give the Express Checkout Element its own Elements instance, created with the same options as above, so elements.submit() for the wallet does not also validate your empty card form.

const expressElements = stripe.elements({
mode: "payment",
amount: Math.round(priced.total * 100),
currency: config.currency,
captureMethod: "manual",
});
const express = expressElements.create("expressCheckout", {
emailRequired: true,
phoneNumberRequired: true,
shippingAddressRequired: true,
billingAddressRequired: true,
});
express.mount("#express-checkout");
// The wallet sheet shows the server's shipping for the current cart.
express.on("click", (event) =>
event.resolve({
shippingRates: [
{
id: "shipping",
displayName: priced.shippingTotal === 0 ? "Free shipping" : "Shipping",
amount: Math.round(priced.shippingTotal * 100),
},
],
}),
);
express.on("shippingaddresschange", (event) => event.resolve());
express.on("confirm", async (event) => {
const { error } = await expressElements.submit();
if (error) return showError(error.message);
try {
if (event.billingDetails?.email) {
await client.updateCheckout(priced._id, { email: event.billingDetails.email });
}
const order = await client.placeOrder(priced._id, {
paymentMethod: event.expressPaymentType,
confirmPayment: (clientSecret) =>
stripe.confirmPayment({
elements: expressElements,
clientSecret,
confirmParams: { return_url: window.location.href },
redirect: "if_required",
}),
});
showConfirmation(order.orderNumber);
} catch (err) {
// Same handling as the card form.
}
});

When the cart is re-priced, call expressElements.update({ amount }) as you do for the card form. Shipping does not depend on the address, so the shipping address change handler only resolves. The paymentMethod you pass is recorded for reporting.

Test cards

With a test token, use Stripe’s test cards with any future expiry date, any CVC (card verification code) and any postal code. Address validation still runs in test mode, so use a real address.

Card numberResult
4242 4242 4242 4242Succeeds.
4000 0025 0000 3155Asks for 3DS authentication, then succeeds.
4000 0000 0000 0002Declined: ShoppablePaymentError.
4000 0000 0000 9995Declined for insufficient funds: ShoppablePaymentError.

Test mode places no real orders. Show a “Test mode” badge in your checkout when config.isTestMode is true.