This repository was archived by the owner on Feb 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathCheckoutForm.tsx
75 lines (66 loc) · 2.3 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
72
73
74
75
import React, { useState } from 'react';
import CustomDonationInput from '../components/CustomDonationInput';
import StripeTestCards from '../components/StripeTestCards';
import getStripe from '../utils/get-stripejs';
import { fetchPostJSON } from '../utils/api-helpers';
import { formatAmountForDisplay } from '../utils/stripe-helpers';
import * as config from '../config';
const CheckoutForm = () => {
const [loading, setLoading] = useState(false);
const [input, setInput] = useState({
customDonation: Math.round(config.MAX_AMOUNT / config.AMOUNT_STEP),
});
const handleInputChange: React.ChangeEventHandler<HTMLInputElement> = (e) =>
setInput({
...input,
[e.currentTarget.name]: e.currentTarget.value,
});
const handleSubmit: React.FormEventHandler<HTMLFormElement> = async (e) => {
e.preventDefault();
setLoading(true);
// 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 stripe = await getStripe();
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);
setLoading(false);
};
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}
/>
<StripeTestCards />
<button
className="checkout-style-background"
type="submit"
disabled={loading}
>
Donate {formatAmountForDisplay(input.customDonation, config.CURRENCY)}
</button>
</form>
);
};
export default CheckoutForm;