Token not provided (Vue Stripe)

I am facing an issue while trying to process a payment using Stripe. Every time I click onPurchase, I receive an error message saying "no token provided". Can anyone assist me with this?

Below is my Vue template where I call the function:

 
<span class="a-button-inner">
 <span @click="onPurchase" class="a-button-text">Purchase</span>
 </span>

This is the script tag in which I send the token to Stripe for payment processing:


<script>
import { mapGetters } from "vuex";
import axios from "axios";

export default {
  data() {
    return {
      error: "",
      stripe: null,
      card: null
    };
  },

  computed: {
    ...mapGetters([
      "getCart",
      "getCartTotalPriceWithShipping",
      "getEstimatedDelivery"
    ])
  },
  mounted() {
    this.stripe = window.Stripe(
      "pk_test_51KGqWkHCcyZvTrDrTmAbtZkngRWbP0FCvV3bgZnz8GXuleqD1fo1lRa5seDD3qKsk0irYLumaH3SeI5cILED3pwq00NR023dNZ"
    );
    let elements = this.stripe.elements();
    this.card = elements.create("card");
    this.card.mount(this.$refs.card);
  },
  methods: {
    
   async onPurchase() {
// This creates a token to send to Stripe
      let token = await this.stripe.createToken(this.card);
       return axios("http://localhost:5000/api/payment", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          token: token,
          totalPrice: this.getCartTotalPriceWithShipping,
          cart: this.getCart,
          estimatedDelivery: this.getEstimatedDelivery
        })
      })
       
        .then(data => {
          console.log(data);
        })
        .then(res => {
          console.log(res);
        });
    },
    formatPrice(value) {
      let val = (value / 1).toFixed(2).replace(".", ",");
      return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    }
  }
};
</script>

The following error message appears in my console:

{
    "success": false,
    "message": "No token Provided"
}

In my backend code, I handle sending the payment to Stripe:

const router = require("express").Router();
const moment = require("moment");
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const verifyToken = require("../middelwares/verify-token");
const Order = require("../models/order");

const SHIPMENT = {
  normal: {
    price: 13.98,
    days: 7
  },
  fast: {
    price: 49.98,
    days: 3
  }
};

function shipmentPrice(shipmentOption) {
  let estimated = moment()
    .add(shipmentOption.days, "d")
    .format("dddd MMMM Do");

  return { estimated, price: shipmentOption.price };
}

router.post("/shipment", (req, res) => {
  let shipment;
  if (req.body.shipment === "normal") {
    shipment = shipmentPrice(SHIPMENT.normal);
  } else {
    shipment = shipmentPrice(SHIPMENT.fast);
  }

  res.json({ success: true, shipment: shipment });
});

router.post("/payment", verifyToken, (req, res) => {
  let totalPrice = Math.round(req.body.totalPrice * 100);
  stripe.customers
    .create({
      email: req.decoded.email
    })
    .then(customer => {
      return stripe.customers.createSource(customer.id, {
        source: "tok_visa"
      });
    })
    .then(source => {
      return stripe.charges.create({
        amount: totalPrice,
        currency: "usd",
        customer: source.customer
      });
    })
    .then(async charge => {
      let order = new Order();
      let cart = req.body.cart;

      cart.map(product => {
        order.products.push({
          productID: product._id,
          quantity: parseInt(product.quantity),
          price: product.price
        });
      });

      order.owner = req.decoded._id;
      order.estimatedDelivery = req.body.estimatedDelivery;
      await order.save();

      res.json({
        success: true,
        message: "Successfully made a payment"
      });
    })
    .catch(err => {
      res.status(500).json({
        success: false,
        message: err.message
      });
    });
});

module.exports = router;

Answer №1

To set up Stripe on your server, you must initialize it with your confidential key, which seems to be missing in your code.

const stripe = require('stripe')('your-secret-key')

You can find more information about this in the official Stripe documentation: https://stripe.com/docs/api/authentication?lang=node

--

EDIT: It has been pointed out in the comments that the original poster did not use a dotenv file, resulting in process.env.STRIPE_SECRET_KEY being null and causing an error.

I recommend checking out this resource: https://www.npmjs.com/package/dotenv

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

Utilizing the Google Analytics Embed API for a modern third-party dashboard integration within my Ruby on Rails application

I've been referencing a specific example for utilizing the Google Analytics Embed API with Chart.js in my application. However, I'm encountering an issue at Step 3 where we need to include various javascript libraries. I was successful in loadin ...

Tips for keeping a checkbox checked on page refresh in React JS

I am facing an issue where the checkbox, which was checked by the user and saved in local storage, is displaying as unchecked after a page refresh. Even though the data is stored in local storage, the checkbox state does not persist. The code I am using i ...

Application suddenly crashes due to a severe issue: FATAL EXCEPTION: java.lang.RuntimeException, preventing the activity from starting

I recently updated my Ionic, Angular, and Capacitor application to the latest versions - Ionic 7, Angular 16, and Capacitor 5. After the update, I noticed that on Android, the app works fine when installed for the first time. However, upon restarting the a ...

Comparing DOM Manipulation and Templating

Currently in the process of enhancing the performance of my HTML5 phonegap application, I am faced with the challenge of efficiently managing a <ul> element that is frequently updated. For the initial injection of database data, I am utilizing Docum ...

Having trouble getting the Socket.io package to install on Node.js in Windows 7?

Hey there! I'm having trouble installing the socket.io module using npm install socket.io. Unfortunately, I encountered the following error: npm WARN package.json <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee8f80c3869 ...

Running an Angular-made Chrome extension within an iframe: A guide

I'm currently working on creating a Chrome extension that displays its content in a sidebar rather than the default popup. I've come to realize that in order to achieve this, I need to use an iframe due to the limitations of the default chrome ex ...

.toggleClass malfunctioning inexplicably

I've been struggling to make a div box expand when clicked and revert to its original size when clicked again. It seems like a simple task, but no matter what I try, I can't seem to get it right. I'm not sure where I'm going wrong, as t ...

Jquery's Challenge with Loading Images in Advance

Below is a code snippet to preload image using jQuery. var _images = ['/images/ajax-loader.gif']; $.each(_images, function (e) { $(new Image()).load(function () { //alert($(this).attr('src') + 'has loaded!&ap ...

Understanding how to compare binary values with dates in NodeJs

I have a SQL query that retrieves a column called days, which contains the value 1111100. Each bit in this value represents a day of the week, where the first bit '1' corresponds to Monday and the sixth bit '0' corresponds to Saturday. ...

Using jQuery to Populate a Dropdown List in ASP.NET Core 2.1

I'm trying to implement a function where clicking a button creates a new div row with multiple dropdowns. How can I populate these dropdowns using the viewmodel loaded into my view? @model App.Data.ViewModels.FilterDocumentsViewModel <button type ...

Having trouble making the jQuery post method work to invoke a function in a Coldfusion component

While attempting to invoke a cfc method through ajax using jQuery's post() method, I repeatedly encounter an error message stating that "the xxx parameter to the yyy function is required but was not passed in". Below is the cfc function in question: ...

What is the process to navigate through images by clicking buttons in Angular?

Looking for a solution to cycle through a series of images using previous/next buttons? The goal is to have the image dynamically change with Angular. When one of the buttons is clicked, a different image from an array in the controller should be displaye ...

Dynamic css property implementation in Vue list rendering

I am currently working on creating a carousel-style list of items similar to the iOS native date/time pickers, where the list can be shifted both upwards and downwards. The positioning of each item is determined by the `top` property from a model, which i ...

Exploring the dynamic relationship between React's useEffect and useState functions

Currently, I am working on developing a table using React and Material UI's XGrid component. The table includes buttons that execute specific actions when clicked. One of the requirements is to set the row ID upon clicking the row itself using the use ...

"Executing a child component's method from a parent component in Vue.js: A step-by-step guide

I am currently working with a parent component that includes two child components: a dropdown and a map. <template> ... <dropdown-city @currentCity="updateCity"></dropdown-city> <map ref="mymap" @myMap=&quo ...

Displaying colors using Javascript

When using node.js to create an HTML file from a js file, I am encountering an issue where the colors are not displaying in the output. I have generated hex values for the colors, but they do not appear in the HTML file as expected. var format; function ...

What is the correct way to pass parameters when using the setState() function in React hooks?

I am working on a project where I have a list of country names. When a user clicks on one of the countries, I want to update the state with the name of the newly selected country. This state change will then trigger other changes in a useEffect(). The stat ...

Using Angular2 to assign the response from an http.get request to a class object

I am a beginner in Angular and I have a JSON file that holds the configuration URL for my application. Path: app/config/development.json { "apiUrl": "http://staging.domain.com:9000/", "debugging": true } Below is the content of my config.service.t ...

Using selenium to create a brief pop-up message that appears for a few seconds

I have a Selenium script in Java that opens a Google web page and then closes the browser. Upon closing the browser, I want a pop-up message to appear briefly with the text "Code executed" before fading away after a few seconds. I know that I can achieve t ...

Enhance the clarity of content within an IFrame by sharpening the focus on

I recently developed an iframe to open a chat site I built using React.js and Tailwind. The iframe is loaded dynamically on the website through javascript. However, I noticed that when I click on the input field inside the iframe, the content appears blurr ...