用户端:使用 fetch 函数的 POST 方法:
let response = await fetch(url, {
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"body": JSON.stringify({"stripeToken": token.id})
});
服务器端:要获取的 URL 是 Firebase 云函数:
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!'});
});
问题是我得到console.log(token) → 'undefined'.
更新 1
Chrome(浏览器)似乎正在阻止获取功能(CORS 策略)。如果我通过 Insomnia 测试端点,则一切正常。
那么,有人知道在这种情况下该怎么做吗?
更新 2
感谢Doug Stevenson,我在函数中添加了 CORS 中间件:
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');
});
});
现在一切正常!
四季花海
404011 cloud function
javascript firebase 云函数:如何修复 require 未定义错误
Error: errCode: -404011 cloud function execution error | errMsg: cloud.callFunction:fail requestID
cloud function service error code -501000
相关分类