0

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;

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

You can get the checkout session id by passing it to the success url

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

Then you can pick it as a query params from your url and use it to get whatever you want, for instance, get the subscription...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.