javascript 在React和Express js中使用Stripe Checkout

kr98yfug  于 2023-08-02  发布在  Java
关注(0)|答案(2)|浏览(90)

我试图在我的react应用程序中设置Stripe Checkout,如果用户单击按钮,它将通过Stripe Checkout将他们引导到Stripe的托管结账页面。在前端,它需要会话ID,我应该从我的nodejs/express服务器获取该ID。我仍然是nodejs的新手,需要帮助正确设置它,这样我才能创建一个路由,发送会话ID的正确响应。此外,此设置适用于按月订阅
Server.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;

f1tvaqid

f1tvaqid1#

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

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

字符串

u91tlkcl

u91tlkcl2#

您可以通过将其传递到success URL来获取 checkout 会话ID

const session = await stripe.checkout.sessions.create({
  // other props
  success_url: "http://yoursite.com/order/success?session_id={CHECKOUT_SESSION_ID}",
});

字符串
然后你可以从你的url中选择它作为一个查询参数,并使用它来获得你想要的任何东西,例如,获得订阅…

相关问题