简体   繁体   中英

No token Provided (vue stripe)

I'm trying to make a payment using stripe but I keep getting no token provided any time I click onPurchase , Can someone help me on this?

My Vue template to call out the function :

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

My script tag on how I send the token to stripe to make payment


<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 create 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>

Error I get in my console :

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

my backend to send the payment to stripe

const router = require("express").Router();
const moment = require("moment");
const stripe = require("stripe")(process.env.STRIPE_SECREY_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;

On the server you need to initialise Stripe with your secret key, which you don't appear to be doing here.

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

Details can be found in the Stripe docs: https://stripe.com/docs/api/authentication?lang=node

--

EDIT: After explanation in the comments, it appears that the OP has not used a dotenv file, which mean process.env.STRIPE_SECRET_KEY is null, hence the error.

Recommended reading: https://www.npmjs.com/package/dotenv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM