【问题标题】:Using Stripe Checkout in React and Express js在 React 和 Express js 中使用 Stripe Checkout
【发布时间】:2020-06-25 19:28:33
【问题描述】:

我正在尝试在我的 react 应用程序中设置 Stripe Checkout,如果用户单击一个按钮,它将通过 Stripe Checkout 将他们定向到条带托管的结帐页面。在前端,它需要会话 ID,我想从我的 nodejs/express 服务器获取该 ID。我仍然是 nodejs 的菜鸟,需要帮助正确设置它,以便我可以创建一个发送会话 ID 正确响应的路由。此外,此设置适用于每月订阅

服务器.js

const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const path = require("path");
const stripe = require("stripe")("sk_test_**********************");

if (process.env.NODE_ENV !== "production") require("dotenv").config();

const app = express();
const port = process.env.PORT || 5000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(cors());

if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "client/build")));

  app.get("*", function(req, res) {
    res.sendFile(path.join(__dirname, "client/build", "index.html"));
  });
}

app.post("/charge", (req, res) => {
  (async () => {
    const session = await stripe.checkout.sessions.create({
      payment_method_type: ["card"],
      subscription_data: {
        items: [
          {
            plan: "plan_***********"
          }
        ]
      },
      success_url:
        "https://example.com/success?session_id={CHECKOUT_SESSION_ID}",
      cancel_url: "https://example.com/cancel"
    });
  })();
});

app.listen(port, err => {
  if (err) throw err;
  console.log("Server running on port" + port);
});

Checkout.js

import React, { useState, useEffect } from "react";

const Checkout = ({ price }) => {
  const [isProcessing, setProcessingTo] = useState(false);
  const [checkoutError, setChecoutError] = useState();

let sessionId;

  const stripe = Stripe("pk_test_*******************************");

  useEffect(() => {
    fetch("/charge", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({})
    })
      .then(function(r) {
        return r.json();
      })
      .then(function(response) {
        sessionId = response.id;
      });
  });

  const handleClick = e => {
    e.preventDefault();
    stripe.redirectToCheckout({
      sessionId: sessionId
    });
  };

  return (
    <div>
      <button onClick={handleClick}>Buy</button>
    </div>
  );
};

export default Checkout;

【问题讨论】:

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


    【解决方案1】:

    当您通过 Stripe API 创建会话对象时,您需要将结果返回给前端。目前你没有返回任何东西。

    const session = await stripe.checkout.sessions.create({
        ...
        ...
        ...
    });
    res.send({ id: session.id }); // send an object back with the id
    

    【讨论】:

      猜你喜欢
      • 2021-03-07
      • 2019-10-02
      • 2018-02-08
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 2017-07-22
      • 2017-12-23
      • 2014-05-04
      相关资源
      最近更新 更多