Appearance
Tokenize Card Data
Once the iframe is embedded and the user has entered their card information, you can securely request tokenization using the postMessage API.
Overview
Create a postMessage to initialize card tokenization securely inside the iframe. This triggers the hosted payment form to tokenize the card data without your application ever handling the sensitive information directly.
Implementation
js
function tokenizeCard() {
iframe.contentWindow.postMessage({ type: "tokenize" }, "*");
}When to Call
Typically, you'll call the tokenizeCard() function in response to a user action, such as:
- Clicking a "Submit Payment" button
- Clicking a "Complete Order" button
- Any other trigger in your checkout flow
Example Button Handler
js
document.getElementById("submit-payment-btn").addEventListener("click", function () {
// Trigger tokenization when user submits
tokenizeCard();
});Security Considerations
IMPORTANT
It is important to check the origin of a postMessage in JavaScript to prevent security vulnerabilities such as cross-site scripting (XSS) and unauthorized data access.
Preventing Cross-Origin Attacks
The postMessage API allows cross-origin communication, meaning any window can send messages to another, regardless of their origins. If the receiver does not check the sender's origin using the event.origin property, malicious sites can send crafted messages to trick the receiving site into performing unintended actions, possibly leaking sensitive data or enabling other attacks.
Additional Info: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
Best Practices
- Origin Validation: Always validate the origin of postMessage events (covered in the next step)
- User Feedback: Show a loading state or disable the submit button after calling
tokenizeCard() - Error Handling: Be prepared to handle both success and error responses from the iframe
- Single Submission: Prevent multiple tokenization requests by disabling the submit button after the first click
Next Step
After requesting tokenization, you need to listen for the response from the hosted payment form.
