@highwirepayments/payment-sdk
v0.10.1
Published
HighWire Payment SDK — one hw.mount() for the card field, Apple Pay, Google Pay and the provider's drop-in, with PCI-isolated card entry.
Maintainers
Readme
HighWire Payment SDK
Browser SDK for taking a payment on a merchant's page. hw.mount() draws, into a container you
choose, the checkout the HighWire gateway's session calls for: a secure card field with Apple Pay and
Google Pay, the card field alone, or the payment provider's own form. Every result, whichever method
took it, arrives through one callback.
A card typed into the card field is encrypted inside a cross-origin iframe the gateway serves
(hybrid AES-256-GCM + RSA-OAEP-256): the merchant page and the wire only ever see ciphertext. The
gateway decrypts the card and runs the payment. Its pages are built in this workspace's
packages/gateway-pages.
merchant page ──▶ SDK ──▶ secure card field (iframe) ──(ciphertext)──▶ gatewayInstall
npm install @highwirepayments/payment-sdkOn a page without a bundler, load the CDN build instead, pinned with the SRI hash you were given:
<script
src="https://cdn.highwirepayments.com/sdk/<version>/highwire.js"
integrity="sha384-<the hash for that version>"
crossorigin="anonymous"></script>
<script type="module">
const HighWire = window.HighWire.default; // window.HighWire is a namespace; `default` is the factory
</script>On Airwallex, Google Pay is an Airwallex component, and it runs on your page. The CDN build (about
30.5 KB gzipped) bundles Airwallex's components loader, so the <script> tag above is all you load. The
ES build imports @airwallex/components-sdk, an optional peer dependency, the first time an Airwallex
checkout draws Google Pay. Your bundler resolves that import when it builds, whatever your
provider, so install it next to the SDK; a Whop checkout never loads it.
npm install @airwallex/components-sdkUsage
init() once per page, mount() when the shopper reaches the payment step, submit() on your Pay
button, unmount() when the checkout leaves the page.
import HighWire from '@highwirepayments/payment-sdk';
const hw = await HighWire.init({
publishableKey: 'hw_pk_live_…', // hw_pk_test_… in sandbox
apiBase: 'https://<gateway-host>', // your HighWire gateway origin, from onboarding
});
const paymentContainer = document.querySelector('#payment')!;
paymentContainer.setAttribute('inert', '');
payButton.disabled = true;
let ready = false;
let cardComplete = false;
let orderBound = false;
let processing = false;
let ended = false;
const syncPay = () => {
const hasCard = paymentContainer.querySelector('[data-hw-slot="card"]') !== null;
payButton.disabled = !orderBound || !ready || processing || ended || (hasCard && !cardComplete);
};
// When the shopper reaches the payment step. mount() creates the payment.
const checkout = await hw.mount({
container: '#payment',
amount: 2999, // integer cents
currency: 'usd',
onReady: () => { ready = true; syncPay(); say(''); },
onAvailabilityChange: (available) => { ready = available; syncPay(); }, // WHOP only
onChange: (card) => { cardComplete = card.complete; syncPay(); },
onProcessing: () => { processing = true; syncPay(); say('Processing your payment…'); },
onResult: (result) => {
processing = false;
if (result.status === 'declined' && result.retryable) {
syncPay();
return say('Declined. Try another card or method.');
}
ended = true;
syncPay();
if (result.status === 'declined') return say('This checkout has ended. Please start again.');
if (result.status === 'pending') return say('We are confirming your payment.'); // not known yet
showThankYou(); // fulfil from your server's read of the payment
},
onError: (error) => {
say(messageFor(error.code));
const canSubmitAgain = error.recovery
? error.recovery === 'correct' || error.recovery === 'retry'
: error.code === 'HW_INCOMPLETE' || error.code === 'HW_NOT_READY' || error.code === 'HW_UNSUPPORTED';
if (canSubmitAgain) {
processing = false;
syncPay();
} else if (error.recovery === 'unavailable') {
ended = true;
syncPay();
} else if (error.recovery !== 'wait' && orderBound) offerServerPaymentCheck(checkout.paymentId);
},
});
// Tie the payment to your order, on your server, before the shopper can pay.
const binding = await fetch(`/orders/${orderId}/payment`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ paymentId: checkout.paymentId }),
});
if (!binding.ok) {
checkout.unmount();
throw new Error('Could not link the payment to the order');
}
orderBound = true;
paymentContainer.removeAttribute('inert');
syncPay();
// Card fields and WHOP use your Pay button.
payButton.hidden = !checkout.requiresSubmit;
payButton.onclick = () => {
processing = true;
syncPay();
checkout
.submit({ customerEmail: email, customerPhone, billingAddress: { name: billingName, country: billingCountry, line1, line2, city, state, postalCode } })
.catch(() => {});
};
// When the shopper goes back to edit the order:
checkout.unmount();HighWire.init(config)
| Option | |
|---|---|
| publishableKey | hw_pk_test_… (sandbox) or hw_pk_live_… (production). Safe to embed in the page. |
| apiBase | The HighWire gateway's origin. https, except on localhost. |
| fieldsOrigin | Optional. The origin serving the card field and the drop-in; defaults to apiBase. Leave it unset unless HighWire gives you one. |
init() throws HW_UNSUPPORTED synchronously on an invalid config. Otherwise it resolves with the
instance once the device session has settled, or after 2 s (see Device screening).
The instance is a frozen object with only two methods: mount() and chargeSavedMethod().
hw.mount(options)
| Option | |
|---|---|
| container | Required. A CSS selector or an Element. |
| amount | Required. Integer cents. |
| currency | Required. 'usd' is the only currency taken. |
| savePaymentMethodForFutureUse | Shows an unticked save-card box in the card field, or under Whop's card form on WHOP. Only the shopper's tick saves it under the e-mail submit() sends. Airwallex Drop-in and wallet payments show no box and save no card. See Saving a card. |
| billingAddressForm | 'none' (default): your page passes the full billing address to submit(); WHOP needs at least name, country and postal code. 'full': WHOP shows its own billing form and submit() takes no billingAddress. WHOP only: any other checkout rejects HW_UNSUPPORTED. Read at mount() only. See WHOP's billing form. |
| onReady() | The card field or the provider's form is ready. |
| onChange(card) | The card field changed: { complete, empty, brand, error }. Enable Pay on complete. No card value is ever part of it. |
| onProcessing(method) | A payment started and the SDK is confirming it. |
| onResult(result) | A payment's result. See Results. |
| onError(error) | Every failure, including each rejection of mount() and submit(). After unmount(), only the failure of a payment already in progress. See Errors and retries. |
mount() resolves with the Checkout once its parts are on the page.
mount()creates the payment and reserves your account's limits. Call it when the shopper reaches the payment step, not on page load.- One mounted checkout per instance.
unmount()it before mounting another. - Mounting the same order again after
unmount()(same amount, currency andsavePaymentMethodForFutureUse) reuses its payment while that payment is open. Another amount creates a new one. Another save option does too, once the order's last payment can no longer capture.
Checkout
| Member | |
|---|---|
| paymentId | The payment this checkout charges. Send it to your server and tie it to the order. |
| requiresSubmit | true for a card field or WHOP. Show your Pay button; WHOP becomes available on onReady, cards on onChange.complete. Airwallex Drop-in retains its own payment controls. |
| submit(payer?) | Pays with the card field or WHOP. payer is { customerEmail?, customerPhone?, billingAddress?: { name?, country?, line1?, line2?, city?, state?, postalCode? } }. WHOP copies, trims and validates recognized fields and needs the full billing address, with at least name, two-letter country and postal code (the SDK checks name and country; Whop validates postal code); with billingAddressForm: 'full' it requires no address and rejects one. A card needs customerEmail here. WHOP needs one here or falls back to the email of the last attempt WHOP declined; before such a decline an omitted one rejects HW_INCOMPLETE. The gateway screens and binds it when the frame confirms the card token, before WHOP is called, and takes a corrected one up to 3 per payment (see WHOP integration). Raw-card mapping retains its existing email/phone/line1/city/state/postal fields. Resolves with the same result onResult receives. |
| recheck() | Reads the original WHOP payment once without minting a session or submitting again. Available after an uncertain submit settles or returns pending, including after unmount. Returns succeeded or pending; does not repeat onResult. Other providers reject HW_UNSUPPORTED. |
| unmount() | Removes the checkout from the page. A payment already being confirmed still reaches onResult, except a card whose confirm has not answered yet: submit() then rejects HW_DESTROYED and that answer is lost (see A lost answer). |
What mount() draws
What mount() draws comes from the checkout's session (layout), never from the merchant's code:
| layout | Parts, in the order they are added | requiresSubmit |
|---|---|---|
| card_and_wallets (Airwallex) | googlePay, card | true |
| card_and_wallets (Yuno) | applePay, googlePay, card | true |
| card_only (Airwallex, Yuno) | card | true |
| drop_in (WHOP) | dropIn | true |
| drop_in (Airwallex) | dropIn | false |
Airwallex checkouts default to card_and_wallets. Yuno checkouts default to card_only: the card
field, and the gateway charges Yuno from it. Yuno's card_and_wallets adds Apple Pay and Google Pay,
each only when the session lists it: Apple Pay only on a domain enabled for it (Wallets).
HighWire's hosted checkout does the same on Yuno, once the gateway lists applepay for it. Airwallex
checkouts offer no Apple Pay. Whop checkouts are always drop_in: Whop's own
Payment Elements card form with a visible Buyer Terms line: your page supplies email and the full
billing address, and your Pay button calls submit(payer). With billingAddressForm: 'full', the shopper
enters the address in Whop's form instead. WHOP Elements offers cards only.
A full-page 3DS step can take the merchant's tab to the gateway's return page; the result then comes
by webhook and the gateway status read.
See Merchant payer submission for readiness, identity and retry rules.
On Airwallex the drop-in is Airwallex's complete form, never with Apple Pay. A wallet the session
does not offer gets no slot.
The hooks your CSS can use:
- The container gets
data-hw-layoutwith the layout's name. - Each part is a direct child of the container, added after its own children, and marked
data-hw-slot="applePay" | "googlePay" | "card" | "dropIn". Reorder the parts with CSSorderin a flex or grid container. - A wallet that cannot pay on this browser, or that failed once the checkout's session had expired,
gets
hidden. Do not setdisplayon the slots: it would overridehidden. - A slot that draws nothing gets
data-hw-empty, for collapsing spacing or labels. Neverdisplay: nonethe slot itself: it would never report a size again. - The wallet and drop-in slots get
inertandaria-disabled="true"while a payment is in progress, and after a card confirm whose answer was lost, until that answer is known. - While a payment is being confirmed, from
onProcessinguntil itsonResultoronError, the container getsdata-hw-processingwith the method (card,applePay,googlePay,dropIn): cover the checkout with a loader from CSS alone. A 3-D Secure dialog opens above the page, not inside the container. A WHOPrecovery: 'wait'error keeps the original operation's indicator. Other WHOP errors clear the indicator while the retained payment can remain locked and its status can still be checked. - While Whop shows a verification or address overlay, the
dropInslot's frame covers the window, above the page; the slot keeps its height meanwhile. Inside atransformed,filtered orcontained ancestor it can only cover that ancestor. unmount()removes the slots and the container'sdata-hw-processing, and puts itsdata-hw-layoutback as it was. A checkout that has ended removes its slots by itself.
#payment { display: flex; flex-direction: column; }
#payment > [data-hw-slot] { margin-bottom: 12px; }
#payment > [data-hw-empty] { margin-bottom: 0; }
#payment > [data-hw-slot="card"] { order: -1; } /* the card field above the wallets */
#payment { position: relative; }
#payment[data-hw-processing]::after { content: ''; position: absolute; inset: 0; background: rgb(255 255 255 / .7); }Results
onResult receives every result: card, Apple Pay, Google Pay and drop-in. On a card layout or WHOP,
checkout.submit() resolves with the same object; when a wallet takes the payment while submit()
runs, it resolves with that wallet's result.
interface PaymentResult {
status: 'succeeded' | 'declined' | 'pending';
paymentId: string; // the same as checkout.paymentId
retryable?: boolean; // on every 'declined' result
paymentMethodId?: string; // a card the shopper chose to save
customerId?: string;
maskedCard?: string; // first 6 and last 4 digits
}| Result | What it means | What to do |
|---|---|---|
| succeeded | Paid, as far as the browser can tell. | Show the thank-you page; fulfil from your server's read of the payment. |
| declined, retryable: true | Not paid. The checkout stays open. | Let the shopper try another card or method on the same checkout. If it was unmounted meanwhile, mount the same order again: it reuses the payment. |
| declined, retryable: false | Not paid, and the checkout has ended: its slots are removed. | Another attempt is a new order: a new mount(). |
| pending | Not known yet, and the checkout has ended. | Read the payment on your server before taking another one for the same order. After a card pending, mounting the same order again reads that payment first and creates a new payment only once it reads declined, expired or voided: it rejects HW_SESSION_EXPIRED once the payment has captured, and HW_TOKENIZE_IN_PROGRESS while it reads anything else or cannot be read (a network failure rejects with its own code). |
A card decline's retryable follows the gateway where it says whether the payment takes another card
attempt: a fifth decline, or a decline from a risk decision, is retryable: false. Where it does not
say, such a decline is retryable: true, and the next card attempt is refused without charging and
ends the checkout: submit() rejects HW_SESSION_EXPIRED after a fifth decline, and otherwise resolves
declined with retryable: false. A card the gateway's velocity checks refuse resolves declined with
retryable: true: nothing was charged, and another card can pay on the same checkout. The same card is
refused again until the window passes (the same card at the same amount within 5 minutes is a
duplicate).
A card result is read from the gateway before it reaches you. When the processor has not decided yet,
submit() keeps waiting (after onProcessing), up to 3 minutes, and resolves succeeded, declined
with retryable: false, or pending.
onResult is not proof of payment. Fulfil the order from your server's read of the payment
bound to it: GET /v1/payments/:id with your Basic credentials, or the gateway's webhook. Never
fulfil from an id the browser sends. A payment can settle after the shopper has left the page (a
3-D Secure challenge, a wallet, the drop-in), so reconcile pending orders from your server too.
There is no decline reason in the result: show your own decline message.
3-D Secure
A card the issuer challenges is verified inside submit(): the SDK opens a dialog over your page,
and submit() resolves once the payment settles. Nothing extra to call. Closing the dialog rejects
HW_3DS_ABANDONED and ends the checkout. A challenge not finished within 10 minutes rejects
HW_TIMEOUT: call submit() again, and it resends the same attempt. If the shopper changed the card
or the save-card box before that retry, the gateway refuses the resent attempt, and submit() shows
the challenge the gateway still holds instead. That challenge pays with the card the first attempt
sent, and the result carries no paymentMethodId, customerId or maskedCard. A challenge whose
dialog could not open is tried again the same way by the next submit(). The dialog frames the
verification page from yours, so a strict Content-Security-Policy has to allow it: see
3-D Secure in docs/CDN_INTEGRATION.md.
Errors and retries
mount() and submit() reject with the same HighWireError they pass to onError: one failure, one
event. With onError set, a rejection it already heard is never reported as unhandled. After
unmount(), submit() only rejects, so keep a catch on it. HighWireError is exported.
WHOP errors include recovery; use it before falling back to code:
| Recovery | What to do |
|---|---|
| correct | Let the shopper correct their contact or billing details, then submit again. |
| retry | The payment was not dispatched. Allow another submit once the form is available. |
| wait | Keep Pay disabled and wait for the active operation to settle. |
| recheck | Keep Pay disabled and show that the payment is unconfirmed. After the active submit settles, offer a Check payment button that calls checkout.recheck(). |
| unavailable | Disable submission on this checkout. |
A WHOP provider error can reach onError while submit() is still checking the original payment.
Show “Checking your payment status…” and keep replacement payments blocked. Calling recheck()
during that operation rejects with recovery: 'wait'. Once it settles, render the result returned by
recheck() explicitly; it does not call onResult again. A pending check never grants another charge.
For errors without recovery, use code:
| Code | When | What to do |
|---|---|---|
| HW_NETWORK, HW_TIMEOUT, HW_SERVICE_UNAVAILABLE | The gateway or submit bridge could not answer. | From submit(): call it again. Cards resend the same idempotent attempt; WHOP checks the original payment without another provider submit. From mount(): nothing is mounted; call mount() again. |
| HW_DECLINED | mount(): the gateway refused to create the payment: a merchant limit, a risk decision, or a failure at the payment provider or in reserving the limits, which the gateway records as a decline. Nothing is mounted, and nothing is charged. WHOP submit(): the gateway denied the shopper's e-mail, with recovery recheck; see a WHOP e-mail the gateway denies. | Show your decline message. Another mount() creates a new payment, which can pass when the cause was a failure; a limit or a risk decision refuses it again, so do not retry in a loop. After a WHOP submit(), follow the recovery: that checkout takes no other payment. |
| HW_SESSION_EXPIRED | The checkout's payment has ended: its session expired, the shopper tried again after five declines, or the checkout had already ended. WHOP submit(): the payment takes no e-mail any more; one the SDK then reads as paid resolves succeeded instead. From mount() of the same order: its last payment ended without the page hearing how. | The checkout has ended. Read the payment on your server: it may have been paid. Another attempt is a new order: a new mount(). |
| HW_3DS_ABANDONED | The shopper closed the 3-D Secure dialog. | The checkout has ended. Keep reading the payment on your server: a challenge finished as the dialog closed can still capture. Another attempt is a new mount(). Mounting the same order again rejects HW_TOKENIZE_IN_PROGRESS while that payment is still being confirmed or cannot be read (its verification counts as being confirmed for 2 minutes after the dialog closed), and HW_SESSION_EXPIRED once it has captured. |
| HW_INCOMPLETE | The card is incomplete, or submit()'s e-mail is missing or malformed. | Let the shopper fix it, then call again. |
| HW_NOT_READY | submit() before the card field loaded, or while it reloads. | Enable Pay only once onChange reports complete. |
| HW_IFRAME_UNRECOVERABLE, HW_PROTOCOL_MISMATCH | Through onError only; mount() still resolves. The card field or the provider's form could not load. A HW_TIMEOUT there means the same, and so does HW_UNSUPPORTED when a WHOP checkout mounted with billingAddressForm: 'full' cannot show its billing form. | Tell the shopper the payment form is unavailable. unmount(), then mounting the same order again reuses its payment. |
| HW_TOKENIZE_IN_PROGRESS | A payment is already in progress, or mount() of a different order while a card confirm's answer is unknown, or mount() of the same order after HW_3DS_ABANDONED or a card pending while that payment is still being confirmed or cannot be read. | Wait for the result. After a lost answer, call submit() on the same order again (mount it again with the same options if it was unmounted). After HW_3DS_ABANDONED or a card pending, read the payment on your server and mount the order again once it has declined, expired or been voided; each such mount() reads the payment, so space retries a few seconds apart. |
| HW_DESTROYED | submit() on an unmounted checkout, or unmount() while submit() ran. Unmounted after the card was sent, the confirm's answer is lost: the card may have been charged. | Mount the same order again with the same options, then call submit(). |
| HW_UNAUTHORIZED | The gateway refused the key or the page's origin. | Check the publishable key and the origins registered for your account. |
| HW_UNSUPPORTED | Invalid options, a second mount() on the same instance, submit() on a checkout whose requiresSubmit is false, or a checkout this SDK cannot draw. From mount(), also billingAddressForm: 'full' on a checkout that is not WHOP. From submit(), also a card attempt the gateway refused without charging, with the checkout still open, or a billingAddress passed to a 'full' checkout. | Fix the integration. After a refused card attempt, let the shopper try another card. After a 'full' mount is refused, mount again with 'none' and show your own billing form: the same payment is reused. |
A lost card answer. After HW_NETWORK, HW_TIMEOUT or HW_SERVICE_UNAVAILABLE from card submit(), or
HW_DESTROYED when the checkout was unmounted after the card was sent, the payment may or may not have
gone through. Until that confirm's answer is known, the wallet and drop-in slots stay inert, and
mounting a different order rejects HW_TOKENIZE_IN_PROGRESS. Call submit() again (after
HW_DESTROYED, on the same order mounted again): it resends the same attempt, so the shopper is never
charged twice, and its answer tells you how the payment ended.
An uncertain WHOP attempt. A refused card-token preparation allows correction before dispatch. After dispatch
could have started, another submit() only reads the same payment; it never changes the payer or
submits to WHOP again. A final pending result ends the checkout and blocks reminting it from a later
declined or expired read. Check that payment on your server before starting another checkout. These
locks persist across same-instance unmount/remount, but do not coordinate independent tabs or devices.
A WHOP card decline. WHOP refusing the card resolves submit() and calls onResult with declined. With
retryable: true the checkout stays open for another card; with retryable: false it has ended, as after a
card decline. An e-mail, card details or billing address WHOP
cannot use rejects HW_INCOMPLETE with recovery correct.
A WHOP e-mail the gateway denies. When the gateway's screen of the e-mail submit() sent denies
the payment, submit() rejects HW_DECLINED with recovery recheck at once, and that submit never
reaches WHOP. WHOP may still capture a payment already in flight, so the SDK keeps the payment: a later
submit() only reads its status, for up to 3 minutes (a capture resolves succeeded, and otherwise
submit() resolves pending when the 3 minutes are up), and recheck() reads it once. A status read
that fails for good rejects HW_SERVICE_UNAVAILABLE with recovery recheck; network and gateway
outages are retried within the 3 minutes. Even once the payment reads declined, the checkout
takes no other payment: read it on your server before you start another checkout for the order.
A refusal that reads as a network error. The gateway answers a revoked key (401), an inactive
merchant (403) and its rate limit (429) without CORS headers, so the browser cannot read them and the
SDK reports HW_NETWORK, not HW_UNAUTHORIZED or HW_RATE_LIMITED. A page origin missing from your
account's registered origins is a readable 403: HW_UNAUTHORIZED. When mount() keeps failing with
HW_NETWORK, check the key and the account before the network.
Wallets
Apple Pay is offered on Yuno checkouts only; the SDK draws no Apple Pay on Airwallex. It always runs on the merchant's page, outside HighWire's iframe, and Apple validates the page's own domain. HighWire enables the domain for Apple Pay in its admin, which registers it with your Yuno account, and gives you Yuno's domain-association file:
- Serve it, unchanged, at
https://<your-domain>/.well-known/apple-developer-merchantid-domain-association: plain text, no extension, no redirect, and keep it there. - Check it:
curl https://<your-domain>/.well-known/apple-developer-merchantid-domain-associationmust return the file, not your site'sindex.html.
The checkout's session lists applepay only on a page whose origin is enabled.
Apple Pay renders only on https; in Safari, and on other desktop browsers on a registered domain,
through Apple's flow that finishes on the shopper's iPhone. Elsewhere its slot
stays hidden or data-hw-empty, and nothing reaches onError. A checkout embedded in a
third-party iframe needs Safari 17 or later, allow="payment" on that iframe, and both domains
registered.
Google Pay needs no domain file. Its sheet shows the merchant name from the checkout's session.
Apple Pay and Google Pay on Yuno are drawn by Yuno's Web SDK on the merchant's page, both from one
Yuno transaction, which the SDK loads from one pinned prod.y.uno URL with its SRI hash when the
buttons mount. Each tap is its own attempt: the gateway creates the Yuno payment from the wallet's
one-time token, and the result arrives through onResult like a card's. A dismissed sheet reports
nothing. A declined attempt reports declined with retryable: true and both buttons come back for
another try; an attempt whose answer was lost waits on the payment's status and reports pending if
it is still open, never declined.
Whop Elements checkouts accept cards only. submit(payer) sends the email and billing address
with the card token before the gateway confirms it. Phone is not forwarded. The theme follows the
container's color-scheme (light, dark, or the shopper's preference with light dark), falling
back to the shopper's system setting.
Content-Security-Policy. The wallets and the device session load from Airwallex's, Apple's,
Yuno's, Google's and the fraud vendor's hosts on your page, besides the gateway and the card field's origin. The hosts to
allow are in the Content-Security-Policy section of docs/CDN_INTEGRATION.md.
Saving a card and charging it again
Mount with savePaymentMethodForFutureUse: true: the card field shows the shopper an unticked
save-card box. Only the shopper's own tick saves the card, under the e-mail submit() sends: the
gateway finds or creates that customer then. The card's PaymentResult then carries paymentMethodId
and customerId; without the tick there is neither. A
result after a 3-D Secure challenge that submit() had to reopen (see 3-D Secure)
carries none either.
On WHOP the box sits under Whop's card form, and the checkout passes the shopper's choice to Whop
with the card and to the gateway with the e-mail, before anything is charged. A succeeded result
carries paymentMethodId and customerId once the ticked card is saved. Changing the box while a
WHOP payment of the checkout is in progress rejects HW_TOKENIZE_IN_PROGRESS with recovery
recheck. chargeSavedMethod() charges a WHOP card saved this way like any other saved card. Whop
collects it asynchronously, so expect pending and settle it from your server. A WHOP card whose
issuer asks for 3-D Secure again does not capture there: the call has no shopper verification step,
and Whop leaves the charge waiting.
hw.chargeSavedMethod() charges that card again, for an add-on: no field, no checkout, and it works
after a reload.
const addOn = await hw.chargeSavedMethod({
paymentMethodId, // from the earlier checkout's PaymentResult
amount: 500, // integer cents
idempotencyKey: addOnKey, // required: one per add-on, stored with it
});
// { status: 'succeeded' | 'declined' | 'pending', paymentId, amount, paymentMethodId }idempotencyKeyis required here, and it is yours to keep: store it with the add-on so a retry, even after a reload, sends the same one. A retry under the same key is never charged twice.- The gateway bounds reuse: a time window after the card was saved, a number of charges, and an amount
no higher than the payment that saved it. Outside those bounds the call rejects:
HW_UPSELL_NOT_READY: the checkout that saved the card has not settled yet. Retry shortly with the sameidempotencyKey.HW_UPSELL_AMOUNT_EXCEEDED: above the amount of the payment that saved the card. A smaller amount may pass.HW_UPSELL_REFUSED: this card cannot be charged again.
HW_RATE_LIMITED: the gateway's velocity checks refused the card (the same card at the same amount within 5 minutes is a duplicate). Nothing was charged, and the gateway keeps that refusal under the key: a retry later needs a newidempotencyKey.- A decline resolves with
status: 'declined'.pendingsettles later: read it on your server (GET /v1/payments/:id). - One call at a time per instance: a second call while one runs rejects
HW_TOKENIZE_IN_PROGRESS.
Session lifetime
The payment session expires 30 to 60 minutes after the mount() that created its payment. The length
is a setting of your account, and the gateway applies it in an hourly sweep. Airwallex's wallet secret
lasts 60 minutes. The SDK renews neither. Once the sweep has expired the payment, a card payment on
that checkout rejects HW_SESSION_EXPIRED, and an Airwallex wallet or drop-in payment that fails reports
declined with retryable: false; before the sweep, a failing wallet or drop-in reports
retryable: true. Apple Pay or Google Pay failing at or past the session's expiry (the expiry the
gateway sends with the session, or 55 minutes after that mount() when it sends none) is then taken
off the checkout if that failure leaves the checkout open: its slot becomes hidden, mounting the
same order again leaves it out, and the card field and the drop-in stay. A new order is a new
mount(). Mount at the payment step, not on page load: visitors who never reach it
reserve nothing.
Device screening
init() asks the gateway for this checkout's device session and loads whatever your account needs:
the fraud vendor's script, the processor's fingerprint script, both or neither. Nothing to configure: the
gateway decides from the publishable key, and mount() attaches the session key to the payment by
itself.
It is fail-open: a CSP, an ad-blocker, a gateway error or a vendor outage resolves to "no session",
and the payment proceeds unscreened. init() resolves once the session has settled, or after 2 s while
it keeps loading, and mount() waits at most 2 s more for the key.
Merchants who charge through the Direct API from their own backend have two ways to the key.
Read it off the collector entry, with the same apiBase as init() —
await HighWireCollect({ publishableKey, apiBase }).riskSessionKey(), a string or null when there
is no screening, see Direct API: collect — and relay it to the backend. Or mint one yourself — POST /v1/sdk/payments/session, with the publishable
key in the X-Publishable-Key header and no body — and initialise the vendor's browser loader with
it, from the page, before the shopper pays: the response says which loader and with what. A key is
only a handle; a key no browser reported on is screened without device signals, exactly like no key
at all.
Either way the key goes on the charge as riskSessionKey — on POST /v1/payments/auth for an
authorization-only hold as much as on POST /v1/payments/auth-and-capture; a charge sent without it
is still screened, without a device behind it.
The hosts this loads from need a CSP allowance: see the Content-Security-Policy section of
docs/CDN_INTEGRATION.md.
Direct API: collect
For merchants who render their own payment form and charge from their backend (the Direct API), the
same package ships a second, separate entry: the browser-context collector. It adds deviceData and
the device-session key to the request the merchant's backend already sends, and loads none of the
checkout code above. Each entry mints a device session of its own.
import { HighWireCollect } from '@highwirepayments/payment-sdk/collect';
const hw = HighWireCollect({ publishableKey: 'hw_pk_live_…' });
const deviceData = await hw.collect();
const riskSessionKey = await hw.riskSessionKey();On a plain <script> page it is collect/<version>/highwire-collect.js on the CDN, pinned with its
SRI, which registers window.HighWireCollect. Its source is packages/highwire-js; its merchant
documentation starts at docs/collect/index.md.
Upgrading from 0.4
0.5.0 replaces the element API with hw.mount(). The changes that break an 0.4 integration:
| 0.4 | 0.5 |
|---|---|
| hw.elements().create('card' \| 'applePay' \| 'googlePay' \| 'walletButton' \| 'dropIn'), then .mount(target) | hw.mount({ container, amount, currency, … }). The checkout's session decides what is drawn. |
| getContext: () => ({ amount, currency, … }) on an element | amount and currency in the mount() options. |
| hw.createSession(order) → { paymentId } | mount() creates the payment: checkout.paymentId. |
| hw.submit(order) | checkout.submit(payer?). Amount and currency come from mount(). |
| idempotencyKey on createSession(), submit() and the element contexts | None: the SDK makes every key. chargeSavedMethod() still takes one. |
| cardholderEmail, cardholderPhone, cardholderBilling* | customerEmail, customerPhone, billingAddress: { line1, city, state, postalCode }, in submit(). |
| environment in HighWire.init() | Removed. apiBase names the gateway, and the key says sandbox (hw_pk_test_…) or production (hw_pk_live_…). A plain-JS page that still passes it keeps working. |
| displayItems | Removed. |
| Element events: on('ready' \| 'change' \| 'recovering' \| 'success' \| 'result' \| 'error' \| …) | onReady, onChange, onProcessing, onResult, onError. A card field that reloads blank reports an empty onChange. |
| submit() → { status, paymentId?, declinedReason?, … } | PaymentResult: paymentId always, retryable on every decline, no declinedReason. |
| A refusal at session creation (a merchant limit, a risk decision, a provider failure the gateway records as a decline): HW_SERVICE_UNAVAILABLE | mount() rejects HW_DECLINED and mounts nothing. |
| Types ElementsManager, FieldController, WalletButtonController, DropinController, FieldEventName, DropinEvent, FieldState, WalletKind, WalletButtonOptions, DropinOptions, WalletChargeContext, SubmitContext, AuthCaptureResult, CheckoutSession | Removed. The checkout's types are MountOptions, Checkout, PaymentResult, PaymentMethod, CardState, PayerDetails and BillingAddress. |
HighWire.init() takes the same options except environment, and hw.chargeSavedMethod() is
unchanged. The instance has only mount() and chargeSavedMethod(), and it is frozen: its members
cannot be reassigned or spied on.
Reference integration
Internal, for HighWire's developers. The reference merchant integration is
playground/highwire/checkout in the gateway repository (high-wire-gateway): one
provider-agnostic store page on the public API (HighWire.init,
hw.mount, checkout.submit and onResult), with a small server standing in for the merchant's
backend that binds the payment to the order and confirms it with Basic credentials. It runs against a
local gateway serving this workspace's packages/gateway-pages build, for an Airwallex and a Whop
merchant. Its README has the runbook, the sandbox test cards and a manual test matrix.
Setup & commands
Node 22 + pnpm 10.
pnpm install
pnpm build # SDK lib (dist/) + the collector (./collect, dist/highwire-collect.*)
pnpm build:collect # just the collector entry, from packages/highwire-js
pnpm test # vitest
pnpm typecheck # tsc --noEmit
pnpm lint
pnpm size # gzipped size of the SDK's ES and UMD files (budget < 50 KB) and the collector's UMD (< 3 KB)
pnpm check:package # the npm package is publishable: publint, arethetypeswrong, tarball
# contents, size budget, every entry point loads (scripts/check-package.mjs)CI (.github/workflows/ci.yml, on PRs to and pushes of main and staging) runs all of the
above; the release workflow runs the same gates again before publishing.
Releasing to npm
The package @highwirepayments/payment-sdk ships the loader and the collector; merchants load
the loader from the CDN (an npm install works too). The secure-field iframe the gateway serves
under /sdk/* is not in it: it is built in packages/gateway-pages
(@high-wire-payments/gateway-pages), with its own version, reported as HW_READY.iframeVersion,
and published to GitHub Packages for the gateway by the same script with --pages (tags pages-v*;
the workspace README, "Releasing").
The postMessage protocol major (HW_PROTOCOL_VERSION, in packages/sdk-protocol) is what keeps an
older loader working against a newer iframe. Within a major, the loader's greeting stays flat and says, with
hwNested, that it reads the nested envelope. A frame that does not know it answers flat, and the loader then
stays flat, so a newer loader also works against an older frame.
Releases are tag-driven and scripted. scripts/release.mjs does the mechanics; the agent skill
in .agents/skills/release/ (also /release in Claude Code, AGENTS.md for the rest) is the same
procedure with the stop-and-ask points spelled out.
node scripts/release.mjs status # where a release stands
node scripts/release.mjs prepare 0.2.0 --dry-run # or patch | minor | major | 0.2.0-rc.1
node scripts/release.mjs prepare 0.2.0 # bump both version strings, run every CI gate,
# open the release PR into staging (as highwire-dev)
node scripts/release.mjs merge # once CI + review are green: merge commit
node scripts/release.mjs tag # tag origin/staging, push, watch the publish, verify on npmWhat the tag triggers: .github/workflows/publish-npm.yml installs, lints, typechecks, tests,
builds, refuses a tag that differs from package.json, runs pnpm check:package (see below),
then publishes with npm publish --access public through npm
trusted publishing (OIDC — no token exists, in the repo or anywhere else). A prerelease version
(1.2.0-rc.1) is published under the next dist-tag, so the gateway can pin it without it
becoming latest. A stable version takes latest only if it is higher than every stable version
already published; otherwise npm refuses the publish, so a backport has to be published
deliberately, by hand, with an explicit --tag. The job runs in the npm GitHub environment: add
required reviewers to it (Settings → Environments) and every release waits for an approval first.
The two version strings — version in package.json and SDK_VERSION in src/config.ts — move
together; prepare edits both and check:package refuses a build where they differ.
One-time setup, already done: the npm scope is @highwirepayments — the npm organisation of that
name, no hyphens — while the GitHub organisation is High-Wire-Payments. The trusted publisher on
npmjs.com (package settings → Trusted publisher → GitHub Actions) is High-Wire-Payments/highwire-sdk,
workflow publish-npm.yml, environment npm; trusted publishing also checks that repository.url
in package.json matches that repository exactly. If the package ever has to be recreated, the
first version must be published by hand (npm publish --access public, 2FA required;
prepublishOnly builds and validates) before a trusted publisher can be attached to it.
What ships, and what does not. Both loader files (dist/highwire-payment-sdk.es.js,
dist/highwire-payment-sdk.umd.cjs) and the collector are minified with terser (vite.minify.ts,
whose options packages/gateway-pages copies for the iframe; /* @__PURE__ */ annotations kept so a
merchant's bundler can still tree-shake the ES build) with no comment left but the
/*! @highwirepayments/payment-sdk vX.Y.Z … */ banner on line 1 of each loader file; the UMD
file's banner also names the packages it bundles, with their versions and licenses. Source
maps are built (dist/**/*.map, for a private error-tracking upload) but never published — they
embed the full original source — and the built files carry no sourceMappingURL, so nothing goes
looking for them. The tarball holds dist/ (maps excluded, and never the gateway's pages:
dist/iframe or dist/checkout), package.json, README.md and CHANGELOG.md, and
"sideEffects": false lets bundlers drop whatever a merchant does not import. pnpm check:package
enforces all of this, plus publint, arethetypeswrong (the require entry has its own
index.d.cts, so TypeScript's node16 resolution is happy from CommonJS too), the 50 KB gz
budget on each loader file, the Airwallex loader bundled in the UMD file and external in the ES
file, and a smoke load of each entry point — including the UMD file as a classic <script> in a
page-like context, which must define window.HighWire and nothing else and append nothing to the
document.
Releases carry no npm provenance: npm only accepts provenance from public source
repositories, and this one is private. If it becomes public, add --provenance back to the
workflow's publish step.
@airwallex/components-sdk is an optional peer dependency of the ES build, which
dynamic-imports it the first time an Airwallex checkout draws Google Pay. The import names the
package literally, so a merchant's bundler resolves it at build time whatever the provider: a
merchant who bundles the ES build installs the package, even on Whop, where it is never loaded. The
UMD build (require, the CDN) carries its own copy of that loader, evaluated only when a checkout
first draws a wallet. Either way the wallet components run on the merchant's page, not inside a
HighWire iframe.
