Checkout with elements

Show prices, a card form and Apple Pay, Google Pay and PayPal buttons on your page with the Payments SDK.

Elements are separate blocks of the checkout: the card form and the wallet buttons. You put each block in your own layout. Elements work with Primer prices only.

Read Payments SDK first. It explains the publishable key and the script tag.

1. Initialize the SDK

W2WPay.init({
  key: 'w2w_pk_...',
  user: { id: 'user_123', email: '[email protected]' },
});
OptionDescription
keyRequired. The publishable key from Payments SDK.
user.idThe ID of the user in your system.
user.emailThe email of the user. web2wave saves it as the email user property.
visitThe ad tags of the user. See After the payment.

If the user signs in later, call W2WPay.identify({ id, email }).

2. Show the prices

Get the prices by their IDs. Use the web2wave price ID or the price ID of the payment system.

const prices = await W2WPay.getPrices([12, 13, 14]);

Each price has these fields:

FieldDescription
idThe web2wave price ID.
nameThe name of the plan.
amountThe price in minor units, for example 999 for 9.99.
amount_formattedThe price as text, for example 9.99.
currencyThe currency, for example USD.
first_payment_amountThe first payment. It is different from amount for a trial or an intro price.
period, period_intervalThe billing period, for example month and 1.
free_trial_daysThe days of a free trial, or 0.
access_levelsThe access levels of the price, for example ['premium'].

Use these fields to show your own plan cards. To get one price, call W2WPay.getPrice(12).

Currency

The SDK selects the currency of each price in this order:

  1. The currency that you send in currency, if the price has it.
  2. The currency of the user's country, if the price has it. The SDK finds the country by the IP address.
  3. The main currency of the price.
W2WPay.getPrice(12, { country: 'DE' });   // the price for a user from Germany
W2WPay.getPrice(12, { country: false });  // the main currency of the price
W2WPay.getPrice(12, { currency: 'EUR' }); // the price in EUR

Send the same country and currency to W2WPay.checkout(). Then the user pays the amount that your page shows.

3. Create a checkout

const checkout = await W2WPay.checkout({
  price: 12,
  metadata: { order: 'A-17' },
});
OptionDescription
priceRequired. The price ID.
country, currencyThe same values as in getPrices().
emailThe email of the user. The default is the email from init.
metadataYour own data, up to 20 keys. web2wave saves it on the subscription.
appearanceThe styles of the form and the buttons. See Styling.
localeThe language of the payment form, for example de.

If the user selects another plan, call checkout.updatePrice(13). The SDK does not draw the form again.

4. Show the card form and the buttons

checkout.mount('wallets', '#wallets');
checkout.mount('card', '#card');
document.getElementById('pay').onclick = () => checkout.submit();

mount(type, target) draws one block in the element target. These types are available:

TypeBlock
cardThe card form. The user pays with your button and checkout.submit().
walletsApple Pay or Google Pay, the first one that the device has.
apple_payThe Apple Pay button.
google_payThe Google Pay button.
paypalThe PayPal button.

The wallet buttons start the payment themselves. They do not need submit().

Apple Pay and Google Pay

A wallet is available if the Primer account has it and the device supports it. Apple Pay works only in Safari with a card in Apple Wallet.

Use getAvailableMethods() to show only the available buttons:

const methods = await checkout.getAvailableMethods();
// { card: true, apple_pay: true, google_pay: false, paypal: false, wallet: 'apple_pay' }

if (methods.wallet) {
  checkout.mount('wallets', '#wallets');
} else {
  document.getElementById('wallets').hidden = true;
}

wallet is the button that mount('wallets') shows, or null. If you mount a method that is not available, mount() returns null and the SDK sends the unavailable event.

⚠️

For Apple Pay, register the domain of your page in your Primer account. Without it, the Apple Pay button does not show.

5. Handle the result

checkout.on('processing', () => payButton.disabled = true);
checkout.on('success', ({ subscription }) => {
  // subscription.status, subscription.access_levels
});
checkout.on('error', (error) => {
  payButton.disabled = false;
  showError(error.message);
});
EventDataWhen
ready{ element }A block shows on the page.
unavailable{ element }A wallet is not available. Hide its container.
change{ element: 'card', complete }The card form becomes complete or incomplete.
processing{ method }The payment starts. Disable your button.
success{ session_id, user_id, subscription, method }web2wave has the subscription. Give access to the user.
pending{ session_id, method }The payment system took the payment, but the subscription is late. Your webhook comes later.
error{ code, message }The payment failed. The user can pay again in the same checkout.
cancel{ method }The user closed the wallet window.
price{ price_id, amount, currency }updatePrice() is complete.

An incomplete card form gives the error event with validation: true. A declined card gives the error event with the reason in message.

Styling

Send the styles in appearance when you create the checkout.

const checkout = await W2WPay.checkout({
  price: 12,
  appearance: {
    variables: {
      colorPrimary: '#2563eb',
      colorText: '#1a1f36',
      colorBackground: '#ffffff',
      colorBorder: '#d5d9e2',
      fontFamily: 'Arial, sans-serif',
      borderRadius: 10,
      inputHeight: 46,
    },
    wallet: {
      type: 'subscribe',
      color: 'black',
      height: 48,
      borderRadius: 8,
    },
  },
});

Card form

VariableDescription
colorPrimaryThe border of the active field.
colorTextThe text in the fields.
colorLabelThe labels above the fields.
colorBackgroundThe background of the fields.
colorBorderThe border of the fields.
colorPlaceholderThe placeholder text.
colorDangerThe border of an incorrect field and the error text.
fontFamilyThe font.
fontSizeBaseThe size of the text in the fields.
labelSizeThe size of the labels.
borderRadiusThe corner radius of the fields.
borderWidthThe border width of the fields.
inputHeightThe height of the fields.
inputPaddingThe space inside the fields.
spacingThe space between the fields.

A number is a value in pixels. You can also send a CSS value, for example '1rem'.

The card number, the date and the CVV are in secure Primer frames. Your page CSS does not change the text in these frames. The SDK sends colorText, colorPlaceholder, colorDanger, fontFamily and fontSizeBase into the frames.

⚠️

Use a font that the browser has, for example Arial or Georgia. The secure frames do not load the web fonts of your page.

The labels and the field borders are normal HTML on your page. You can change them with your CSS. The classes are w2w-pay-card, w2w-pay-field, w2w-pay-label, w2w-pay-input, w2w-pay-input--invalid and w2w-pay-error.

To change the labels or to show the name field, send options to mount():

checkout.mount('card', '#card', {
  labels: { number: 'Card number', expiry: 'Valid until', cvv: 'CVC', name: 'Name on card' },
  cardholderName: true,
});

Wallet buttons

OptionValues
typeplain, buy, subscribe, checkout, book, donate, pay, order
colorblack, white, white-outline. PayPal also has gold, blue and silver.
heightThe height in pixels.
borderRadiusThe corner radius. Half of the height or more makes a round button.

If a wallet does not have the type, it shows its plain button. To give one button another size, send it to mount():

checkout.mount('wallets', '#wallets', { height: 54, borderRadius: 27 });

Test the checkout

  1. In Payments SDK, click Open test page.
  2. Select a plan.
  3. Pay with a test card from your Primer sandbox.

Use test prices for tests. A test price uses the Primer sandbox keys of the project.

Errors

CodeDescription
invalid_keyThe publishable key is not correct.
price_not_foundThe project has no price with this ID.
unsupported_payment_systemThe price is not a Primer price. Use the embedded paywall.
validation_errorThe card form is incomplete.
payment_failedThe payment system declined the payment.
too_many_attemptsThe user opened too many checkouts. The user can try again later.
network_errorThe browser cannot connect to web2wave.