简体   繁体   中英

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. On the front end, it requires the session id and I'm suppose to get that id from my nodejs/express server. 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. Also, this setup is for monthly subscriptions

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;

When you create the session object through the Stripe API, you need to return the result back to the frontend. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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