import React, {useState, useEffect} from "react"; import { Button } from "./ui/button"; import { Input } from "./ui/input"; import QRCode from "react-qr-code"; import { Dialog, DialogContent, DialogHeader, DialogTitle} from "./ui/dialog"; import { Toast } from './Toast'; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "./ui/card"; import { FileX, Copy, CheckCircle2, AlertCircle, X } from "lucide-react"; import Loader from "./ui/loader"; const API_URL = 'https://host-api.cs1.hz.siliconpin.com/v1/users/'; export default function MakePayment(){ const [initialOrderData, setInitialOrderData] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const [showQRModal, setShowQRModal] = useState(false); const [showHelpMessage, setShowHelpMessage] = useState(false); const [transactionId, setTransactionId] = useState(''); const [orderIdInput, setOrderIdInput] = useState(''); const [upiPaymentLink, setUpiPaymentLink] = useState(""); const [copied, setCopied] = useState(false); const [getOrderId, setGetOrderId] = useState(); const [saveUpiResponse, setSaveUpiResponse] = useState({ message: '', visible: false, isSuccess: false }); useEffect(() => { const urlParams = new URLSearchParams(window.location.search); const orderId = urlParams.get('orderId'); if (!orderId) { setError('Order ID is missing from URL'); setIsLoading(false); return; } setGetOrderId(orderId); const getInitialOrderData = () => { setIsLoading(true); const formData = new FormData(); formData.append('order_id', orderId); fetch(`${API_URL}?query=get-initiated_payment`, { method: 'POST', body: formData, credentials: 'include' }) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then(data => { if (!data.success) { throw new Error(data.message || 'Failed to initialize payment'); } setInitialOrderData(data); setError(null); // Generate UPI payment link when data is loaded if (data.payment_data?.amount) { const amount = data.payment_data.amount; const upiLink = generateUPILink(amount, data.txn_id); setUpiPaymentLink(upiLink); } }) .catch(error => { setError(error.message || 'Payment failed. Please try again.'); console.error('An error occurred:', error); }) .finally(() => { setIsLoading(false); }); }; getInitialOrderData(); }, []); function generateUPILink(amount, transactionId) { // Replace these with your actual merchant details const merchantUPI = "7001601485@okbizaxis"; const merchantName = "SiliconPin"; const currency = "INR"; // Encode parameters for URL const encodedMerchantName = encodeURIComponent(merchantName); const transactionNote = encodeURIComponent(`Payment for order #${transactionId}`); // Construct UPI payment link return `upi://pay?pa=${merchantUPI}&pn=${encodedMerchantName}&am=${amount}&cu=${currency}&tn=${transactionNote}`; } // waiting payment update // Payment update not recieved if function redirectToPayU() { if (!initialOrderData?.payment_data || !initialOrderData.payment_url) { console.error('Payment data not loaded yet'); alert('Payment information is not ready. Please wait.'); return; } // Create a form dynamically const form = document.createElement('form'); form.method = 'POST'; form.action = initialOrderData.payment_url; form.style.display = 'none'; Object.entries(initialOrderData.payment_data).forEach(([key, value]) => { const input = document.createElement('input'); input.type = 'text'; input.name = key; input.value = value; form.appendChild(input); console.log(`Adding field: ${key}=${value}`); }); document.body.appendChild(form); form.submit(); } useEffect(() => { let timer; if (showQRModal) { setShowHelpMessage(false); timer = setTimeout(() => { setShowHelpMessage(true); }, 2000); } return () => clearTimeout(timer); // Cleanup on unmount or when modal closes }, [showQRModal]); function handleQRPaymentClick() { if (!upiPaymentLink) { alert('Payment information is not ready. Please wait.'); return; } setShowQRModal(true); } const handleCopy = () => { navigator.clipboard.writeText(getOrderId) .then(() => { setCopied(true); setTimeout(() => setCopied(false), 1000); // Reset after 1 second }) .catch(err => { console.error('Failed to copy text: ', err); }); }; const handlePayPalPayment = () => { const rawInrAmount = initialOrderData.payment_data?.amount || 0; const exchangeRate = 80; const convertedUSD = rawInrAmount / exchangeRate; const usdAmount = Math.max(convertedUSD, 1).toFixed(2); const paypalUrl = `https://www.paypal.com/paypalme/dwdconsultancy/${usdAmount}`; window.open(paypalUrl, '_blank'); }; const handleSaveUPIPayment = async () => { try { const response = await fetch(`${API_URL}?query=save-upi-payment`, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ orderId: orderIdInput, transactionId: transactionId }) }); const data = await response.json(); if (data.success === true) { setSaveUpiResponse({ message: `Transaction ID ${transactionId} saved. We'll contact you shortly.`, visible: true, isSuccess: true }); setShowHelpMessage(false); } } catch (error) { console.error('Error:', error); setSaveUpiResponse({ message: 'Failed to save payment details. Please try again.', visible: true, isSuccess: false }); } }; if (isLoading) { return ; } if(!initialOrderData){ return (

No bill was found. Click here to go to your profile.

); } if (error) { return
Error: {error}
; } return (

Complete Your Payment

{initialOrderData && (
Order ID: {initialOrderData.txn_id}
Amount: ₹{initialOrderData.payment_data?.amount}
)}
Pay Using:
Banking Service by DWD Consultancy Services (0% Processing Fee)
OR
{/* 2% Payment Gateway Charge */} {/* Add this divider and PayPal button */} {/*
OR
*/} {/* 3.5% Payment Processing Fee */}
{/* QR Code Modal */} {setShowQRModal(open); if (!open) {setShowHelpMessage(false);}}}> Scan QR Code to Pay

Scan this QR code with any UPI app to complete your payment

{showHelpMessage && (

If you haven't received payment confirmation, please share your Order Id & transaction ID with us.

setOrderIdInput(e.target.value)} placeholder="Enter your Order ID" className="w-full p-2 border border-gray-300 rounded-md text-sm mb-2" /> setTransactionId(e.target.value)} placeholder="Enter your transaction ID" className="w-full p-2 border border-gray-300 rounded-md text-sm mb-2" />
)} {saveUpiResponse.visible && (
{saveUpiResponse.isSuccess ? ( ) : ( )}

{saveUpiResponse.message}

)}
); } // Transaction ID ${transactionId} saved. We'll contact you shortly.