/
CheckoutForm.tsx
71 lines (61 loc) · 2.13 KB
/
CheckoutForm.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import React, { useState } from 'react'
import CustomDonationInput from '../components/CustomDonationInput'
import { fetchPostJSON } from '../utils/api-helpers'
import { formatAmountForDisplay } from '../utils/stripe-helpers'
import * as config from '../config'
import { useStripe } from '@stripe/react-stripe-js'
const CheckoutForm: React.FunctionComponent = () => {
const [input, setInput] = useState({
customDonation: Math.round(config.MAX_AMOUNT / config.AMOUNT_STEP),
})
const stripe = useStripe()
const handleInputChange: React.ChangeEventHandler<HTMLInputElement> = e =>
setInput({
...input,
[e.currentTarget.name]: e.currentTarget.value,
})
const handleSubmit: React.FormEventHandler<HTMLFormElement> = async e => {
e.preventDefault()
// Create a Checkout Session.
const response = await fetchPostJSON('/api/checkout_sessions', {
amount: input.customDonation,
})
if (response.statusCode === 500) {
console.error(response.message)
return
}
// Redirect to Checkout.
const { error } = await stripe!.redirectToCheckout({
// Make the id field from the Checkout Session creation API response
// available to this file, so you can provide it as parameter here
// instead of the {{CHECKOUT_SESSION_ID}} placeholder.
sessionId: response.id,
})
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `error.message`.
console.warn(error.message)
}
return (
<form onSubmit={handleSubmit}>
<CustomDonationInput
className="checkout-style"
name={'customDonation'}
value={input.customDonation}
min={config.MIN_AMOUNT}
max={config.MAX_AMOUNT}
step={config.AMOUNT_STEP}
currency={config.CURRENCY}
onChange={handleInputChange}
/>
<button
className="checkout-style-background"
type="submit"
disabled={!stripe}
>
Donate {formatAmountForDisplay(input.customDonation, config.CURRENCY)}
</button>
</form>
)
}
export default CheckoutForm