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

When attempting to send a POST request to /api/users/login, the system returned an error stating that "

Is there a way to make a post request to the mLab Database in order to determine if a user account already exists? The server's response states that the User is not defined. Can you please review my code? // @route post api/user/login# router.post(& ...

Exploring the concept of passing 'this' as a parameter in JavaScript

<button type="button" aria-haspopup="dialog" aria-controls="b" onclick="openLayer($('#b'))"> button</button> <div role="dialog" id="b"><"button type="button">close<"/button></div> function openLayer(target){ ...

Steps for creating a personalized @click function for a <router-link> element

I am currently working on a VueJS 3 application that includes a router-link element. I am trying to implement a custom click-handler where instead of redirecting to the href URL, it will trigger a function in my pinia-store. <router-link ...

How to change a string from utf-8 to iso-8859-1 using Javascript

Although it may seem unpleasant, it is essential. I am facing an issue with a HTML form on my website that uses utf-8 charset but is sent to a server operating with iso-8859-1 charset. The problem arises when the server fails to interpret characters commo ...

Can html-webpack-plugin be configured to create <style> elements from CSS files?

I am managing a static site with Vue and Webpack. In my project, I have a file named style.css containing global CSS rules which I import using import './styles.css' in my index.js file. Additionally, I have some .vue files that generate their o ...

Is there a way to launch QTP from JavaScript without relying on ActiveXObject?

Is there a way to call QTP from JavaScript without relying on ActiveXObject? I would appreciate any guidance on how to accomplish this task. Thanks in advance, Ramya. ...

Adjusting diagram size based on screen width using Bootstrap and jQuery

I recently created a diagram that adjusts its size according to the screen width. However, when I implemented this code on my page, I encountered an issue where the final circle or glyph would drop to the next line instead of staying on the same line as in ...

Disregard keys with null values when making a post request using react and axios

As a beginner in JavaScript, I am facing an issue where I do not want to include keys with null values when sending metadata. For example, I should only send the filepath as it has a value, and omit tags and owner which are null. How can I achieve this? ...

JSP checkbox functionality

I have been attempting to solve this issue since last night, but I am struggling and need some help. There are two pages, named name.jsp and roll.jsp. In name.jsp, there are two input text boxes and one checkbox. After entering data in the text boxes and ...

ObservableResolve(): Unleashing the power of RxJS5 for handling asynchronous data streams

Hey there! To dive deeper into RxJS, I thought of creating my own custom Rx operator. So here's a straightforward one that seems to be working smoothly: Rx.Observable.prototype.multiply = function (input) { const source = this; return Rx.O ...

Template displaying multiple polymer variables side by side

Here is the date object I am working with: date = { day: '05' } When I use this code: <div>{{date.day}}</div> It generates the following HTML output: <div>05</div> Everything looks good so far. Now, I want to try th ...

The combination of sass-loader and Webpack fails to produce CSS output

Need help with setting up sass-loader to compile SCSS into CSS and include it in an HTML file using express.js, alongside react-hot-loader. Check out my configuration file below: var webpack = require('webpack'); var ExtractTextPlugin = require ...

Obtain the origin of the image using dots in Javascript

Sharing my experience with setting a background image using Javascript. Initially, I tried using two dots like this: .style.backgroundImage = "url('../images/image00.jpg')" However, it did not work as expected. So, I removed one dot: .style.ba ...

The necessary parameters are not provided for [Route: sender] with the [URI: {name}/{code}]. The missing parameters are name and code

I have encountered a problem while using AJAX and I am struggling to find a solution. Routes: web.php Route::get('/{name}/{code}', 'TestController@counter'); Route::post('/{name}/{code}', 'TestController@sender')-&g ...

Guidelines for linking a promise function to a JSX component

How can we use React components to handle the result of a promise function and map it to JSX components? <Promise on={myFunc}> <Pending> ... </Pending> <Resolved> {(data: any) => ( ... )} ...

Tips for utilizing boolean values in form appending with Vue.js

I am currently attempting to send availability as a boolean value. However, despite my efforts, it keeps sending false to my database. Here is my code snippet: <input v-model="availability" /> </d ...

Using JavaScript regex to substitute white spaces and other characters

Here is a string I need to modify: "Gem. Buitentemperatuur (etmaal)" I want to remove all spaces, capital letters, and special characters from the string so that it becomes: "gem_buitentemperatuur_etmaal" ...

Remove a field from a JSON array

Consider the following JSON array: var arr = [ {ID: "1", Title: "T1", Name: "N1"}, {ID: "2", Title: "T2", Name: "N2"}, {ID: "3", Title: "T3", Name: "N3"} ] Is there a way to remove the Title key from all rows simultaneously without using a loop? The r ...

You cannot invoke this expression while destructuring an array of React hooks in TypeScript

Within my React TypeScript component, I have several fields that check a specific condition. If the condition is not met, the corresponding field error is set to true in order to be reflected in the component's DOM and prevent submission. However, whe ...

Is it possible to calculate a variable within a dataset using existing data as a reference point?

Is there a way to dynamically compute some of the data variables in a Vue instance by referencing other variables and tracking their changes? new Vue({ el: '#root', data: { x: 1, y: x + 1 } }) <script src="https://cdnjs.cloudf ...