Uber_Clone/components/Payment.tsx

82 lines
2.6 KiB
TypeScript

import { Alert, Text, View } from "react-native";
import CustomButton from "./CustomButton";
import tw from "twrnc";
import { PaymentMethod, PaymentSheetError, useStripe } from "@stripe/stripe-react-native";
import { useState, useEffect } from "react";
import { fetchAPI } from "@/lib/fetch";
import { PaymentProps } from "@/types/type";
const Payment = ({fullName,email,amount,driverId,rideTime}:PaymentProps) => {
const [success, setSuccess] = useState(false);
const { initPaymentSheet, presentPaymentSheet } = useStripe();
const confirmHandler = async (paymentMethod,_, intentCreationCallback) => {
const {paymentIntent,customer} = await fetchAPI("/(api)/(stripe)/create",{
method:"POST",
headers:{
"Content-Type": "application/json",
},
body:JSON.stringify({
name:fullName || email.split("@")[0],
email: email,
amount: amount,
paymentMethodId : paymentMethod.id,
}),
},
);
if(paymentIntent.client_sercet){
const {result} = await fetchAPI ("/(api)/(stripe)/pay",{
method:"POST",
headers:{
"Content-Type":"application/json",
},
body: JSON.stringify({
payment_method_id:paymentMethod.id,
payment_intent_id:paymentIntent.id,
customer_id:customer,
}),
});
if (result.client_sercet) {
//ride/create
}
}
const { clientSercet, error } = await response.json();
if(clientSercet){
intentCreationCallback({clientSercet})
}
else{
intentCreationCallback({error})
}
}
const initializePaymentSheet = async () => {
const { error } = await initPaymentSheet({
merchantDisplayName: "Example,Inc.",
intentConfiguration: {
mode: {
amount: 1099,
currencyCode: "USD",
},
confirmHandler: confirmHandler
}
});
if (error) {
//handle error
}
};
const openPaymentSheet = async () => {
await initializePaymentSheet();
const { error } = await presentPaymentSheet();
if (error) {
Alert.alert(`Error code: ${error.code}`, error.message);
}
else {
setSuccess(true);
}
};
return (
<>
<CustomButton title="Confirm Ride" style={tw`my-10`} onPress={openPaymentSheet} />
</>
)
};
export default Payment;