命中条带校验流后缺少Req.params和Req.user



我正在尝试将我的应用程序中的Stripe订阅计费与分层定价模型集成,根据我的理解,我需要做两件事:

  1. 允许我的新用户也创建一个条纹客户帐户(通过集成(
  2. 监控Stripe webhook"事件",以便在客户订阅付款处于活动状态时提供访问权限

我的用户流如下:

  • 在我的应用程序中创建配置文件(保存到数据库(->重定向到条带结账门户以获取计费信息(保存到条带数据库(->尝试将stripe customerId保存到我的数据库中,以便我可以监视订阅状态

但是,我不知道如何将customerId信息保存在我的应用程序中,因为req.userreq.params是空的,因为用户被从条纹计费门户发送回

控制器功能

module.exports.stripeWebhook = async (req, res) => {
let data;
const webhookSecret = stripeWebhookSecret;
if (webhookSecret) {
let event;
let signature = req.headers["stripe-signature"];
try {
event = stripe.webhooks.constructEvent(
req.body,
signature,
webhookSecret
);
} catch (err) {
console.log(`⚠️  Webhook signature verification failed.`);
return res.sendStatus(400);
}
data = event.data;
eventType = event.type;
} else {
// retrieve the event data directly from the request body.
data = req.body.data;
eventType = req.body.type;
}
switch (eventType) {
case 'payment_intent.succeeded': {
console.log('PaymentIntent was successful!');
break;
}
case 'checkout.session.completed':
// Payment is successful and the subscription is created.
// You should provision the subscription and save the customer ID to your database.
console.log(data.object.customer);  <- works
const user = await User.findById(req.user.id); <- comes back empty so my next two lines of code don't work
user.stripeId.push(data.object.customer);
await user.save();
break;
default:
}
res.sendStatus(200);
};

App.js

app.use(bodyParser.raw({type: "application/json"}));
app.use(express.json({ limit: '1mb' }));
app.use(express.urlencoded({ extended: true }));

我包含了app.js代码,因为bodyparser.raw会影响主体在我的控制器函数中的运行方式。

我指望req.user或req.params在我的数据库中找到用户,但它不起作用。如何像条纹注释建议的那样将customerId保存到我的数据库中?

在为客户创建结账会话之前,您应该创建Stripe客户帐户。

  1. 检查客户是否已经拥有stripe_customer帐户(Stripe客户帐户(。如果是,就用那个。若并没有,为他创建一个并保存在数据库中。

  2. 为结账会话设置stripe_customer,这样客户将在Stripe结账中自动进行身份验证

  3. 您可以选择将用户的_id放入Stripe签出会话的元数据中,以便稍后在webhook中访问该数据。

注意:您应该为每种货币创建一个stripe_customer帐户。因此,一个用户可以有多个stripe_customer帐户,每个货币一个。

router.post('/create-checkout-session', authenticate.verifyUser, async (req, res) => {
const { currency } = req.body;
...
// If user does not have stripe customer for order currency, create a new one.
if (!(req.user.stripe_customer && req.user.stripe_customer[currency])) {
const new_stripe_customer = await stripe.customers.create({
email: req.user.email,
metadata: {
user_id: req.user._id.toString(),
},
});
let update = {};
update[`stripe_customer.${currency}`] = new_stripe_customer.id;
await Users.findByIdAndUpdate(req.user._id, update);
if (!req.user.stripe_customer) {
req.user.stripe_customer = {};
req.user.stripe_customer[currency] = new_stripe_customer.id;
} else {
req.user.stripe_customer[currency] = new_stripe_customer.id;
}
}
...
// Set `stripe_customer` for checkout session.
const session = await stripe.checkout.sessions.create({
customer: req.user.stripe_customer[currency],
...
});

...
}

最新更新