条纹付款后重定向到其他页面-Node.js

时间:2018-06-20 11:19:20

标签: node.js express stripe-payments stripe.js

我正在按照https://stripe.com/docs/recipes/custom-checkout上的指南,在我的网站上放一个自定义结帐按钮。到目前为止,测试付款将通过,我可以创建一个客户和一个新的费用。

我被困的部分实际上是在交易后将用户重定向到/success页面,例如,详细说明所收取的费用。我尝试使用res.render('success')甚至res.redirect('/success'),但无法执行。

<button id="upgrade_membership"</button>

<script>
  var checkoutHandler = StripeCheckout.configure({
    key: "<%= keyPublishable %>",
    locale: "auto"
  });

  var button = document.getElementById("upgrade_membership");
    button.addEventListener("click", function(ev) {
    checkoutHandler.open({
      name: "Name",
      description: "Description",
      image: 'images/path.jpg',
      token: handleToken
    });
  });

  function handleToken(token) {
    fetch("/charge", {
      method: "POST",
      headers: {"Content-Type": "application/json"},
      body: JSON.stringify(token)
    })
    .then(response => {
      if (!response.ok)
        throw response;
        return response.json();
      })
   .then(output => {
     console.log("Purchase succeeded:", output);
   })
   .catch(err => {
     console.log("Purchase failed:", err);
   })
}
</script>

服务器

app.post("/charge", async (req, res) => {
  let amount = 1000;

  // Check user has stripe id as stripe do not check for uniqueness of email address
  try {
    var user_stripe_id = await queries.get_stripe_id_by_email(req.body.email);
  } catch (err) {
    console.log("Error with Query " + err);
    return;
  }

  if(user_stripe_id !== null) {
    // Need to process payment as a current customer on stripe
    return;
  } else {
    // Create Stripe Customer
    stripe.customers.create({
      email: req.body.email,
      card: req.body.id
    })
  .then(customer =>
    // Charge Customer payment
    stripe.charges.create({
      amount,
      description: "description here",
      currency: "GBP",
      customer: customer.id
    }))
    .then(charge => {
      // gets all the way here and logs out the charge object
      // want to redirect here
      res.send(charge)
      // if i replace the above with res.render('home') nothing happens 
    })
    .catch(err => {
      console.log("Error:", err);
      res.status(500).send({error: "Purchase Failed"});
    });
   } // if/else
});

因此,在浏览器控制台中成功完成交易后,我会打印Purchase succeeded:

我想要实现的是将服务器重定向到另一页

更新

因此,我尝试在付款成功后在此处呈现其他页面,但是我什么都无法工作

res.render('home') // does not work
return res.render('home') // does not work
return res.redirect('/') // does not work
res.redirect('/') // does not work

更令人困惑的

console.log("I WANT TO RENDER A NEW PAGE")
res.render('home')
console.log("WHY IS THIS BEING LOGGED")

两个控制台日志都已记录

是因为我在then链中吗?真的不明白这里发生了什么

1 个答案:

答案 0 :(得分:1)

问题与提取API和POST请求的工作方式有关。请参阅this SO discussion,了解为什么不能将fs.render()与获取API一起使用,以及this SO discussion,了解如何在客户端获取请求后进行重定向。

将它们放在一起,您可以在获取响应中发送回要重定向的URL,然后使用window.location.replace(...)

从客户端重定向到该URL。