@paymid-limited/js
v0.2.0
Published
The Paymid JavaScript SDK. Accept card, Apple Pay and Google Pay payments on your own checkout page with one call.
Downloads
1,132
Readme
@paymid-limited/js
The Paymid JavaScript SDK. Accept card, Apple Pay and Google Pay payments on your own checkout page with one call.
- PCI scope SAQ A. The card form and wallet buttons are Paymid-hosted iframes. Card data never touches your page.
- No secrets in the browser. Your API key stays on your server. The SDK makes no network request of its own.
- Typed and small. Written in TypeScript, types included, no runtime dependencies, under 16 kB gzipped.
- Framework-free. Works with plain JavaScript, React, Vue and Angular, from npm or a script tag.
This README covers the SDK itself. Three more guides ship in the package under docs/:
| Guide | Covers |
| ---------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| Framework examples | The usePaymidCheckout hook for React and for Vue |
| Backend integration | The Paymid API calls your server makes, the return page, the webhook, saved cards |
| Apple Pay domain verification | The file your domain must serve before Apple Pay works |
Install
npm install @paymid-limited/jsNo bundler? Use the script-tag build.
Quick start
You need two endpoints on your own server (see What your server returns) and two steps in the browser.
1. Add a container and your own Pay button.
<div id="checkout"></div>
<button id="pay">Pay £10.00</button>
<p id="error" role="alert"></p>2. Create the checkout.
import { Paymid } from '@paymid-limited/js'
const checkout = await Paymid.checkout({
session: () => fetch('/api/paymid/session').then((response) => response.json()),
container: '#checkout',
submitButton: '#pay',
amount: '10.00',
currency: 'GBP',
returnUrl: 'https://shop.example/return',
createPaymentRequest: (input) =>
fetch('/api/paymid/payments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
}).then((response) => response.json()),
onFailed: ({ message }) => {
document.querySelector('#error').textContent = message
},
})That is the whole integration. In the sandbox, pay with the test card 4242 4242 4242 4242.
What happens:
- Session. The SDK calls
session. Your server builds it from the Paymid API. It contains no secret. - Render. The SDK mounts the Paymid iframes in your container.
- Pay. The shopper presses your Pay button, or approves an Apple Pay or Google Pay sheet.
- Payment request. The SDK calls
createPaymentRequest. Your server creates a payment request with Paymid and returns its id and reference. This is not the charge. - Charge. The Paymid iframe charges that payment request. The card exists only there.
- Result. On success the shopper lands on
returnUrl?reference=<reference>. On failureonFailedfires on your checkout page.
Options
Required:
| Option | Type | Description |
| ---------------------- | ---------- | --------------------------------------------------------------------- |
| session | function | Loads the Paymid session from your server. A session object works too |
| amount | string | For example '10.00'. Digits, at most two decimals, above zero |
| currency | string | For example 'GBP' |
| returnUrl | string | Absolute http or https URL of your return page, no # fragment |
| createPaymentRequest | function | Creates a payment request on your server, once per attempt |
Optional:
| Option | Type | Default | Description |
| ----------------- | --------------------- | ---------- | ------------------------------------------------------------------------- |
| container | selector or element | | Where everything renders. Without it, call checkout.mount() |
| containers | object | | A place of its own for card, apple or google. See Layout |
| submitButton | selector or element | | Your Pay button. Without it, call checkout.confirm() |
| methods | array | all three | Any of 'card', 'apple', 'google' |
| walletsPosition | 'top' or 'bottom' | 'top' | Wallet buttons above or below the card form |
| redirect | string | 'always' | 'if_required' stays on the page when no redirect is needed |
| paymentRequest | object or promise | | A request created up front. Replaces createPaymentRequest |
| holderName | string | | Pre-fills "Name on card" |
| savedCards | boolean | false | Offers saved cards in the card form. See Saved cards |
| currencySign | string | | Passed to the wallet buttons, for example '£' |
| appearance | object | | Look of the Paymid iframes. See Styling |
| locale | string | | Language of the Paymid iframes, for example 'en-GB' |
| onSubmit | function | | Runs before each card payment. Return false to stop it |
Event handlers, all optional:
| Handler | Fires when |
| ------------- | ---------------------------------------------------------------------- |
| onReady | The checkout has rendered. Receives the methods that are shown |
| onChange | The card form changes |
| onFailed | A card or wallet payment fails |
| onCancelled | The shopper closes a wallet sheet before approving it |
| onPaid | A payment is made without leaving the page (redirect: 'if_required') |
| onError | Something other than a payment goes wrong, such as iframes not loading |
Good to know:
- Pass exactly one of
createPaymentRequestandpaymentRequest. With both or neither,Paymid.checkoutrejects withinvalid_options. onSubmitruns for card payments only. To stop every method, check insidecreatePaymentRequest, which runs for all of them before anything is charged.- A
submitButtonis disabled by the SDK while a payment is in flight.
The checkout object
Paymid.checkout resolves with the checkout object.
| Method | Description |
| ------------------------------------------------ | ---------------------------------------------------------------------- |
| confirm() | Runs a card payment and resolves with the result |
| update(options) | Changes the amount, currency, appearance, locale or up-front request |
| reset() | Clears a locked or completed checkout for a new payment |
| setHolderName(name), focus(field), clear() | Work on the card form |
| mount(target), unmount() | Render the checkout, or remove its iframes |
| destroy() | Removes everything for good, for example on a route change |
| on(event, handler), off(event, handler) | Subscribe to ready, change, paid, failed, cancelled, error |
checkout.update({ amount: '12.50' })
const result = await checkout.confirm()
if (result.status === 'failed') showError(result.message)Handling results
Success. The shopper is sent to returnUrl?reference=<reference>. The reference in the URL is not proof of payment, so rely on the Paymid webhook, or a status lookup from your server, before you fulfil the order. Both are in the backend integration guide.
Failure. onFailed fires with what you need to respond:
| Field | Description |
| ----------- | -------------------------------------------------------------- |
| method | 'card', 'apple' or 'google' |
| code | An error code, for example payment_failed |
| message | A readable message you can show the shopper |
| retryable | true when the shopper can simply press Pay again |
| reference | The payment request reference, when the failure is tied to one |
When retryable is false (payment_outcome_unknown, payment_request_spent), the charge may have gone through. Check the reference on your server before you allow another attempt.
New codes can arrive in minor versions, so give every switch on code or status a default branch.
Saved cards
Pass savedCards: true to let returning shoppers pay with a card they saved, and to offer "save this card" on a new one. Everything renders inside the Paymid iframe.
The snippets from here on show only the options that differ from the Quick start.
await Paymid.checkout({
savedCards: true,
paymentRequest: fetch('/api/paymid/payments', { method: 'POST' }).then((response) => response.json()),
})- Your server must create the payment request with a
customerToken. Without it nothing is listed and nothing is saved. See Saved cards in the backend guide. - The list needs the up-front
paymentRequest. WithcreatePaymentRequestthe shopper still gets the "save this card" checkbox, but no list. - A saved card still needs its CVC, typed inside the iframe.
Layout
Everything renders inside the one container:
#checkout your container
└─ .paymid-checkout added by the SDK
├─ .paymid-checkout__wallets Apple Pay and Google Pay buttons
└─ .paymid-checkout__card card form- A wallet shows only when your session enables it and the browser supports it. If none can show, the wallet area is hidden and the card form stays.
- Your Pay button pays by card. Apple Pay and Google Pay are paid from their own buttons.
- The three class names are yours to style.
To place each method yourself, name a container per method:
await Paymid.checkout({
containers: { apple: '#apple-pay', google: '#google-pay', card: '#card-form' },
})- Each iframe fills 100% of its container.
- A method without its own entry stays in the main
container, which is optional only when every enabled method has an entry. - A container that cannot be found throws
mount_target_not_found, and nothing is rendered.
Styling
Pass an appearance object. variables set what the whole form shares, and the named parts style the input fields:
await Paymid.checkout({
locale: 'en-GB',
appearance: {
theme: 'light',
labels: 'above',
variables: {
colorPrimary: '#0b5fff',
colorText: '#1a1a1a',
fontFamily: 'Inter, system-ui, sans-serif',
fontSize: 16,
borderRadius: 8,
walletButtonHeight: 48,
},
input: { height: 48, backgroundColor: '#f9fafb', borderColor: '#d0d5dd' },
inputFocus: { borderColor: '#0b5fff', ringColor: '#0b5fff33', ringWidth: 3 },
inputInvalid: { borderColor: '#d92d20' },
label: { color: '#475467', fontSize: 13, fontWeight: 600 },
},
})| Group | Styles |
| --------------------------------------------------- | ------------------------------------------------------------- |
| theme, labels | Light or dark, and labels above the fields or as placeholders |
| variables | Colours, font, radius, spacing and the wallet button size |
| input, inputHover, inputFocus, inputInvalid | The input fields, at rest and in each state |
| label, placeholder, error | The text around the fields |
- Fixed list, no CSS. You cannot pass CSS, selectors or HTML into the iframes. A value outside its accepted range is dropped, with no error.
- Wallet buttons follow Apple's and Google's design rules, so only
theme,walletButtonHeightandwalletButtonRadiusapply to them. - Change it later with
checkout.update({ appearance, locale }).
What your server returns
The SDK never calls your API itself. Your two functions do, with your own auth. How your server builds each answer is in the backend integration guide.
Session, returned by your session function:
{
"embedBaseUrl": "https://checkout.paymid.example",
"merchantAccountId": "your-merchant-account-id",
"merchantName": "Your Shop",
"country": "GB",
"applePay": true,
"googlePay": {
"publicKey": "...",
"merchantId": "...",
"environment": "TEST",
"supportedAuthMethods": ["CRYPTOGRAM_3DS"]
}
}Set googlePay to null to hide Google Pay. applePay: true also needs domain verification.
Payment request, returned by your createPaymentRequest function, a new one for every attempt:
{ "paymentRequestId": "the id Paymid returned", "reference": "your order reference" }Neither object contains a secret. A wrong session makes Paymid.checkout reject with invalid_session. A wrong payment request fails the attempt with payment_request_failed.
Other entry points
Script tag. dist/paymid.umd.js defines window.Paymid. Call Paymid.checkout with the same options as the Quick start. Paymid does not host the file: copy it from the package and serve it yourself.
<script src="/assets/paymid.umd.js"></script>React and Vue hooks. usePaymidCheckout from @paymid-limited/js/react or @paymid-limited/js/vue creates the checkout on mount, pushes option changes to it and destroys it on unmount. It takes the same options, without container and submitButton. React 18 and Vue 3.3 or newer. See Framework examples.
const { containerRef, submitButtonRef, ready, error } = usePaymidCheckout(options)Web components. import '@paymid-limited/js/elements' registers <paymid-card> and <paymid-wallets>. The plain @paymid-limited/js import registers nothing and has no side effects.
Element API. Paymid.init or loadPaymid, then create('card'), create('wallets') and confirmCardPayment, for when you want to drive the card form and the wallet buttons yourself. Paymid.checkout is built on it.
Browser support
The last two versions of Chrome, Edge, Firefox and Safari, on desktop and on iOS. The SDK uses URL.canParse, available from Chrome and Edge 120, Firefox 115 and Safari 17. In an older browser Paymid.checkout rejects.
Security
- Card data stays in the iframe. No SDK value, event or error contains card data.
- No secret in the browser. It receives only a session with no secret, and the id and reference of one payment request.
- Exact origin. The SDK sends messages only to the origin of the session's
embedBaseUrl, never*, and accepts messages only from that origin and from its own iframe. - No injected styling. Appearance is a fixed list of named values, checked by the SDK and again by the iframe.
- Safe redirects. The SDK only redirects to absolute
httpandhttpsURLs.
Versioning
This package follows semantic versioning. Changes are listed in CHANGELOG.md, included in the package. Minor versions may add new result statuses, error codes, events and fields, so your code must handle values it does not know. Only major versions remove or change existing behaviour.
