OK – After way too much research and conversations with Stripe Support, I’ve realized that the best way to implement Stripe through Wix Code, is the use of a HTML component. I have the HTML code SO CLOSE to working, but I cannot for the life of me get it to pass back the data from the HTML component to the page code.
Can anyone tell me why it is not working? Take my word that all of the code in this works perfectly until the very end. Even console.log(token) returns the token I need. However, the very last line of code, “window.parent.postMessage(token, “*”);” does not return the token to the Page Code. I’m stuck. How am I supposed to get the token to the page code?
<script src="https://js.stripe.com/v3/"></script>
<form action="/charge" method="post" id="payment-form">
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element">
</div>
<!-- Used to display form errors -->
<div id="card-errors" role="alert"></div>
</div>
<button>Submit Payment</button>
</form>
<script>
var stripe = Stripe('pk_test_RXbN0BPqSqZlFpivAgvoQZYd');
// Create an instance of Elements
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
const style = {
base: {
// Add your base input styles here. For example:
fontSize: '16px',
color: "#32325d",
},
};
// Create an instance of the card Element
const card = elements.create('card', {style});
// Add an instance of the card Element into the `card-element` <div>
card.mount('#card-element');
card.addEventListener('change', ({error}) => {
const displayError = document.getElementById('card-errors');
if (error) {
displayError.textContent = error.message;
} else {
displayError.textContent = '';
}
});
// Create a token or display an error when the form is submitted.
const form = document.getElementById('payment-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const {token, error} = await stripe.createToken(card);
if (error) {
// Inform the customer that there was an error
const errorElement = document.getElementById('card-errors');
errorElement.textContent = error.message;
} else {
// Send the token to your server
stripeTokenHandler(token);
}
});
const stripeTokenHandler = (token) => {
// Insert the token ID into the form so it gets submitted to the server
const form = document.getElementById('payment-form');
const hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
console.log(token)
window.parent.postMessage(token, "*");
}
</script>