Skip to content

Orders page is not opening on clicking buy now #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
shivasinghal2000 opened this issue Dec 7, 2020 · 8 comments
Open

Orders page is not opening on clicking buy now #12

shivasinghal2000 opened this issue Dec 7, 2020 · 8 comments

Comments

@shivasinghal2000
Copy link

image

After clicking on buy now button it is showing processing only

@shivasinghal2000
Copy link
Author

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

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(() => {
//generate the special stripe secret which allows us to charge a customer
const getClientSecret = async () => {
// axios is way to make request (pull request, push request) basicaly it allows us to interact with API's
const response = await axios({
method: 'post',
// Stripe excpects the total in a currencies subunits
url: /payments/create?total=${getBasketTotal(basket) * 100}
})
setClientSecret(response.data.clientSecret)
}
getClientSecret()
}, [basket])

console.log('THE SECRET IS >>>', clientSecret)
console.log('👱', user)

const handleSubmit = async (event) => {
// stripe functions is used here
// console.log("heyr")
event.preventDefault()
setProcessing(true)

const payload = await stripe.confirmCardPayment(clientSecret,{
  payment_method: {
    card: elements.getElement(CardElement)
  }
}).then(({ paymentIntent }) => {
  // paymentIntent = payment confirmation
  
  db
  .collection('users')
  .doc(user?.uid)
  .collection('orders')
  .doc(paymentIntent.id)
  .set({
    basket: basket,
    amount: paymentIntent.amount,
    created: paymentIntent.created
  })
  
  setSucceeded(true)
  setError(null)
  setProcessing(false)
  
  dispatch({
    type: 'EMPTY_BASKET'
  })
  history.replace('/orders')
})

}

const handleChange = event => {
// List for changes in the CardElement and display any errors as the customer types their card details
setDisabled(event.empty)
setError(event.error ? event.error.message : "")
}

return (




Checkout (
{basket?.length} items
)

    {/* Payment section - delivery address */}
    <div className='payment_section'>
      <div className='payment_title'>
        <h3>Delivery Address</h3>
      </div>
      <div className='payment_address'>
        <p>{user?.email}</p>
        <p>IGDTUW College</p>
        <p>Kashmere Gate</p>
      </div>
    </div>
    {/* Payment section - review Items */}
    <div className='payment_section'>
        <div className='payment_title'>
            <h3>Review items and delivery</h3>
        </div>
        <div className='payment_items'>
            {basket.map(item => (
                <CheckoutProduct 
                    key={item.id}
                    id={item.id}
                    image={item.image}
                    title={item.title}
                    price={item.price}
                    rating={item.rating}
                />
            ))}
        </div>
    </div>
    {/* Payment section - Payment method */}
    <div className='payment_section' >
       <div className='payment_title'>
         <h3>Payment Method</h3>
       </div>
       <div className='payment_details'>
         {/* Stripe is used here  */}
         <form onSubmit={handleSubmit}>
              <CardElement onChange={handleChange} />
              <div className='payment_priceContainer'>
              <CurrencyFormat
                renderText={(value) => (
                  <h3>Order Total: {value}</h3>
                )}
                decimalScale={2}
                value={getBasketTotal(basket)}
                displayType={'text'}
                thousandSeparator={true}
                prefix={'$'}
              />
              <button disabled={processing || disabled || succeeded} >
                <span>{processing ? <p>Processing</p> : "Buy Now"}</span>
              </button>
              </div>
              {/* Error */}
                {error && <div>{error}</div>}
         </form>
       </div>
    </div>
  </div>
</div>

)
}

export default Payment
`
This is my code of Payment.js

@hahajska
Copy link

hahajska commented Jan 9, 2021

Hello, did you fix it? if yes, let me know how please

@ghilaslinz
Copy link

@shivasinghal2000 Did you fix this error ?

@haroon437
Copy link

@shivasinghal2000 Did you fix this error

@nishant334567
Copy link

@shivasinghal2000 hey are you able to do the payment and rendering orders page? Please help if you already fixed it

@minal322
Copy link

minal322 commented Aug 1, 2022

@shivasinghal2000 Did you fix this error ?

did you fix this ?

@Naveen-singla
Copy link

Naveen-singla commented Sep 26, 2022

guys if you are facing issue regarding payments then try doing debugging using stripe account when you try to make a payment see what kind of error you are getting and also try console logging the client secret

majorly i faced issue during the payment are is you have to use metadata when you are trying to make an paymentintent

app.post("/payments/create", async (request, response) => {
  const total = request.query.total;
  console.log("Payment Request Recieved BOOM!!! for this amount >>>", total);
  const paymentIntent = await stripe.paymentIntents.create({
    amount: total, // subunits of the currency
    currency: "inr",
    metadata: { integration_check: "accept_a_payment" },
  });
  response.status(201).send({
    clientSecret: paymentIntent.client_secret,
  });
}); 

and we have to use useNavigate instead of useHistory

@MuluKidan
Copy link

I am facing exactly the same problem, the buy now button is stuck on Processing and not navigating to the Orders page. I did replace the replacehistory ('/orders') line of code with navigate('/orders').If anyone figured out the solution i would appreciate it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants