User side: POST method using fetch function:
let response = await fetch(url, {
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"body": JSON.stringify({"stripeToken": token.id})
});
Server side: URL to fetch is a Firebase Cloud Function:
const functions = require('firebase-functions');
const cors = require('cors')({origin: true});
const stripe = require("stripe")("PRIVATE_KEY");
exports.chargeStripe = functions.https.onRequest( async (request, response) => {
// Getting token
let token = request.body.stripeToken;
// Creating charge
let charge = await stripe.charges.create({
amount: 99,
currency: 'eur',
description: 'Payment',
source: token
});
// Sending response
charge ? send(response, 200, {message: 'Success'}) : send(response, 500, {message: 'Error!'});
});
The problem is that I am getting console.log(token) → 'undefined'
.
Update 1
It seems that Chrome (browser) is blocking the fetch function (CORS policy). If I test the end-point via Insomnia, everything is working fine.
So, someone knows what to do in this case?
Update 2
Thanks to Doug Stevenson, I added CORS middleware inside the function:
exports.chargeStripe = functions.https.onRequest( (request, response) => {
// Enable CORS using the `cors` express middleware.
return cors(request, response, async () => {
// Reading token
let token = request.body.stripeToken;
// Charging user
let charge = await stripe.charges.create({
amount: 99,
currency: 'eur',
description: 'Payment',
source: token
});
// Sending response
response.status(200).send('Ok');
});
});
Now everything works!