1

I'm new to using axios and stripe and I'm encountering some issues. When I try to make a post request with axios I receive this error:

This is the error I receive when making a post request

Perhaps my endpoint is incorrect. I'm not sure. Here is my code in Payments.js:


import React,{useState, useEffect} from 'react'
import CheckoutProduct from './CheckoutProduct';
import './Payment.css';
import {useStateValue} from './StateProvider';
import {Link, useHistory} from 'react-router-dom';
import {CardElement, useStripe, useElements} from "@stripe/react-stripe-js";
import CurrencyFormat from "react-currency-format";
import {getBasketTotal} from "./reducer";
import axios from './axios';


function Payment() {

    const [{basket,user}, dispatch] = useStateValue();
    const history = useHistory();

    const stripe = useStripe();
    const elements = useElements();
    
    const [succeeded, setSucceeded] = useState(false);
    const [processing, setProcessing] = useState("");
    const [error,setError] = useState(null);
    const [disabled,setDisabled] = useState(true);
    const [clientSecret,setClientSecret] = useState(true);

    useEffect(() => {
       
        const getClientSecret = async () => {
            try {
            const response = await axios({
                method: 'post',
                url: `/payments/create?total=${getBasketTotal(basket)*100}` 
            });
           
            console.log("THIS IS THE RESPONSE", response);
            setClientSecret(response.data.clientSecret);
                 }
              catch (error) {
                console.log("THIS IS THE ERROR", error);
                }
        }
        
        getClientSecret();

    },[basket]);

    console.log('THE CLIENT SECRET >>>', clientSecret);

And here is my middleware code in index.js:

const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
const stripe = require("stripe")("/* my secret stripe api key is here */");

const app = express();

app.use(cors({origin: true}));
app.use(express.json());


app.get("/", (request, response) => response.status(200).send
("hello world"));

app.post("/payments/create/", async (request, response) => {
  const total = request.params.total;
  console.log("Payment Request Received >>>", total);

  const paymentIntent = await stripe.paymentIntents.create({
    amount:total, 
    currency:"usd",
    });
    response.status(201).send({
        clientSecret: paymentIntent.client_secret,
    })
});

exports.api = functions.https.onRequest(app);


Here is my axios.js file:

import axios from "axios";

const instance = axios.create({
    baseURL: 'http://127.0.0.1:5001/clone-bfd8a/us-central1/api'
});

export default instance;

I was reviewing the post endpoint in my Payments.js file to see if it was correct. Then I checked my middleware in index.js to see if it coincided with my endpoint in Payment.js. To me, the endpoints seem correct. I was expecting that the application show the clientSecret but instead I got the axios Network Error.

I also received this error in my terminal: It states that the 'amount' parameter is missing

It says the 'amount' parameter is missing but I'm not sure why it says that because I included it in the post middleware route.

I think the error may be in Payments.js where it says:

setClientSecret(response.data.clientSecret);

Maybe response.data.clientSecret doesn't exist.

I'm also thinking the error is in index.js where it says:


clientSecret: paymentIntent.client_secret,

Perhaps client_secret is not defined by stripe. I'm not sure. Any ideas why I'm receiving this Axios network error? Any help is appreciated! Thanks in advance :)

UPDATE:

So it seems to be kind of working now. I changed req.params.total to req.query.total in my middleware post route in index.js:

enter image description here

But it still seems to be acting kind of weird: When I first start the application, I get the error as mentioned above. However, after waiting a couple of minutes, I am able to successfully make a post request with axios. Is it possible that the frontend and backend need to take some time to be synchronized? Could it be that the error is happening because the basket variable is empty at first and then axios tries to make the post request? Thanks in advance!

2 Answers 2

1

I think your endpoint configuration should be

app.post("/payments/create", ...

Instead of

app.post("/payments/create/", ...

Also, your endpoint is dependent on the execution of a 3rd-party service (stripe) so you better add some error handling as well. In short:

app.post("/payments/create/", async (request, response) => {
  const total = request.params.total;
  console.log("Payment Request Received >>>", total);
  try {
    const paymentIntent = await stripe.paymentIntents.create({
      amount:total, 
      currency:"usd",
      });
      response.status(201).send({
        clientSecret: paymentIntent.client_secret,
      });
  } catch (error) {
      response.status(500).send({ error: error.message });
  }
});
Sign up to request clarification or add additional context in comments.

Comments

0

This error is of stripe, total must be in cents (100 for $ 1 dolar)


const paymentIntent = await stripe.paymentIntents.create({
          amount: total,
          currency: "usd",
          payment_method_types: ["card"],
          description: "Buy a xxxx"
          confirm: true,
          });

          if (paymentIntent) {
              if (
                  paymentIntent.status === "requires_action" &&
                  paymentIntent.next_action.type === "use_stripe_sdk"
                  ) {

                    response.status(201).send({
                       clientSecret: paymentIntent.client_secret,
                    })

                  } else if (paymentIntent.status === "succeeded") {
                         
                     response.status(200).send({
                      message: "success"
                     })
                      
                  } else {
                     console.log("Invalid PaymentIntent status");
                  }
             } else {
                   console.log("Invalid PaymentIntent status");
             }

Please validate error of paymentIntent (Stripe), when an error appears in stripe, axios cannot continue and show Network Error.

3 Comments

Hey Camilo thanks for your comment! I made sure the total was in cents because in my Payments.js I multiplied /payments/create?total=${getBasketTotal(basket)*100} . So im not sure why Stripe is giving an error
This error stripe: "parameter missing" Some parameter is missing, but I'm wondering if the required are already set and only the optional ones remain. I use : amount, currency, payment_method_types, customer, payment_method, description, metadata, confirm. Maybe useEffect is executed more than once and the first time sends empty values
Ok well I got it to kind of work. I made an update on my post. It seems that I got it to kind of work. Im able to successfully make a post request. But it doesn't seem to work when I first run my application. Only when I make some coding change in the useEffect() function does it start to work. Or if I wait a couple of minutes, it begins to work. Does it have something to do when the basket variable is empty? Or does the frontend and backend need some time to be synchronized?

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.