71 lines
2.0 KiB
JavaScript
71 lines
2.0 KiB
JavaScript
import {useState} from 'react'
|
||
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({prices, validMontant, setError, isLoading, setIsLoading}) {
|
||
const stripe = useStripe()
|
||
const elements = useElements()
|
||
const [isPaymentLoading, setIsPaymentLoading] = useState(false)
|
||
const amount = prices.find(({id}) => id === validMontant).unit_amount
|
||
|
||
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 s’est produite.')
|
||
}
|
||
|
||
setIsPaymentLoading(false)
|
||
}
|
||
|
||
const handleReady = () => {
|
||
setIsLoading(false)
|
||
}
|
||
|
||
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 paiement de <strong>{amount / 100} euros</strong>
|
||
</Button>
|
||
)}
|
||
{isPaymentLoading && (
|
||
<LinearProgress size={24} style={{width: '100%', marginTop: 10}} />
|
||
)}
|
||
</Paper>
|
||
</Container>
|
||
)
|
||
}
|
||
|
||
CheckoutForm.propTypes = {
|
||
validMontant: PropTypes.string.isRequired,
|
||
prices: PropTypes.array.isRequired,
|
||
setError: PropTypes.func.isRequired,
|
||
isLoading: PropTypes.bool.isRequired,
|
||
setIsLoading: PropTypes.func.isRequired
|
||
}
|