'Why is the response (payment Intent) after completing the payment undefined?

myReactApp/functions/index.js

const functions = require("firebase-functions");

const express = require("express");
const cors = require("cors");
const stripe = require('stripe')
('sk_test_**********');

// API 

// App config
const app = express();

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

// API routes
app.get('/', (request, respond) => respond.status(200).send("page is working") );

app.post('/payment/create', async (request, response) => {
    const total = request.query.total;//get the value of total from URL using query

    console.log('payment request recived >>>' , total);

    const paymentIntent = await stripe.paymentIntents.create({
        amount: total,
        currency: 'USD'
    })

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

})

//http://localhost:5001/clone-21937/us-central1/api

// Listen command
exports.api = functions.https.onRequest(app);

myReactApp/src/payment.js

import React, { useEffect, useState } from 'react';
import Orders from './Orders';
import CheckoutProduct from './CheckoutProduct';
import CurrencyFormat from 'react-currency-format';
import { CardElement, useElements, useStripe } from '@stripe/react-stripe-js';
import { collection, addDoc, setDoc } from 'firebase/firestore/lite'
import { Link, useNavigate } from 'react-router-dom';
import { useStateValue } from './StateProvider';
import { db } from './firebase';
import axios from './axios';


const Payment = () => {
    const stripe = useStripe();
    const elements = useElements();
    const navigate = useNavigate();

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

    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 () => {
            const response = await axios({
                method: 'POST',
                url: `/payment/create?total=${subtotal * 100}`
            });
            //clientSecret is the amount to be paid
            //fetching the clientSecret send from response (Index.js)
            setClientSecret(response.data.clientSecret);
        }

        getClientSecret();

    }, [basket]);


    //handle submitting the form
    const handleSubmit = async (event) => {

        event.preventDefault();
        setProcessing(true);
        const payload = await stripe.confirmCardPayment(clientSecret, {
            payment_method: {
                card: elements.getElement(CardElement)
            }

        }).then( ({paymentIntent}) => {
            console.log(paymentIntent);//undefined
            try {
                addDoc(
                    collection(db,'users', user?.uid, 'orders'),{
                        basket:basket
                    }
                )
            }
            catch (error) {
                alert(error.message);
            }

            //empty the basket after order
            dispatch({
                type: 'EMPTY_BASKET'
            })

            setSucceeded(true);
            setProcessing(false);
            setError(null);

            // navigate('/orders');
        })
    }

    const handleChange = (event) => {
        setDisabled(event.empty);
        setError(event.error ? event.error.message : '');
    }

    return (
        
                <div className="payment_sectionTransaction">
                    <form onSubmit={handleSubmit}>
                        <CardElement className='payment_cardElement' onChange={handleChange}/>

                        <CurrencyFormat
                            value={subtotal}
                            prefix={'$'}
                            decimalScale={2}
                            thousandSeparator={true}
                            displayType={'text'}
                            renderText={(value) => {
                                return <>
                                    <p><strong>Amount: {value}</strong></p>
                                </>
                            }} />
                        <button type='submit' disabled={processing || succeeded || disabled} >
                            {processing ? 'Processing..' : 'Confirm Order'}
                        </button>
                    </form>
                </div>
           

       
    )
}

export default Payment

After payment I am trying to get the response-paymentIntent but it shows to be undefined. I can see the payment in the stripe dashboard so may be payment sections is all good but response after the payment is not good. I also get this error in console after payment get done:

POST http://localhost:5001/clone-21937/us-central1/api/payment/create?total=0 net::ERR_FAILED 200



Solution 1:[1]

getClientSecret is async function. You must write code look like

const result = await getClientSecret();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BaoTrung Tran