HTMLComponent - Stripe

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>

Hi David,

Requires a bit of reading and understanding (but much less than you’ve already done)… have a look here to get the general idea of how pass and retrieve information from HTML using Wix Code.

Liran.

avid, are you sure you are waiting on a postmessage from the HTML-component using. onMessage event in your main program (on the client side, Wix code)?

Hmmm – Yes, I’ve read through the article Liran and still am unsuccessful. Giri, my page code is simple just for testing purposes. The log returns the test, but nothing in regards to the HTML message, see below:

//Page Code
export function button2_click(event) {
	$w("#html2").onMessage( (event) => {
    $w("#text134").text = event.data;
    console.log(event.data);
        
  } );
  console.log("Test");
}

Hi David,

Your code seems to be in an ‘onClick’ event… so this means that you set the ‘onMessage’ callback function for your HTML component only when the button is clicked.
This callback function is the one to be called when the HTML component sends a message to the parent window (when you call stripeTokenHandler from your HTML component).
So first of all, I would move the code that sets ‘onMessage’ to ‘$w.onReady’ code (so then callback function is set as soon as the page is loaded).
Still, you might have some issues if the HTML component code fires the message back to the parent before the page is fully loaded and the ‘onMessage’ function is set.
Having said that, seems like you only send the message upon form submission, so this might be enough.

Let me know how it goes,
Liran.

This worked! I had to fiddle with the code a bit, including converting the token, using JSON.stringify, before sending it back to the page code. I am communicating with the Stripe Support team as well. I am going to put in some more research into this then try and create a forum post that encompasses all of this Stripe/Wix Code stuff I’ve gathered.

David, that post would be highly appreciated, I believe. Maybe then I can use it as a starting point for the thorn in my shoe, MercadoPago (a South American PayPal).

Definitely, I’ll try to post it today or tomorrow. There are just a lot of moving puzzle pieces and content that I’d like to include, between PCI Compliance, the iFrames, back-end charges, etc. Making progress tho. Stay tuned!

Giri – I create a new forum post “Stripe - Wix Code”. Definite work in progress, but the code does successfully make charges and should be a good starting point.

I searched for the “Stripe - Wix Code” Forum and couldn’t find it.

Tanzi, I think this will help you navigate the forums better these days. Hope the text is readable.