Newer
Older
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { useStripe } from "@stripe/stripe-react-native";
import React, { useEffect, useState } from "react";
import { Alert, Text, Button, SafeAreaView } from "react-native";
export default function CheckoutScreen() {
const { initPaymentSheet, presentPaymentSheet } = useStripe();
const [loading, setLoading] = useState(false);
const [paymentIntentId, setPaymentIntentId] = useState<string>("");
const apiUrl = "http://172.26.7.103:8000";
const userId = "cus_THVVhujjj328BN";
const items = [
{
"id": 1,
"amount": 2
}
];
const fetchPaymentSheetParams = async () => {
const response = await fetch(`${apiUrl}/payments/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"pending_items": items,
"customer_id": userId
})
});
const { paymentIntent, ephemeralKey, customer } = await response.json();
return {
paymentIntent,
ephemeralKey,
customer,
};
};
const initializePaymentSheet = async () => {
const {
paymentIntent,
ephemeralKey,
customer,
} = await fetchPaymentSheetParams();
const { error } = await initPaymentSheet({
merchantDisplayName: "Example, Inc.",
customerId: customer,
customerEphemeralKeySecret: ephemeralKey,
paymentIntentClientSecret: paymentIntent,
allowsDelayedPaymentMethods: false,
});
if (!error) {
setPaymentIntentId(paymentIntent);
setLoading(true);
}
};
const openPaymentSheet = async () => {
const { error } = await presentPaymentSheet();
if (error) {
Alert.alert(`Error code: ${error.code}`, error.message);
} else {
const paymentIntent = `pi_${paymentIntentId.split("_")[1]}`;
const response = await fetch(`${apiUrl}/payments/check/${paymentIntent}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"customer_id": userId
})
});
if (response.status == 200) Alert.alert('Success', 'Your order is confirmed!');
}
};
useEffect(() => {
initializePaymentSheet();
}, []);
return (
<SafeAreaView>
<Text>Payment</Text>
<Button
disabled={!loading}
title="Checkout"
onPress={openPaymentSheet}
/>
</SafeAreaView>
);
}