#rk0660-checkout

1 messages · Page 1 of 1 (latest)

left cliff
#

that's third-party, and it's deprecated

wet fractal
#

Ohh I am, that makes sense. Sorry, I'm really new to React so this may be a pointless question, but that does that explain how to handle stripe both client side and server side? I've split my project into a client section and a api section

#

I also don't see a js/react section on that page

left cliff
#

it should explain it, if you're using Checkout though it's mostly server side since all the client has to do is redirect

#

yeah because it's just you make a call to your backend and your backend does a 3xx redirect, you don't need any Javascript on the frontend or to use our library.

#

you can just use a <form action> and do things that way

wet fractal
#

Ahhh alright, I will take a look through that and come back soon if I have some questions, thanks!

#

So just got started on it, and when I try to test it curl -X POST -is "http://localhost:3000/create-checkout-session" -d "" it fails to find a route

#

HTTP/1.1 404 Not Found

#

My node.js is on port 5000 and my react app is on port 3000

left cliff
#

then it would be localhost:5000 that you have to curl since that's your backend

wet fractal
#

Oh my bad, so if I type that in I get no response

#

Is that the same as a success?

#

Or more importantly, when clicking the button on my client, it says Cannot POST /create-checkout-session

left cliff
#

what do the logs in the node.js console say

left cliff
wet fractal
#
curl -X POST -is "http://localhost:5000/create-checkout-session" -d "" -vvv
*   Trying ::1...
* TCP_NODELAY set
* Connection failed
* connect to ::1 port 5000 failed: Connection refused
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connection failed
* connect to 127.0.0.1 port 5000 failed: Connection refused
* Failed to connect to localhost port 5000: Connection refused
* Closing connection 0
left cliff
#

sounds like your Node server isn't running then.

wet fractal
#

It is up the DB is connected and everything

#

I fixed the error, I had to export the router and in my index.js file I run app.use("/api/stripe", stripeRoutes), so when I navigate to localhost:3000/api/stripe/create-checkout-session it's a blank page

#

no checkout though

left cliff
#

not sure what you mean by "navigate".

#

it's an API route, so visiting in a browser (a GET request) wouldn't do much

left cliff
wet fractal
#

Ah nope, clicking the button takes me back to the error about cannot POST to /api/stripe/create-checkout-session

#

This is my frontend:

<Form action="/api/stripe/create-checkout-session" method="post">
                        <SummaryButton> CHECKOUT NOW</SummaryButton>
                    </Form>
#

And my stripe.js file handling the routes

const router = require('express').Router();
const STRIPE_SECRET_KEY_TEST = process.env.STRIPE_SECRET_KEY_TEST;
const stripe = require('stripe')(STRIPE_SECRET_KEY_TEST)

router.post('/create-checkout-session', async (req, res) => {
    const session = await stripe.checkout.sessions.create({
        line_items: [
          {
            price_data: {
              currency: 'usd',
              product_data: {
                name: 'T-shirt',
              },
              unit_amount: 2000,
            },
            quantity: 1,
          },
        ],
        mode: 'payment',
        success_url: 'https://example.com/success',
        cancel_url: 'https://example.com/cancel',
      });
    
      res.redirect(303, session.url);
      
});

module.exports = router;
left cliff
wet fractal
#

How can I prevent that?

left cliff
#

I think that's why the guide I linked uses "proxy": "http://localhost:5000" .

#

alternatively you can change the form to action="http://localhost:5000/api/stripe/create-checkout-session" but that probably has other issues and is not very scalable

wet fractal
#

Ok thanks, I tried the second one and in my node.js console got UnhandledPromiseRejectionWarning: Error: You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details

left cliff
#

sounds like process.env.STRIPE_SECRET_KEY_TEST is not set then.

wet fractal
#

Ok thanks, I'll take some time to properly go through it all and come back if I need

#

I appreciate the help!

wet fractal
#

Hi, just a quick update, trying to first build out the backend and I run:

curl -X POST -is "http://localhost:5000/api/stripe/create-checkout-session" -d ""

My code is:

const router = require('express').Router();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

router.post("/create-checkout-session", async (req, res) => {
    const session = await stripe.checkout.sessions.create({
        line_items: [
          {
            price_data: {
              currency: 'usd',
              product_data: {
                name: 'T-shirt',
              },
              unit_amount: 2000,
            },
            quantity: 1,
          },
        ],
        mode: 'payment',
        success_url: 'https://example.com/success',
        cancel_url: 'https://example.com/cancel',
      });
    
      res.redirect(303, session.url);
});


module.exports = router;
#

My response is : {"type":"StripeAuthenticationError","raw":{"message":"You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY').

#

So do I need to somehow send the sk_test key in the curl req?

left cliff
#

no, you set it in the backend Javascript code.

#

like I said, process.env.STRIPE_SECRET_KEY is probably not set. Did you try console.log-ing it? Do you understand what that line represents?

wet fractal
#

Yeah, when i console.log(process.env.STRIPE_SECRET_KEY) I get sk_test_numbers

left cliff
#

also wait wait wait

#

why do you have stripe.charges.create

#

where did you get that from

#

go back to what you had with await stripe.checkout.sessions.create

wet fractal
#

Oh alright I just reversed it to that now

#

I get in my node.js logs:

(node:3589) UnhandledPromiseRejectionWarning: Error: You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.
    at res.toJSON.then.StripeAPIError.message
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:3589) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
left cliff
#

share the full code including where you console.log-ed the value please

wet fractal
#

Ok one second, I'll make it in a easy way to read

#

Stripe.JS:

const router = require('express').Router();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

router.post("/create-checkout-session", async (req, res) => {
    const session = await stripe.checkout.sessions.create({
        line_items: [
          {
            price_data: {
              currency: 'usd',
              product_data: {
                name: 'T-shirt',
              },
              unit_amount: 2000,
            },
            quantity: 1,
          },
        ],
        mode: 'payment',
        success_url: 'https://example.com/success',
        cancel_url: 'https://example.com/cancel',
      });
    
      res.redirect(303, session.url);
});


module.exports = router;

index.js

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const userRoutes = require("./routes/user");
const cartRoutes = require("./routes/cart");
const stripeRoutes = require("./routes/stripe");
const cors = require("cors");

dotenv.config();
app.use(express.json());
app.use(cors());
app.use("/api/users", userRoutes);
app.use("/api/cart", cartRoutes);
app.use("/api/stripe", stripeRoutes);

mongoose.connect(process.env.MONGO_URL).then(() => console.log("DBConnection Successful!")).catch((err) => {console.log(err);});

app.listen(process.env.PORT || 5000, () => {
    console.log("Backend server is running!");
    console.log(process.env.STRIPE_SECRET_KEY);
});
#

My output (on starting the Node.js server):

Backend server is running!
sk_test_numbers
DBConnection Successful!
left cliff
#

thanks, give me a bit to look

wet fractal
#

No problem, thanks sorry for the trivial questions

left cliff
#

you need to move dotenv.config(); to be before the line where you have const stripeRoutes = require("./routes/stripe"); as far as I know

#

since that's the line that reads your .env file and populates process.env so right now you're registering the Stripe route before that variable has been loaded

wet fractal
#

Ohh I should have seen that, thank you! Now the only error I get is node:3698) UnhandledPromiseRejectionWarning: Error: In order to use Checkout, you must set an account or business name at https://dashboard.stripe.com/account

left cliff
#

yep the error tells you how to resolve that one

wet fractal
#

Oh perfect! So now I get a HTTP/1.1 303 See Other status

#

So now if I were to go to my react app and make that form with a action to that endpoint

#

I should get a stripe checkout page?

#

I got it! Can I pass a payload/parameter with the Form so I can use it in the checkout page? For example I Have a [products] array and I'd like to map over them to display in the checkout page

left cliff
left cliff
wet fractal
#

So I would make a function and prevent the actual form submit, then make a custom post request to the endpoint passing my own products parameters

#

Make sense, thanks for all your help :)