簡體   English   中英

在完成交易后發送響應 - Stripe

[英]Sending a response after a finalized transaction - Stripe

在與 ChatGPT 進行長時間討論后,我設法編寫了將用戶重定向到 Stripe 支付頁面的代碼,然后在交易成功完成時捕獲事件。 問題是我的fetch請求已經收到來自/checkout端點的響應,而不是等待來自/webhook的響應。 我希望我的 API 在成功完成交易后返回正確生成的響應。 我究竟做錯了什么?

首先,我向/checkout端點發送請求,該端點負責生成支付鏈接並將其發回:

fetch('http://localhost:3001/checkout', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        items: [
            {
                id: 0,
            },
        ],
    }),
})
    .then((res) => {
        if (res.ok) return res.json();
        return res.json().then((e) => console.error(e));
    })
    .then(({url}) => {
        console.log(url);
        window.location = url;
    })
    .catch((e) => {
        console.log(e);
    });

當我按下按鈕時,這段代碼將我重定向到 Stripe 支付頁面。

端點/checkout

app.post('/checkout', async (req, res) => {
  try {
      const session = await stripe.checkout.sessions.create({
          payment_method_types: ['card'],
          line_items: req.body.items.map(({id}) => {
              const storeItem = storeItems.get(id);
              return {
                  price_data: {
                      currency: 'pln',
                      product_data: {
                          name: storeItem.name,
                      },
                      unit_amount: storeItem.priceInCents,
                  },
                  quantity: 1,
              };
          }),
          mode: 'payment',
          success_url: `${process.env.CLIENT_URL}/success.html`,
          cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
      });
      console.log(session.url);
      res.json({url: session.url});
  } catch (e) {
      // If there is an error send it to the client
      console.log(e.message);
      res.status(500).json({error: e.message});
  }
});

我使用stripe listen --forward-to localhost:3001/webhook StripeCLI 連接到我的服務器。 現在我可以使用/webhook端點捕獲成功的交易事件,但我無法The transaction was successful返回給客戶端:

app.post('/webhook', (req, res) => {
  const event = req.body;

  if (event.type === 'checkout.session.completed') {
      res.send('The transaction was successful');
  }
});

成功付款后,客戶應被重定向回您的網站。 您可以在哪里創建成功頁面。

success_url: `${process.env.CLIENT_URL}/success.html`,

如果你想在付款成功頁面后從 Strapi 取回一些數據,你可以添加這個

success_url: `${process.env.CLIENT_URL}/success.html?&session_id={CHECKOUT_SESSION_ID}`

在成功頁面,您只需解構數據。 和他們一起做任何你想做的事:)

Stripe 會自動將客戶端重定向到您在創建 Stripe 時指定的success_url session。

例如,您可以使用 webhook 將訂單保存在數據庫中,但不能重定向客戶端。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM