What steps do I need to take to transition from using Stripe Checkout.js to implementing Stripe Elements?

I am working on creating a personalized checkout form using custom elements and incorporating my ajax function that utilizes StripeCheckout.configure to handle the payment processing. My goal is to develop a highly adaptable checkout form. I have discovered a method to achieve this through elements with the following setup:

<script src="https://js.stripe.com/v3/"></script>
<body>
  <form action="//httpbin.org/post" method="POST">
    <input type="hidden" name="token" />
    <div class="group">
      <label>
        <span>Card number</span>
        <div id="card-number-element" class="field"></div>
      </label>
      <label>
        <span>Expiry date</span>
        <div id="card-expiry-element" class="field"></div>
      </label>
      <label>
        <span>CVC</span>
        <div id="card-cvc-element" class="field"></div>
      </label>
      <label>
        <span>Postal code</span>
        <input id="postal-code" name="postal_code" class="field" placeholder="Regular field placeholder" />
      </label>
    </div>
    <button type="submit">Pay $25</button>
    <div class="outcome">
      <div class="error"></div>
      <div class="success">
        Success! Your Stripe token is <span class="token"></span>
      </div>
    </div>
  </form>
  <script>
    var stripe = Stripe('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
var elements = stripe.elements();

var style = {
  base: {
    iconColor: '#666EE8',
    color: '#31325F',
    lineHeight: '40px',
    fontWeight: 300,
    fontFamily: 'Helvetica Neue',
    fontSize: '15px',

    '::placeholder': {
      color: '#CFD7E0',
    },
  },
};

var cardNumberElement = elements.create('cardNumber', {
  style: style,
  placeholder: 'Custom card number placeholder',
});
cardNumberElement.mount('#card-number-element');

var cardExpiryElement = elements.create('cardExpiry', {
  style: style,
  placeholder: 'Custom expiry date placeholder',
});
cardExpiryElement.mount('#card-expiry-element');

var cardCvcElement = elements.create('cardCvc', {
  style: style,
  placeholder: 'Custom CVC placeholder',
});
cardCvcElement.mount('#card-cvc-element');


function setOutcome(result) {
  var successElement = document.querySelector('.success');
  var errorElement = document.querySelector('.error');
  successElement.classList.remove('visible');
  errorElement.classList.remove('visible');

  if (result.token) {
    // In this example, we're simply displaying the token
    successElement.querySelector('.token').textContent = result.token.id;
    successElement.classList.add('visible');

    // In a real integration, you'd submit the form with the token to your backend server
    var form = document.querySelector('form');
    form.querySelector('input[name="token"]').setAttribute('value', result.token.id);
    form.submit();
  } else if (result.error) {
    errorElement.textContent = result.error.message;
    errorElement.classList.add('visible');
  }
}

cardNumberElement.on('change', function(event) {
  setOutcome(event);
});

document.querySelector('form').addEventListener('submit', function(e) {
  e.preventDefault();
  var options = {
    address_zip: document.getElementById('postal-code').value,
  };
  stripe.createToken(cardNumberElement, options).then(setOutcome);
});

  </script>
</body>

I aim to incorporate an ajax-stripe combination without relying solely on elements but utilizing versions that are element-based.

<form action="{% url 'payments' %}" method="post">
  {% csrf_token %}
  <script src="https://checkout.stripe.com/checkout.js"></script>
  <script>
        CSRF_TOKEN = document.getElementsByName("csrfmiddlewaretoken")[0].value;
        var handler = StripeCheckout.configure({
        key: '{{ key }}',
        locale: 'auto',
        token: function(token) {
          $('.notification-success-wrapper').css('display', 'none');
          $('.notification-danger-wrapper').css('display', 'none');
          $.ajax({
            url: "{% url 'payments' %}",
            method: 'POST',
            data: JSON.stringify({
              token: token.id,
              amount: {{ amount }},
              description: "{{ description }}",
            }),
            headers: {'X-CSRFToken': CSRF_TOKEN},
          })
          .done((res) => {
            console.log(res)
          })
          .fail((err) => {
            console.log(err)
          });
        },
        allowRememberMe: false
      });
      document.getElementById('purchase-btn').addEventListener('click', function(e) {
        // Open Checkout with further options:
        handler.open({
          name: "demoo",
          description: "{{ description }}",
          amount: {{ amount }}
        });
        e.preventDefault();
      });
      // Close Checkout on page navigation:
      window.addEventListener('popstate', function() {
        handler.close();
      });
  </script>
</form>

Answer №1

Make sure to include the AJAX call within your setOutcome function in addition to the legacy Checkout token callback. This will allow you to properly handle and modify the result.token as needed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS blank drop-down selection

I am currently working on an AngularJS select element with ng-options using the code below: <select ng-model="vm.selectedship" ng-change="vm.updateShip()" data-ng-options="ship as ('ship' + ' is ready (' + ship.currentlocation + & ...

The occurrence of an unanticipated character '#' was found

I'm currently facing an issue while using webpack to load dependencies. Whenever I execute the npm run dev command, I encounter the following error: Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: ...

When a string begins with the "<" character, jQuery regex is unable to find a match

I am attempting to check if a string starts with the "<" character, but I am running into issues. The expression works perfectly fine on regex101.com, however, it fails when used in my personal files. When I input a backslash everything works as expect ...

"Unlock the Power of VueJS 2 with Dynamic Templates

Just starting out as a VueJS student! I created a "MainTemplate.vue", which includes a menu, footer, header... Then I decided to create another .vue file named "ComponentB.vue". Here is the content of my ComponentB.vue file: <template> <h ...

What would be the best way to structure this workflow as a JavaScript data format?

I have a complex workflow that I need to represent as a JavaScript data structure. This workflow involves a series of questions and answers where the response to one question determines the next one asked. Here is a basic example of what this workflow migh ...

Ensure all <li> tags within a HTML document exhibit consistent jquery mousedown and hover effects, abstaining from the assignment of unique IDs to each

I understand that this approach might not be correct, but I wanted to create a simulation of what I am trying to achieve. Is there a way for each <li> element within a specific <ul class="myul"> to have separate mousedown, mouseout, hover effe ...

Is Ajax capable of producing multiple outputs at once?

I am looking to retrieve data from a product.json file that contains two objects: (1) object for CCTV camera products (2) object for Laptop products. When a specific button is clicked, I want to access the data for LAPTOP products and the same for CCTV. ...

What is the importance of using a polyfill in Babel instead of automatically transpiling certain methods?

Recently, I have been diving into a course that delves into the use of babel in JavaScript. It was explained to me that babel, with the preset "env," is able to transpile newer versions of ES into ES5. However, I found myself facing a situation where the a ...

Explore the properties within an array of objects through iteration

Here is the array I'm working with: const myArray = [{ id: 1, isSet: true }, { id: 2, isSet: false }, ...]; I only need to iterate over the isSet properties of the objects, ignoring all other properties. Initially, I attempted the following solution ...

Create a dynamic HTML page using JavaScript

When I click on the following links: How can I create a new page using JavaScript? Create and dynamically append elements I'm looking to dynamically add HTML elements with JavaScript within a div, but I don't want my code to become overly comp ...

Dealing with text changes in JQuery inputs: best practices

Although this question has been raised numerous times, a definitive answer remains elusive. My goal is to trigger a process (such as an ajax call) when a user types into an input field. Initially, I attempted to utilize the onchange event, but it failed to ...

The Tailwind Rebuild journey never comes to a halt

I have been using Tailwind for the css in my Flask app. Everything was working fine until recently when I started experiencing issues with Tailwind. Usually, when I run a tailwind build script for my app, it updates the css if there are any changes in the ...

Issue with Angular: Unable to update model before modal closure on submit

I have a search form that is displayed within a modal window created using Angular UI Bootstrap. The input fields in the form update the ng-model when submitted. <script type="text/ng-template" id="mobileSearchPanel"> <form> ...

Internet Explorer 11 Freezes Unexpectedly with Dynamic SVG Components

Lately, I developed a unique SVG Icon control for the new html application at my workplace. However, our quality department started noticing that IE 11 would intermittently "crash" while using the application after its implementation. I'm not convinc ...

Node.js Express: Invalid attempt to modify headers after they have already been sent

I have been working on reading a growing file in nodejs and have implemented the following code in my app.js file. app.post('/readfile',function (req,res) { var fullfilename = req.body.filepath+"\\"+req.body.filename; var bi ...

I am having trouble understanding the error message in my three.js code

Recently, I have been working with three.js and wrote the following code. However, I encountered an error. Can anyone help me identify the part that needs to be changed to make the code error-free? import * as THREE from "/assets/threejs/build/three ...

Sorry, but the jQuery AJAX request cannot be executed

Can you help me figure out why this code is causing an error? $("#message").removeClass().addClass(data.error === true ? "error" : "success").html(data.msg).show is not a function This is the code I have written: $.ajax({ type : 'POST' ...

The functionality of the Apple and Google Pay buttons on Stripe is currently not functioning

For a while, everything was working fine with Apple/Google Pay on my website. However, just the other day, I encountered an issue where it suddenly stopped working. I have HTTPS enabled and have connected my cards to Safari as well. I've spent some t ...

Utilizing AngularJS: Using ng-click with ng-repeat to retrieve all data simultaneously

Having a simple ng-repeat: <div ng-repeat="x in names"> <h4>{{x.productid}}</h4> <h4>{{x.newquantity}}</h4> <h4>{{x.total}}</h4> <button ng-click="addInfoAboutOrder(x)">Add Info</button> ...

PHP redirect malfunctioning, yet still functioning?

After making some changes to the structure of my website, I seem to have broken the script somehow. When a user fills out a form correctly, they should be redirected to the appropriate page. However, the page just hangs. Strangely, the form works fine when ...