Utilizing a dynamically created Stripe checkout button

Currently, I am attempting to integrate a checkout button from the Stripe Dashboard into my VueJS Project.

I have a feeling that I might not be approaching this in the correct manner, so if you have any advice, I would greatly appreciate it.

In order to include the necessary scripts, I have added

<script src="https://js.stripe.com/v3/"></script>
to my index.html file.

Here is the first error that I encountered

And here is the second error that I received

Below is the code snippet for my Vue component:

<template>
    <div>
    <button
            style="background-color:#6772E5;color:#FFF;padding:8px 12px;border:0;border-radius:4px;font-size:1em"
            id="checkout-button-MY_PLAN"
            role="link"
    >
        Checkout
    </button>

    <div id="error-message"></div>
    </div>
</template>

<script>

    (function() {

        let stripe = Stripe('MY_KEY');

        let checkoutButton = document.getElementById('MY_PLAN');
        checkoutButton.addEventListener('click', function () {

            stripe.redirectToCheckout({
                items: [{plan: 'MY_PLAN', quantity: 1}],

                successUrl: '',
                cancelUrl: '',
            })
                .then(function (result) {
                    if (result.error) {
                        let displayError = document.getElementById('error-message');
                        displayError.textContent = result.error.message;
                    }
                });
        });
    })();
</script>

<style scoped>

</style>

If it turns out that using Stripe in a VueJS Project is not feasible, how can I work around this issue without having to make significant modifications to my entire project?

Answer №1

  1. If you're encountering the first error where Stripe is undefined, it's probably because the Stripe.js library hasn't been loaded before that point in your code execution. Make sure to include Stripe.js [1] in your HTML before any JavaScript using Stripe runs. Remember, don't load it async.

<script src="https://js.stripe.com/v3/"></script>

  1. The second error occurs when trying to use getElementById, but the ID passed does not match the button's ID in the HTML.

The button's ID should be checkout-button-MY_PLAN, but you are trying to find it with MY_PLAN. It's recommended to update your getElementById call to:

let checkoutButton = document.getElementById('checkout-button-MY_PLAN');

[1] https://stripe.com/docs/js/including

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

Is there a way to dynamically update one input field while another input field is being modified? [HTML / JS]

I have a form with 3 input fields. One of the inputs is disabled, while the other two are enabled. The goal is to combine the values entered in the enabled fields to populate the disabled field. How can this be achieved? Is it possible for the value in th ...

Tips on adding a watermark to multi-page PDFs using an image as the watermark

I am currently working on embedding a watermark onto every page of a PDF file using the image-watermark library. So far, I have successfully added a text watermark to files with only one page but now I am exploring ways to extend this functionality for mul ...

Enhancing SEO Performance with React Server Components

Exploring the new topic of React Server Components, which has recently been released, how does it impact SEO compared to SSR/Next.js? Unlike Next.js and traditional SSR where components are rendered statically on the server, React Server Components are re ...

What steps can I take to guarantee that the observer receives the latest value immediately upon subscribing?

In my Angular 2 and Typescript project, I am utilizing rxjs. The goal is to share a common web-resource (referred to as a "project" in the app) among multiple components. To achieve this, I implemented a service that provides an observable to be shared by ...

Issues encountered while establishing a connection to an API in React Native

When attempting to log in a user by connecting to my API, I encountered some issues. It seems that every time my laptop has a different IP address, I need to make changes in the file where the fetch or XMLHttpRequest is located in order for the login proce ...

Using jQuery's .load() method to load a PHP file can result in an exponential increase in XHR finished loading time with each subsequent load

There seems to be an issue with my code using .load() to load a PHP page into a div whenever the navbar or link is clicked. After multiple clicks, I noticed that the "XHR finished loading" increases exponentially and it appears that the same PHP file is be ...

What is the best way to create a sidebar that remains open without triggering a new sidebar every time it is clicked

I am looking to add a sidebar that opens a new view without navigating to a different page. The sidebar remains consistent and I want to avoid duplicating it on all pages. Check out this photo for an example. My goal is to provide additional content or fe ...

I am finding that the text I am creating using context.fillText keeps getting distorted within the canvas

I am attempting to place text inside a canvas element. The HTML markup for the canvas is as follows: <canvas id="leaderboard2" style="position: fixed; right: 1250px; top: 140px; width: 230px; height: 330px;"></canvas>. Des ...

Issues with tangents in three.js compared to the VertexTangentsHelper with problems on display

After enabling the "vertexTangentsHelper" feature in THREE.js, I've noticed that the tangents on various geometries appear to be incorrect. I'm questioning whether these tangents are being miscalculated (possibly due to my shader output) or if t ...

Exploring the Power of JQuery with Hover Effects and SlideToggle

I was struggling to keep the navbar displaying without it continuously toggling when my pointer hovered over it. I just wanted it to stay visible until I moved my pointer away. <script> $(document).ready(function(){ $(".menu-trigger").hover(funct ...

What is the process for establishing the default type for an Activity Entity in Microsoft Dynamics?

Currently in the process of restructuring a portion of script code associated with the Fax Activity Entity within Microsoft Dynamics. Within the script code, the following can be found: document.getElementById("regardingobjectid").setAttribute("defaulttyp ...

Enhance the existing User model in loopback by adding additional properties and functionalities

In my loopback app, I am looking to create a model that represents a user profile. However, the default User model provided by loopback only includes the properties: username password realm emailVerified I am wondering what is the most effective approac ...

Prevent the occurrence of the dreaded 'undefined property' error when attempting to validate a grandchild property

I need to set the state of a React component to the location.state passed with React Router. If it doesn't exist, I want to set it to 0. However, in some cases, the parent (location.state) of the property I am checking for (currentItem) doesn't ...

Display the number of draggable items in the Vue Draggaable component for a nested list of items

Is there a way to display the count of dragged items while using VUE draggable for a Nested Item List? I would like to see how many items I am dragging at any given time, especially when moving subitems along with main items. Here is a screenshot showing ...

Choosing a single radio button value within a nested ng-repeat loop in AngularJS

Help needed with selecting only one radio button value in nested ng-repeat. Please review the source code and suggest any potential mistakes. <form ng-submit="save()"> <div ng-repeat="x in surveyLst"> <div class="row"> < ...

Looping through the v-for, each checkbox will have the same value assigned to it

Below is the loop for displaying user's favorite music genres. However, I would like to retrieve them from a property inside my Vue instance. The code snippet is as follows: <div id="app"> <form method="post" action=""> <fi ...

Is there a way to add pins to separate entity layers, and then remove them from a specific entity layer using Bing Maps AJAX Control, Version 7.0?

Currently, I am utilizing Bing Maps to display store locations on a map. The information about the stores is coming from a dynamic JSON response. When the page loads, the map shows local stores with pushpins and infoboxes. As the map pans, my goal is to re ...

Encountering the error "object object" while attempting to pass parameters to my servlet through AJAX

Experiencing an issue where my ajax call is ending up in the error function. I have noticed that my success function is empty, but I was expecting to receive messages from my servlet whether the data provided is correct or incorrect. The popup dialog displ ...

Updating an array of objects within an array using another array of objects

There are two JavaScript Arrays: let x = [ { id: 'Abc', children: [ { id: 12, name: 'john' }, { id: 13, name: 'dow' ...

Serving pages with Node JS and loading .js files on the client side

Here is a simple JS file that will be familiar to those who have worked with Socket.IO in NodeJS and Express: var express = require('express'), app = express(), server = require('http').createServer(app), io = require(&apos ...