问题描述
我使用客户门户设置了 Stripe Checkout,我希望能够检索客户 ID 以让用户访问他的门户.按顺序:
I set up Stripe Checkout with Customer Portal and I want to be able to retrieve the customer id to let the user go to his portal.In order:
- 我想检索客户 ID
- 将其保存在我的数据库中(用户已登录).
结帐表单运行良好,重定向也运行良好.但是我无法检索客户 ID(当我 console.log()
它时什么也没有出现.
The checkout form works well, the redirection too. But I'm unable to retrieve the customer id (nothing appears when I console.log()
it.
我的快递代码:
router.post("/create-checkout-session", ensureAuthenticated, async (req, res) => {
const { priceId } = req.body;
try {
const session = await stripe.checkout.sessions.create({
mode: "subscription",
payment_method_types: ["card"],
line_items: [
{
price: priceId,
quantity: 1,
},
],
success_url: 'http://localhost:3000/fr/premiereconnexion?session_id={CHECKOUT_SESSION_ID}'
});
res.send({
sessionId: session.id,
});
}
catch (e) {
res.status(400);
return res.send({
error: {
message: e.message,
}
});
}
});
router.post('/premiereconnexion', ensureAuthenticated, async (req, res) => {
const session = await stripe.checkout.sessions.retrieve(req.query.session_id);
const customerId = await stripe.customers.retrieve(session.customer.id);
console.log(customerId);
req.user.stripeCustomer = customerId
req.user.save()
});
router.get('/premiereconnexion', ensureAuthenticated, (req, res) => {
res.render('users/fr/endpayment', {
user: req.user
})
})
我的用户模型:
const User = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true,
required: true
},
stripeCustomer: {
type: String,
default: null
}
});
第一个问题是能够调用客户ID.我什至不知道我该怎么做.
The first problem is to be able to call the customer ID. I don't even know how I can do this.
推荐答案
const customerId = await stripe.customers.retrieve(session.customer.id)
Session 对象上的客户 只是一个 ID— 这是 ID 本身.您可以展开它,但您似乎没有.它不是具有 id
字段的对象.所以 customer.id 为空.
Customer on the Session object is just an ID — it's the ID itself. You can expand it but you don't seem to. It's not an object that has an id
field. So customer.id is null.
尝试只做 customerId = session.customer
.
还要注意,您不应该在 success_url
页面上真正执行此逻辑.客户可能不会访问它,因为他们可能会在付款后立即关闭浏览器.您应该使用网络钩子.https://stripe.com/docs/payments/checkout/fulfill-orders
Note also you shouldn't really be doing this logic on the page that is the success_url
. The customer might not visit that since they might close the browser straight after paying. You should use webhooks. https://stripe.com/docs/payments/checkout/fulfill-orders
这篇关于使用 Mongoose 在我的数据库中 checkoiut 后保存 Stripe 客户 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!