简体   繁体   English

在 React 和 Express js 中使用 Stripe Checkout

[英]Using Stripe Checkout in React and Express js

I'm trying to set up Stripe Checkout in my react application where if the user clicks a button, it will direct them to stripe's hosted checkout page via Stripe Checkout.我正在尝试在我的反应应用程序中设置 Stripe Checkout,如果用户单击按钮,它将通过 Stripe Checkout 将他们引导到 Stripe 托管的结账页面。 On the front end, it requires the session id and I'm suppose to get that id from my nodejs/express server.在前端,它需要会话 ID,我想从我的 nodejs/express 服务器获取该 ID。 I am still a noob at nodejs and need help setting it up properly so I can create a route that sends out the correct response of the session id.我仍然是 nodejs 的菜鸟,需要帮助正确设置它,以便我可以创建一个路由来发送会话 ID 的正确响应。 Also, this setup is for monthly subscriptions此外,此设置适用于每月订阅

Server.js服务器.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结帐.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;

When you create the session object through the Stripe API, you need to return the result back to the frontend.当您通过 Stripe API 创建会话对象时,您需要将结果返回给前端。 Currently you aren't returning anything.目前你没有返回任何东西。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM