Hosted payment page iframe integration
Embed the Hosted Payment Page in an iframe and communicate over the postMessage lifecycle protocol.
The Hosted Payment Page (HPP) supports two embedding modes: redirect mode (you navigate the cardholder to the HPP address) and iframe mode (you embed the HPP inside a parent page and communicate over the postMessage lifecycle protocol). This guide covers iframe mode: authorizing a parent origin, the lifecycle event protocol, the command channel, and the security model.
Two pieces of configuration
Iframe embedding requires two independent settings to line up:
- Page-level
AllowedEmbeddingDomains: a list of domains (max 20) authorized to embed a given HPP. Wildcards such as*.example.comare supported. Raw IP addresses,localhost, and entries without a TLD are rejected. This is the security envelope: a page without your origin in its allow list can't be framed by your site. - Per-session
parentOrigin: set when creating each session. It must be a valid HTTPS origin whose host matches anAllowedEmbeddingDomainsentry. If it's omitted, the session is still valid for non-embedded use, but the postMessage channel is disabled fail-closed (no events flow to a parent).
If the host doesn't match, session creation returns 400 with HostedPaymentPage:HppSession:ParentOriginNotAllowed.
The postMessage lifecycle protocol
Once a session has a parentOrigin, the embedded HPP emits a stream of postMessage events to the parent throughout the session lifecycle. Every event shares one envelope shape; the data payload varies by type. Filter on the source discriminator (winkpg-hpp).
A successful payment fires events in this order:
session_loaded -> ready -> payment_started -> payment_succeeded -> navigated(to: 'result')
Subscribe to ready (not session_loaded) when you need the iframe to be visually interactive: ready fires once the form root has mounted in the DOM.
Loading the frame before the payer reaches payment
The frame takes a few seconds to reach ready, and longer on a slow or distant connection. Most of that time is the browser connecting to WinkPG, so you can hide it: create the session and mount the frame, hidden, as soon as your checkout screen opens, and show it when the payer reaches the payment step.
- When the checkout screen opens, create the session on your server and mount the frame inside a container you've hidden, for example with
display: none. Don't setloading="lazy"on an iframe you build yourself: a browser doesn't load a hidden lazy frame until it's shown. - When the payer reaches the payment step, show the container. If
readyhasn't arrived yet, show your own placeholder until it does. - Handle
session_invalid, so a link that can't be paid doesn't leave the payer waiting on a frame that never appears.
A hidden frame measures no height, so its first height_changed arrives only after you show it. Give the container a height, or set initialHeight with the embedded payments SDK, so your page doesn't jump when the fields appear.
The session's lifetime starts when you create it, not when the payer reaches the frame. A checkout session lasts 10 minutes by default. If your checkout screen usually takes longer, set expirySeconds on the create call, up to 900 (15 minutes); your account's session settings can lower that limit. session_loaded carries expiresAtUtc, and the frame sends session_expired when that time passes. If the payer hasn't reached the payment step by then, create a new session and mount a new frame in place of the old one.
Key events include payment_succeeded, payment_failed, payment_pending, height_changed (for automatic resizing), validation_failed, session_expired, session_invalid, and the save-only pair card_saved (a card was vaulted) and ach_saved (a bank account was vaulted). If no event arrives within a few seconds, fall back to a timeout and treat it like session_invalid: a session that never existed has no parentOrigin to address, so it's intentionally silent.
If your page accepts bank accounts on a save-only session, handle ach_saved. A bank-account save used to arrive as card_saved with the card fields empty; it now arrives as ach_saved with the bank account's last four and account type. A page that listens only for card_saved is no longer told about an ACH save. Card saves are unchanged.
card_saved carries the card's BIN classification beside the last four and the brand: bin (the leading digits), funding (Credit, Debit, Prepaid, or Charge), and panLength. Use them to apply your own funding-type rules at save time instead of making a second server call to read the token back. All three are null when the card's range didn't resolve, so branch on the value rather than on the key. The card's expiration date is never on this envelope. If you need it, read it on your server, from the stored payment method with POST /api/tokens/resolve-payment-token-async or from the HostedPaymentPage.CardSaved webhook. Both reach only the merchant that owns the card; see "Reading the expiration date" under Showing only the card fields.
What payment_started tells you
payment_started fires when the customer submits, after the page's own field validation and before the payment is created. Its payload carries paymentMethod (card or bank_account), saveRequested (true when the customer asked for the payment method to be stored) and storedCredential (true when the customer paid with a card already saved on their customer record, picked from the page's saved-card list). Every key is always present.
saveRequested is the effective answer rather than the raw checkbox state: a page that never offered the save option reports false, and a save-only session reports true. Treat the paymentMethod value set as open, and handle a value you don't recognize rather than failing on it.
The values are fixed at submit. They describe the submission now in flight, and nothing re-sends this event, so a customer who changes the checkbox or switches tabs afterward doesn't change what you were told. That lets you record the rail and the save intent straight away instead of holding your record open until the completion webhook arrives.
Digital wallets don't fire this event. Apple Pay, Google Pay, and Paze complete through the wallet sheet rather than the page's own submit, so a wallet payment goes straight to its terminal event. Don't wait on payment_started to move a wallet flow forward: handle payment_succeeded, payment_failed, and payment_pending for those.
What the parent receives on a payment
Payment payloads are restricted to fields the public session endpoint already exposes. No PAN, CVV, expiration, network token, wallet cryptogram, or PII is ever included. A successful payment carries the transaction id, requested and approved amounts (compare them to detect a partial approval), masked last4 and brand, the auth code, and the result status. Token fields (paymentTokenPublicReference, customerId, schemeTransactionId) are present only when the cardholder saved a card; key any card-on-file workflow off the presence of paymentTokenPublicReference.
Locking the amount
A session decides who sets the amount the customer pays. Three choices are available. Customer-entered puts the customer in control: they type the figure themselves, which suits an open balance or an ad-hoc payment. Suggested pre-fills a figure the customer can still change, which suits a suggested donation or a recommended top-up. Locked fixes the figure so the customer can't change it, which suits an invoice or a known order total.
On a locked session, the read-only field is the visible part of the guarantee, not the whole of it. The amount set when the session is created is held with the session on WinkPG's servers, and every submitted payment is checked against it before anything is authorized. A submission whose amount doesn't match the locked value is rejected. Editing the page in a browser, replaying the request with a different figure, and calling the submit endpoint directly all reach the same outcome: the customer pays the amount you set, or nothing is charged. The check doesn't depend on how the customer pays, so card entry and digital wallets such as Apple Pay and Google Pay are all covered.
A locked session fixes the whole payable total, including any tax, shipping, or convenience fee supplied with the session. The clearest setup is a single figure: fold tax and shipping into the locked amount and send one total. The page then shows the customer exactly what will be charged, and one number reconciles against the payment afterward.
Offering the customer's stored cards
On a session bound to a customer, the vault_restriction session directive lets the customer pay with a card already saved on their customer record. Like allowed_payment_methods, it travels as a prefilledFields entry rather than as a field of its own, and you bind the customer by sending customerId on the same session-create call:
POST /api/hostedpaymentpages/sessions
{
"hostedPageId": "...",
"customerId": "a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"prefilledFields": { "vault_restriction": "saved_only" }
}
vault_restriction |
What the customer sees |
|---|---|
omitted, or any |
The new-card form, with no stored cards. This is the default. |
allow_new_and_saved |
The customer's stored cards, listed beside the new-card form. When no stored card qualifies, the page is the plain new-card form. |
saved_only |
Only the customer's stored cards, with no new-card form, no bank account, and no digital wallet. When no stored card qualifies, the customer sees a message that the link can't be paid, and the page offers no way to submit. |
The value isn't case-sensitive. Any other value, an empty one included, is refused at session create with HostedPaymentPage:HppSession:FieldValueInvalid, so omit the key rather than sending it empty.
- Bind
customerId. The stored cards come from the bound customer only; the cardholder email is never used to find them. On an unbound session there are no cards to offer, soallow_new_and_savedshows the plain new-card form andsaved_onlyshows the empty state. - Only cards with a vault token qualify. A saved bank account, a card saved from a digital wallet, and a card saved from a card reader as a reader token aren't offered. The default card is listed first, and each card shows its brand, last four digits, and the name the customer gave it.
- A picked card always asks for its security code, and the page's card acceptance, surcharge, and convenience fee rules apply to it as they do to a typed card.
- Some sessions never offer stored cards: a save-card session, a CVV-only session, and a session whose
allowed_payment_methodsleaves outcard. Don't sendsaved_onlywith any of them.
The server enforces saved_only from the directive stored with the session, never from the payment request. Anything other than one of the bound customer's qualifying stored cards is refused with Transactions:HppSavedOnlyNewInstrumentRefused before anything is charged; it arrives on payment_failed with reason business_exception and that code. A payment made with a picked card fires payment_started with storedCredential: true. A picked card that can no longer be used fails with reason saved_card_unavailable: nothing was charged, and the customer can pick again.
Two-way command channel
The parent can send a small, allowlisted set of commands back into the iframe: cancel, set_locale, prefill, request_height, and submit. Inbound commands carry a distinct discriminator (winkpg-hpp-cmd) so an outbound envelope can't be replayed back into the iframe as a command. submit does nothing unless the session was created with submitControl set to Parent (see the next section), so on every other session payment authorization stays a customer action inside the frame.
Using your own pay button
By default the hosted payment page has its own pay button inside the frame. To put the pay button on your page instead, for example beside your order summary, create the session with submitControl set to Parent:
POST /api/hostedpaymentpages/sessions
{
"hostedPageId": "...",
"parentOrigin": "https://shop.example.com",
"submitControl": "Parent",
"presentationMode": "Embedded"
}
The frame then hides its own pay button, and your page starts the payment by sending the submit command. With the embedded payments SDK, call submit() on the frame handle.
- The frame runs what its own pay button runs. Field validation, the bot check, card issuer verification (3-D Secure), and the consent prompt all happen inside the frame, and you receive the usual events:
payment_started, thenpayment_succeededorpayment_failed. - The command carries nothing. The frame charges what its own form holds. No command sends card data in, and none reads it out.
- A refusal names your command. When a field is missing or invalid, the frame shows the errors to the customer and sends
validation_failedwithcommand: "submit"in its payload, so you can tell it answers your button rather than the customer's own submit. - One payment at a time. A
submitthat arrives while a payment is running, or after a result is showing, is dropped. It isn't queued, and no event answers it. parentOriginis required. The command is accepted only from that origin. A request that sendsParentwithout one is rejected with400. A native app useshostChannelset toNativeWebViewinstead; see the next section.- On every other session the command does nothing. A session created without
submitControl, or withFrame, keeps its own pay button and ignoressubmit. - Digital wallet buttons stay in the frame, and pressing Enter in a field still submits the form.
- Any script on your page can send it. The frame can't see where the command came from, so on a
Parentsession it can't tell your pay button from other code running on your page. ChooseParentknowing that, and keep the scripts on your checkout page under control.
Showing every outcome on your page
With submitControl set to Parent, the frame still shows its own message for each outcome: a dialog for missing information, a dialog for a failed payment or save, and a result panel that replaces the form after a success. To decide what the customer sees yourself, also set outcomeDisplay to Parent:
POST /api/hostedpaymentpages/sessions
{
"hostedPageId": "...",
"parentOrigin": "https://shop.example.com",
"submitControl": "Parent",
"outcomeDisplay": "Parent",
"presentationMode": "Embedded"
}
The frame then shows no outcome dialog and no result panel. Each outcome reaches your page only as the event the frame already sends:
| Outcome | What the frame shows | The event you receive |
|---|---|---|
| A field is missing or invalid | The inline error under each field, and no dialog | validation_failed |
| The bot check refuses the submit | The challenge stays in the frame, and no dialog | payment_failed with reason: "captcha_failed" |
| The payment or save fails | No dialog. The form stays editable with every value as entered | payment_failed with its code |
| The payment or save succeeds | No result panel. The form stays on the page, locked, with the security code cleared | payment_succeeded, payment_pending, card_saved or ach_saved |
- Your page is the only place the customer learns the outcome. A page that ignores
payment_failedleaves the customer with no answer. Confirm the payment from the webhook, which stays the authoritative record. - After a failure, the customer can try again. Nothing is cleared, so you can send
submitagain once they've corrected the card. Whether the link accepts another attempt is unchanged. - Some things stay in the frame. The stored-credential consent checkbox, the page disclosure, the 3-D Secure challenge and the digital wallet sheets are part of the payment itself.
outcomeDisplay: "Parent"requiressubmitControl: "Parent". Any other combination is rejected with400andHostedPaymentPage:HppSession:OutcomeDisplayRequiresParentSubmit. The value is fixed when the session is created, andeffective.outcomeDisplayreports it. It works the same on a native app session.
Showing only the card fields
To save a card through a frame that looks like three inputs inside your own form, create the session with formDisplay set to CardFieldsOnly:
POST /api/hostedpaymentpages/sessions
{
"hostedPageId": "...",
"saveCardOnly": true,
"customerId": "...",
"parentOrigin": "https://shop.example.com",
"submitControl": "Parent",
"formDisplay": "CardFieldsOnly"
}
The frame renders the card number, the expiry and the CVV, with their inline errors, on a transparent background with no outer padding, border or shadow. The session theme still styles the inputs, so you can match them to your own fields.
- What still shows, when the session needs it: the terms of service checkbox with its link (when the page requires terms acceptance), the stored-credential consent checkbox, the page disclosure and its acceptance checkbox, the bot protection widget and the 3-D Secure window. A required checkbox left unticked blocks the save with an inline error and
validation_failed. - What doesn't: the email, name on card (unless the session asks for it with
nameOnCard), address, wallet buttons, order summary, pay button, back link, card logos and page header. - No Test Mode banner. The frame sits inside your form, so it doesn't show the banner a test merchant's full form shows.
session_loadedcarriesisTestMode, so your page can show its own. - The flow is unchanged. Your page sends
submit, and the frame answers withvalidation_failed,card_savedorpayment_failed.
CardFieldsOnly is available only on an embedded card save on a Streamlined page, with submitControl set to Parent, a customerId, or guestSave: true with saveWithoutVerification: true (because the frame can't ask for an email), and nothing that requires an email or billing address. Anything else is rejected with 400 and HostedPaymentPage:HppSession:CardFieldsOnlyNotAvailable, and the error's reason names the requirement that wasn't met. effective.formDisplay reports the value.
Asking for the name on card
To have the frame collect the cardholder name too, add nameOnCard to the same session create. Hidden (the default when you omit it) shows no name input. Optional shows the name input above the card number and lets a blank name save. Required shows it and blocks the save until the payer types a name, with an inline error and validation_failed. The input takes the card fields' theme styling and accepts at most 25 characters.
The card_saved event doesn't carry the name. Your server reads the trimmed name from the stored payment method with POST /api/tokens/resolve-payment-token-async for the paymentTokenPublicReference that card_saved gives you, at paymentDetails.cardData.nameOnCard.
nameOnCard applies only to formDisplay: "CardFieldsOnly". On any other form display, Optional or Required is rejected with 400 and HostedPaymentPage:HppSession:NameOnCardRequiresCardFieldsOnly. effective.nameOnCard reports the value.
Masking the security code
To show a dot for each digit of the security code instead of the digits, add cvvDisplay: "Masked" to the same session create. Plain (the default when you omit it) shows the digits. Masking changes how the digits look and nothing else: the field stays a numeric text field, so the browser's saved-card autofill still fills it, and the code is checked and sent as before. The dots are drawn in Chrome, Edge, Safari on macOS and iOS, and Firefox 114 and later; an older Firefox shows the digits.
cvvDisplay applies only to formDisplay: "CardFieldsOnly". On any other form display, Masked is rejected with 400 and HostedPaymentPage:HppSession:CvvDisplayRequiresCardFieldsOnly. effective.cvvDisplay reports the value.
Reading the expiration date
The payer types the expiration date inside the frame, so your page never sees it, and the card_saved event doesn't carry it. Read it on your server. This matters most on a session opened with saveWithoutVerification, where your own server sends the expiration date to your gateway.
- The stored payment method is the source to read when
card_savedarrives. CallPOST /api/tokens/resolve-payment-token-asyncfor thepaymentTokenPublicReferencethatcard_savedgives you, the same call that returns the name on card. The date is atpaymentDetails.cardData.expirationMonthandpaymentDetails.cardData.expirationYear, with the card number masked. The save finishes on the server before the frame sendscard_saved, so the read already returns the date the payer just typed, for a new card and for a card the merchant already holds. - The
HostedPaymentPage.CardSavedwebhook is the record. It carries the same date asExpirationMonthandExpirationYear. The webhook and thecard_savedevent can arrive in either order, so don't wait for one before handling the other.
Make the read with an API key that has the tokens capability scope, whose owner can view stored payment methods (PaymentTokens.View). A key scoped only to taking payments, or only to vault:outbound, can't make it.
When a save with no WinkPG processor matches a card the merchant already holds, it writes the new date onto that card. If that write fails, the save still completes: the webhook carries the date the payer typed, and the stored payment method keeps the date it had before. Treat the expiration date as cardholder data: keep it out of your logs, and don't send it back to a browser.
Card fields inside your form
To make the frame read as three inputs in your own checkout form, add these theme members to the session create. Every one is optional, and every other form display ignores them:
theme member |
Range | What it sets |
|---|---|---|
inputFieldHeight |
28 to 72 | Height of each input, in pixels. |
inputFieldBorderWidth |
0 to 4 | Border width, in pixels. At 0 a focused input still shows a focus ring. |
inputFieldBorderRadius |
0 to 24 | Corner radius, in pixels. |
inputFieldPaddingX |
0 to 32 | Space inside each input on the left and right, in pixels. |
inputFieldBorderFocusColor |
A hex color, such as #1a73e8 |
Border color of the focused input. |
fieldGap |
0 to 32 | Space between the inputs, in pixels. Setting it, even to 0, draws three separate inputs; without it the three share one bordered block. |
"theme": {
"inputFieldHeight": 44,
"inputFieldBorderWidth": 1,
"inputFieldBorderRadius": 8,
"inputFieldPaddingX": 12,
"inputFieldBorderColor": "#d0d5dd",
"inputFieldBorderFocusColor": "#1a73e8",
"fieldGap": 12
}
inputFieldFontColor, inputFieldFontSize and inputFieldBackgroundFocusColor style the card fields too. A value outside its range is rejected with 400, and the error names the member, for example Theme.InputFieldHeight.
On your page:
- Show your own test badge. Read
isTestModefrom thesession_loadedpayload and, when it'strue, show a badge beside the fields. - Size the frame from the first height. When the form already has a height, the frame sends one
height_changedbeforeready, so set the iframe's height from it and the fields don't jump when they appear. A hidden or collapsed frame measures no height yet and sends its first one afterready. With the embedded payments SDK,initialHeightsets the height before that first event, and the default floor of320pixels doesn't apply to a card-fields-only session unless you setminHeight.
Hosting in a native app
A native iOS, Android, or Flutter app has no parent page to embed the payment page into. It loads the page in a WebView, which is a top-level document: no parent window, no parent origin, and nothing for the lifecycle events to be posted to. Set hostChannel to NativeWebView when creating the session, and the page delivers the same events to a message handler your app installs instead.
Send no parentOrigin with it. The pair is contradictory, so the request is rejected rather than ignored. You also don't need to send presentationMode: a native session renders the chrome-free surface by default, because the standalone page's full-height layout fights the automatic resizing your app does from the height events.
Your app installs one handler named hppHost. On iOS that's a WKScriptMessageHandler added to the WebView's user content controller, which receives a dictionary. On Android it's addJavascriptInterface with a postMessage(String) method carrying the @JavascriptInterface annotation, which receives a JSON string. Flutter's JavaScript channel gives you the string shape on both platforms. On Flutter for iOS both spellings resolve to the same handler underneath, so the page detects that and delivers each event exactly once: don't install both.
A page configured for Apple Pay or Google Pay still renders those buttons inside a WebView, where the wallet sheet has constraints your app has to satisfy on its own. Restrict the tenders with the allowed_payment_methods session directive until you've done that work: it travels as a prefilledFields entry carrying a comma-separated list of method keys, not as a field of its own, and it can only narrow what the page already offers.
Event names, payloads, and the sensitive-field boundary are identical to the browser channel, so an app can reuse whatever parsing a parent page already had. Three commands are available back into the page, cancel, request_height, and submit, sent by calling the global hppHostCommand function with the command envelope as a JSON string. submit works only when your app draws its own pay button: create the session with submitControl set to Parent as well as hostChannel, and send no parentOrigin. Any other native session ignores it. prefill and set_locale aren't offered on this channel. A successful cancel produces a cancelled event whose initiatedBy is "parent", the same value a parent page sees.
The security model changes shape. In a browser the protection is the origin check; a WebView has no origins to compare, so the handler your app installs is the trust boundary. Load only session addresses your own server produced, and don't install the handler on a WebView that can navigate elsewhere. The page's AllowedEmbeddingDomains list and the frame policy that enforces it don't apply, because a WebView load isn't framing. Events carry the session's short token, which is a bearer credential, so never log a whole event: log the type and the transaction id if you need a trail. A page with bot protection enabled runs its challenge inside the WebView, so exercise one while you're still testing in the sandbox.
Security model
A receiver written against the raw addEventListener('message', ...) API must do all three checks before trusting an event:
window.addEventListener('message', (event) => {
if (event.origin !== 'https://hpp.winkpg.com') return; // (1) origin
const msg = event.data;
if (!msg || msg.source !== 'winkpg-hpp') return; // (2) source discriminator
if (msg.sessionId !== mySessionId) return; // (3) session scope
// handle msg.type
});
Skipping any one of these weakens the model. Prefer the client helper library, which performs these checks and exposes typed on(...) and send(...) APIs.
Quick-start checklist
- Confirm the HPP page has the embedding feature enabled and add your origin to
AllowedEmbeddingDomains. - Set
parentOriginto your exact origin on each session create. - Embed the iframe using the session response address and serve the parent over HTTPS.
- Register handlers for at least
ready,payment_succeeded,payment_failed,session_invalid, andheight_changed. - Implement a "no event within N seconds" timeout fallback.
- Create the session and mount the frame hidden when your checkout screen opens, then show it at the payment step. See Loading the frame before the payer reaches payment.
- Hosting in a native app instead of a browser page? Set
hostChanneltoNativeWebView, omitparentOrigin, and install thehppHosthandler.
See also
- The embedded payments SDK: the supported browser loader over this protocol, which performs the origin, source, and session checks above and exposes the lifecycle as callbacks.
- Setting up a hosted payment page: choose a page mode, walk the creation wizard, and configure page options before you get to embedding it.