Files
pawol.nu/components/soutyen/checkout-form.js
T

84 lines
2.3 KiB
JavaScript
Raw Normal View History

import {useState, useEffect} from 'react'
2022-02-19 22:15:03 +04:00
import PropTypes from 'prop-types'
import {
PaymentElement,
useStripe,
useElements
} from '@stripe/react-stripe-js'
import {Button, Container, LinearProgress, Paper} from '@mui/material'
const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3001'
export default function CheckoutForm({validMontant, setError, isLoading, setIsLoading}) {
2022-02-19 22:15:03 +04:00
const stripe = useStripe()
const elements = useElements()
const [isPaymentLoading, setIsPaymentLoading] = useState(false)
const [prices, setPrices] = useState([])
2022-02-19 22:15:03 +04:00
const handleSubmit = async event => {
event.preventDefault()
if (!stripe || !elements) {
return
}
setIsPaymentLoading(true)
const {error} = await stripe.confirmPayment({
elements,
confirmParams: {
return_url: `${SITE_URL}/soutyen`
},
})
if (error.type === 'card_error' || error.type === 'validation_error') {
setError(error.message)
} else {
setError('Une erreur sest produite.')
}
setIsPaymentLoading(false)
}
const handleReady = () => {
setIsLoading(false)
}
useEffect(() => {
const fetchPrices = async () => {
try {
const response = await fetch(`${SITE_URL}/stripe/dons-list`)
const pricesList = await response.json()
setPrices(pricesList)
} catch (error) {
console.error('error', error)
}
}
fetchPrices()
}, [prices])
2022-02-19 22:15:03 +04:00
return (
<Container maxWidth='sm' sx={{marginBottom: 1}}>
<Paper sx={{padding: 2, marginTop: 3}}>
<PaymentElement id='payment-element' onReady={handleReady} />
{!isLoading && (
<Button fullWidth sx={{marginTop: 2}} variant='outlined' disabled={isPaymentLoading || !stripe || !elements} id='submit' onClick={handleSubmit}>
Valider le don de&nbsp;<strong>{prices.find(({id}) => id === validMontant).unit_amount / 100} euros</strong>
2022-02-19 22:15:03 +04:00
</Button>
)}
{isPaymentLoading && (
2022-03-06 10:08:32 +04:00
<LinearProgress size={24} style={{width: '100%', marginTop: 10}} />
2022-02-19 22:15:03 +04:00
)}
</Paper>
</Container>
)
}
CheckoutForm.propTypes = {
2022-03-14 18:59:11 +04:00
validMontant: PropTypes.string.isRequired,
2022-02-19 22:15:03 +04:00
setError: PropTypes.func.isRequired,
isLoading: PropTypes.bool.isRequired,
setIsLoading: PropTypes.func.isRequired
}