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:
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 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 :)
CodePudding user response:
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 });
}
});
CodePudding user response:
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.