Stripe Checkout:从Node转移到Firebase函数



My Angular 11应用程序使用带Express服务器的Stripe Checkout来处理付款。Angular&节点。我想使用Firebase函数而不是Node,但当我调用Firebase函数时,我会得到错误:

集成错误:stripe.redirectToCheckout:必须提供lineItems、items或sessionId之一。

角度代码

checkout(): void {
var stripe = Stripe(environment.stripe.key);
var productName = 'T-shirt!!';
var price = '2000';
const options = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify({
productName: productName,
price: price
})
};
var url = 'http://localhost:4242/create-checkout-session';                      // Node server
//var url = 'http://localhost:5000/MY_FIREBASE_PROJECT/us-central1/stripeTest'; // Firebase emulation
fetch(url, options)
.then(function (response) {
return response.json();
})
.then(function (session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function (result) {
if (result.error) {                                                    // redirect fails due to browser or network error
alert(result.error.message);
}
})
.catch(function (error) {
console.error('Error:', error);
});
}

节点服务器

const express = require('express');
const app = express();
const stripe = require('stripe')('MY_SECRET_KEY')
const port = 4242;
app.use(express.json())                                                          // parse request body as JSON
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');       // website you wish to allow to connect
// res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');                                                                            // request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');             
next();                                                                      // pass to next layer of middleware
});
app.post('/create-checkout-session', async (req, res) => {
var productName = req.body.productName;
var price = req.body.price;
console.log('body = ', req.body);
console.log('price = ', req.body.price);
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: productName,
},
unit_amount: price,
},
quantity: 1,
},
],
mode: 'payment',
success_url: 'http://localhost:4200/home?action=success',
cancel_url: 'http://localhost:4200/home?action=cancel',
});
res.json({ id: session.id });
});
app.listen(port, () => console.log('Listening on port ' + port + '!'));

Firebase功能

const stripe = require('stripe')('MY_SECRET_KEY')
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.stripeTest = functions.https.onCall((data, context) => {
var productName = data['productName'];
var price = data['price'];
console.log('data: ', data);
console.log('product name = ', productName);
console.log('price = ', price);
const session = stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: productName,
},
unit_amount: price,
},
quantity: 1,
},
],
mode: 'payment',
success_url: 'http://localhost:4200/home?action=success',
cancel_url: 'http://localhost:4200/home?action=cancel',
}, async (err, data) => {});
return { id: session.id };
})

我不理解这个问题,因为我通过了line_items考试。谢谢

感谢大家帮助我来到这里。

使用Firebase函数时,您需要使用httpsCallable而不是fetch从Angular进行调用。。。

角度代码

import { AngularFireFunctions } from '@angular/fire/functions';
constructor(
// ...
private afFun: AngularFireFunctions) {
afFun.useEmulator("localhost", 5000);
}
checkoutFirebase(): void {
var stripe = Stripe(environment.stripe.key);
this.afFun.httpsCallable("stripeTest")({ productName: 'T-shirt', price: '400' })
.subscribe(result => {           // the result is your Stripe sessionId
console.log({result});       
stripe.redirectToCheckout({
sessionId: result,
}).then(function (result) {
console.log(result.error.message);
});
});
}

然后我们需要将async添加到Firebase中的onCall中。

Firebase功能

exports.stripeTest = functions.https.onCall(async (data, context) => {
var productName = data['productName'];
var price = data['price'];
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: productName,
},
unit_amount: price,
},
quantity: 1,
},
],
mode: 'payment',
success_url: 'http://localhost:4200/home?action=success',
cancel_url: 'http://localhost:4200/home?action=cancel',
});
return session.id;
})

session.idtypeof 'undefined',正如错误消息提示的那样。这意味着,它必须与data一起传递到函数中(没有可用的服务器端会话(。

还要验证属性名称,因为Stripe API至少未知line_items

篮板Ryan Loggerythm的最新答案。

大约半个小时左右,我在Medium上摆弄了Stripe的文档解决方案(这些解决方案似乎更倾向于让开发人员尝试演示,而不是实际实现技术(和其他指南,然后我加载了你的更新答案,你瞧,它完美地工作了,在两段内,1段用于Angular,1段适用于Firebase函数,因此,使用Stripe的Checkout产品而不是自己结账(或转向Shopify的(的全部意义在于:交钥匙的简单性。

与此同时,Stripe的API文档对于这个简单的解决方案来说就像一个迷宫。也许Ryan应该是制作Stripe文档的人😁

相关内容

  • 没有找到相关文章

最新更新