-
Notifications
You must be signed in to change notification settings - Fork 0
/
Checkout.js
60 lines (49 loc) · 1.46 KB
/
Checkout.js
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
import React from 'react';
import { View, Alert } from 'react-native';
import { useStripe } from '@stripe/stripe-react-native';
import { Button } from '../components/Button';
const API_URL = 'https://plastic-wry-bladder.glitch.me';
export const Checkout = () => {
const { initPaymentSheet, presentPaymentSheet } = useStripe();
const [clientSecret, setClientSecret] = React.useState();
const fetchPaymentSheetParams = async () => {
const response = await fetch(`${API_URL}/checkout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const { paymentIntent } = await response.json();
return {
paymentIntent,
};
};
const initializePaymentSheet = async () => {
const { paymentIntent } = await fetchPaymentSheetParams();
const { error } = await initPaymentSheet({
paymentIntentClientSecret: paymentIntent,
});
if (!error) {
setClientSecret(paymentIntent);
}
};
const openPaymentSheet = async () => {
if (!clientSecret) {
return;
}
const { error } = await presentPaymentSheet({ clientSecret });
if (error) {
Alert.alert(`Error code: ${error.code}`, error.message);
} else {
Alert.alert('Success', 'Your order is confirmed!');
}
};
React.useEffect(() => {
initializePaymentSheet();
}, []);
return (
<View style={{ padding: 10 }}>
<Button onPress={openPaymentSheet}>Checkout</Button>
</View>
);
};