instead of rental data in local storage, using stripe metadata
This commit is contained in:
@@ -10,6 +10,8 @@ const CheckoutReturn: React.FC = () => {
|
||||
>("loading");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [processing, setProcessing] = useState(false);
|
||||
const [itemId, setItemId] = useState<string | null>(null);
|
||||
const [sessionMetadata, setSessionMetadata] = useState<any>(null);
|
||||
const hasProcessed = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -27,31 +29,32 @@ const CheckoutReturn: React.FC = () => {
|
||||
checkSessionStatus(sessionId);
|
||||
}, [searchParams]);
|
||||
|
||||
const createRental = async () => {
|
||||
const createRental = async (metadata: any) => {
|
||||
try {
|
||||
// Get rental data from localStorage (set before payment)
|
||||
const rentalDataString = localStorage.getItem("pendingRental");
|
||||
|
||||
if (!rentalDataString) {
|
||||
console.error("No rental data found in localStorage");
|
||||
throw new Error("No rental data found in localStorage");
|
||||
if (!metadata || !metadata.itemId) {
|
||||
throw new Error("No rental data found in Stripe metadata");
|
||||
}
|
||||
|
||||
const rentalData = JSON.parse(rentalDataString);
|
||||
// Convert metadata back to proper types
|
||||
const rentalData = {
|
||||
itemId: metadata.itemId,
|
||||
startDate: metadata.startDate,
|
||||
endDate: metadata.endDate,
|
||||
startTime: metadata.startTime,
|
||||
endTime: metadata.endTime,
|
||||
totalAmount: parseFloat(metadata.totalAmount),
|
||||
deliveryMethod: metadata.deliveryMethod,
|
||||
};
|
||||
|
||||
const response = await rentalAPI.createRental(rentalData);
|
||||
|
||||
// Clear the pending rental data
|
||||
localStorage.removeItem("pendingRental");
|
||||
localStorage.removeItem("lastItemId");
|
||||
|
||||
return response;
|
||||
} catch (error: any) {
|
||||
const errorMessage =
|
||||
error.response?.data?.message ||
|
||||
error.message ||
|
||||
"Failed to create rental";
|
||||
console.error("Throwing error:", errorMessage);
|
||||
console.error("Rental creation error:", errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
};
|
||||
@@ -63,12 +66,18 @@ const CheckoutReturn: React.FC = () => {
|
||||
// Get checkout session status
|
||||
const response = await stripeAPI.getCheckoutSession(sessionId);
|
||||
|
||||
const { status: sessionStatus, payment_status } = response.data;
|
||||
const { status: sessionStatus, payment_status, metadata } = response.data;
|
||||
|
||||
// Store metadata for retry functionality
|
||||
setSessionMetadata(metadata);
|
||||
if (metadata?.itemId) {
|
||||
setItemId(metadata.itemId);
|
||||
}
|
||||
|
||||
if (sessionStatus === "complete" && payment_status === "paid") {
|
||||
// Payment was successful - now create the rental
|
||||
try {
|
||||
const rentalResult = await createRental();
|
||||
const rentalResult = await createRental(metadata);
|
||||
setStatus("success");
|
||||
} catch (rentalError: any) {
|
||||
// Payment succeeded but rental creation failed
|
||||
@@ -95,7 +104,6 @@ const CheckoutReturn: React.FC = () => {
|
||||
|
||||
const handleRetry = () => {
|
||||
// Go back to the item page to try payment again
|
||||
const itemId = localStorage.getItem("lastItemId");
|
||||
if (itemId) {
|
||||
navigate(`/items/${itemId}`);
|
||||
} else {
|
||||
@@ -106,7 +114,7 @@ const CheckoutReturn: React.FC = () => {
|
||||
const handleRetryRentalCreation = async () => {
|
||||
setProcessing(true);
|
||||
try {
|
||||
await createRental();
|
||||
await createRental(sessionMetadata);
|
||||
setStatus("success");
|
||||
setError(null);
|
||||
} catch (error: any) {
|
||||
|
||||
103
frontend/src/components/StripePaymentForm.tsx
Normal file
103
frontend/src/components/StripePaymentForm.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
import React, { useState, useEffect, useCallback, useRef } from "react";
|
||||
import { loadStripe } from "@stripe/stripe-js";
|
||||
import {
|
||||
EmbeddedCheckoutProvider,
|
||||
EmbeddedCheckout,
|
||||
Elements,
|
||||
useStripe,
|
||||
useElements,
|
||||
} from "@stripe/react-stripe-js";
|
||||
import { stripeAPI } from "../services/api";
|
||||
|
||||
const stripePromise = loadStripe(
|
||||
process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY || ""
|
||||
);
|
||||
|
||||
interface PaymentFormProps {
|
||||
itemName: string;
|
||||
total: number;
|
||||
rentalData: any;
|
||||
onSuccess: () => void;
|
||||
onError: (error: string) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const PaymentForm: React.FC<PaymentFormProps> = ({
|
||||
itemName,
|
||||
total,
|
||||
rentalData,
|
||||
onSuccess,
|
||||
onError,
|
||||
disabled,
|
||||
}) => {
|
||||
// const stripe = useStripe();
|
||||
// const elements = useElements();
|
||||
// const [processing, setProcessing] = useState(false);
|
||||
const [clientSecret, setClientSecret] = useState<string>("");
|
||||
const hasCreatedSession = useRef(false);
|
||||
|
||||
const createCheckoutSession = useCallback(async () => {
|
||||
if (hasCreatedSession.current) return;
|
||||
|
||||
try {
|
||||
hasCreatedSession.current = true;
|
||||
const return_url = `${window.location.origin}/checkout/return?session_id={CHECKOUT_SESSION_ID}`;
|
||||
|
||||
const requestData = {
|
||||
itemName,
|
||||
total,
|
||||
return_url,
|
||||
rentalData,
|
||||
};
|
||||
|
||||
const response = await stripeAPI.createCheckoutSession(requestData);
|
||||
|
||||
setClientSecret(response.data.clientSecret);
|
||||
} catch (error: any) {
|
||||
hasCreatedSession.current = false; // Reset on error so it can be retried
|
||||
onError(
|
||||
error.response?.data?.error || "Failed to create checkout session"
|
||||
);
|
||||
}
|
||||
}, [itemName, total, rentalData, onError]);
|
||||
|
||||
useEffect(() => {
|
||||
if (itemName && total > 0 && !clientSecret) {
|
||||
createCheckoutSession();
|
||||
}
|
||||
}, [itemName, total, clientSecret, createCheckoutSession]);
|
||||
|
||||
return (
|
||||
<div id="checkout">
|
||||
{clientSecret && (
|
||||
<EmbeddedCheckoutProvider
|
||||
key={clientSecret}
|
||||
stripe={stripePromise}
|
||||
options={{ clientSecret }}
|
||||
>
|
||||
<EmbeddedCheckout />
|
||||
</EmbeddedCheckoutProvider>
|
||||
)}
|
||||
{!clientSecret && (
|
||||
<div className="text-center">
|
||||
<div className="spinner-border" role="status">
|
||||
<span className="visually-hidden">Loading payment...</span>
|
||||
</div>
|
||||
<p className="mt-2">Preparing payment...</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
interface StripePaymentFormProps extends PaymentFormProps {}
|
||||
|
||||
const StripePaymentForm: React.FC<StripePaymentFormProps> = (props) => {
|
||||
return (
|
||||
<Elements stripe={stripePromise}>
|
||||
<PaymentForm {...props} />
|
||||
</Elements>
|
||||
);
|
||||
};
|
||||
|
||||
export default StripePaymentForm;
|
||||
Reference in New Issue
Block a user