如何通过Stripe CLI Post请求中的变量

发布于 2025-02-13 14:14:17 字数 2552 浏览 1 评论 0 原文

我想保存一个变量,并在重新加载页面后能够进一步传递。因此,我想获得 req.session.variable ,并能够在 router.post('/webhook',...)中使用它,该由Stripe控制CLI。本文的内部请求 req.session.variable 不可用,因为该网站已将用户重定向到另一个网站,该网站清除了 req.session content,更多地< code> req.body post request 默认情况下是 req.rawbody 格式中的。有没有办法将此变量传递到请求中并轻松使用?

let express = require('express');
let router = express.Router();
let postMong = require('./post')
require("dotenv").config()
router.use(express.json());
const YOUR_DOMAIN = 'http://localhost:4242';
const stripe = require('stripe')(process.env.PUBLIC_KEY);
const endpointSecret = 'whsec_1c7320d5c8878c54d6f99e0d5dcd441008c79b76ddb0a09727a4fd977d3ac1ed';
const fulfillOrder = (ses) => {
  console.log("Order Completed")
}


router.post('/checkout/create-order', async (req, res) => {
  const price = req.body.order.stripe_price || undefined,
        product = req.body.order.stripe_product || undefined
  const session = await stripe.checkout.sessions.create({
    //shipping_address_collection: {
    //  allowed_countries: ['US', 'CA'],
    //},
    //shipping_options: [
    //  {
    //    shipping_rate_data: {
    //      type: 'fixed_amount',
    //      fixed_amount: {
    //        amount: 2499,
    //        currency: 'usd',
    //      },
    //      display_name: 'International Shipping',
    //      // Delivers between 5-7 business days
    //      delivery_estimate: {
    //        minimum: {
    //          unit: 'week',
    //          value: 2,
    //        },
    //      }
    //    }
    //  },
    //],
    line_items: [
      {
        price: price,
        quantity: 1,
      },
    ],
    payment_method_types: ["card", 'us_bank_account'],
    mode: 'payment',
    success_url: `${YOUR_DOMAIN}/success.html`,
    cancel_url: `${YOUR_DOMAIN}/index.html`,
  });

  res.json({url: session.url})
});


router.post('/webhook', (request, response) => {
  const payload = request.body;
let username = request.session.username; // returns undefined because the session is empty after the redirect
  const sig = request.headers['stripe-signature'];
  let event;
  try {
    event = stripe.webhooks.constructEvent(payload, sig, endpointSecret);
  } catch (err) {
    console.log(err.message)
    return response.status(400).send(`Webhook Error: ${err.message}`);
  }

  if (event.type === 'checkout.session.completed') {
    const session = event.data.object;
    fulfillOrder(session);
  }

  response.status(200);
});

module.exports = router

I want to save a variable and be able to pass it further after the page has been reloaded. So i want to get the req.session.variable and be able to use it in router.post('/webhook', ...) which is controled by Stripe CLI. Inside of this post request the req.session.variable is unavailable because the site has redirected the user to another website which clears the req.session content, moreove the content of req.body inside the post request is by default in req.rawBody format. Is there a way i can pass this variable into the request and use it with ease?

let express = require('express');
let router = express.Router();
let postMong = require('./post')
require("dotenv").config()
router.use(express.json());
const YOUR_DOMAIN = 'http://localhost:4242';
const stripe = require('stripe')(process.env.PUBLIC_KEY);
const endpointSecret = 'whsec_1c7320d5c8878c54d6f99e0d5dcd441008c79b76ddb0a09727a4fd977d3ac1ed';
const fulfillOrder = (ses) => {
  console.log("Order Completed")
}


router.post('/checkout/create-order', async (req, res) => {
  const price = req.body.order.stripe_price || undefined,
        product = req.body.order.stripe_product || undefined
  const session = await stripe.checkout.sessions.create({
    //shipping_address_collection: {
    //  allowed_countries: ['US', 'CA'],
    //},
    //shipping_options: [
    //  {
    //    shipping_rate_data: {
    //      type: 'fixed_amount',
    //      fixed_amount: {
    //        amount: 2499,
    //        currency: 'usd',
    //      },
    //      display_name: 'International Shipping',
    //      // Delivers between 5-7 business days
    //      delivery_estimate: {
    //        minimum: {
    //          unit: 'week',
    //          value: 2,
    //        },
    //      }
    //    }
    //  },
    //],
    line_items: [
      {
        price: price,
        quantity: 1,
      },
    ],
    payment_method_types: ["card", 'us_bank_account'],
    mode: 'payment',
    success_url: `${YOUR_DOMAIN}/success.html`,
    cancel_url: `${YOUR_DOMAIN}/index.html`,
  });

  res.json({url: session.url})
});


router.post('/webhook', (request, response) => {
  const payload = request.body;
let username = request.session.username; // returns undefined because the session is empty after the redirect
  const sig = request.headers['stripe-signature'];
  let event;
  try {
    event = stripe.webhooks.constructEvent(payload, sig, endpointSecret);
  } catch (err) {
    console.log(err.message)
    return response.status(400).send(`Webhook Error: ${err.message}`);
  }

  if (event.type === 'checkout.session.completed') {
    const session = event.data.object;
    fulfillOrder(session);
  }

  response.status(200);
});

module.exports = router

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尐偏执 2025-02-20 14:14:18

根据您需要存储的信息,您有几个不同的选项,但是在所有情况下,最好使用Checkout Session对象[0]存储所需的内容。
如果您想传递参考ID(例如,来自应用程序的客户ID或CART ID),则可以使用 Client_reference_id [1]。如果您需要传递更多的信息,则可以依靠元数据 [2]哈希,您可以在其中最多输入所需的信息。

由于您已经配置了Webhook端点,因此在会话完成后,您可以在 session 对象中访问这两个字段。

[0] https://stripe.com/docs/docs/api/papi/checkections yobjections/sessions/sessions/objections/object/object/

[1] https://stripe.com/docs/api/checkout/sessions/sessions/create#create_checkout_checkout_session_session-client_reference_id_id

[2]会话/create#create_checkout_session-metadata” rel =“ nofollow noreferrer”> https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session_session_session-metadata

Depending on what you need to store as information you have a couple of different options, but in all cases it’s best if you use the Checkout Session Object[0] to store what you need.
If you’re looking to pass a reference id (e.g. customer id or cart id from your app) you can use client_reference_id[1]. If you need to pass more info than you can rely to the metadata[2] hash where you can input as much information as you need.

Since you’ve already got a webhook endpoint configured, you will have access to both of these fields in your session object after the session is complete.

[0] https://stripe.com/docs/api/checkout/sessions/object

[1] https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-client_reference_id

[2] https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-metadata

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文