使用 Mongoose 在我的数据库中保存 checkoiut 后的 Stripe 客户 ID

Save Stripe customer id after checkoiut in my database with Mongoose

我使用客户门户设置了 Stripe Checkout,我希望能够检索客户 ID 以让用户转到他的门户。 依次为:

  1. 我要检索客户 ID
  2. 将其保存在我的数据库中(用户已经登录)。

结帐表单效果很好,重定向也很好。但是我无法检索客户 ID(当我 console.log() 它时什么也没有出现。

我的快递代码:

  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。我什至不知道我该怎么做。

const customerId = await stripe.customers.retrieve(session.customer.id)

Session 对象上的客户 is just an ID — it's the ID itself. You can expand 它,但您似乎没有。它不是具有 id 字段的对象。所以 customer.id 为空。

尝试只做 customerId = session.customer

另请注意,您不应该真正在 success_url 页面上执行此逻辑。客户可能不会访问它,因为他们可能会在付款后立即关闭浏览器。你应该使用网络钩子。 https://stripe.com/docs/payments/checkout/fulfill-orders