Giter Club home page Giter Club logo

Comments (8)

hahajska avatar hahajska commented on August 26, 2024 2

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

from react-challenge-amazon-clone.

shivasinghal2000 avatar shivasinghal2000 commented on August 26, 2024

`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

from react-challenge-amazon-clone.

ghilaslinz avatar ghilaslinz commented on August 26, 2024

@shivasinghal2000 Did you fix this error ?

from react-challenge-amazon-clone.

haroon437 avatar haroon437 commented on August 26, 2024

@shivasinghal2000 Did you fix this error

from react-challenge-amazon-clone.

nishant334567 avatar nishant334567 commented on August 26, 2024

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

from react-challenge-amazon-clone.

minal322 avatar minal322 commented on August 26, 2024

@shivasinghal2000 Did you fix this error ?

did you fix this ?

from react-challenge-amazon-clone.

Naveen-singla avatar Naveen-singla commented on August 26, 2024

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

from react-challenge-amazon-clone.

MuluKidan avatar MuluKidan commented on August 26, 2024

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.

from react-challenge-amazon-clone.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.