UNPKG

deepvue-digilocker-react-sdk

Version:

A SDK powered by Deepvue for DigiLocker authentication flows

1,208 lines (1,205 loc) 45.3 kB
import { useState, useEffect } from 'react'; import { Box, useTheme, Fade, Paper, Typography, CircularProgress, Chip, Button, Stack, Divider, useMediaQuery, alpha, Alert } from '@mui/material'; import { createSvgIcon } from '@mui/material/utils'; import { jsx, jsxs, Fragment } from 'react/jsx-runtime'; import axios from 'axios'; import { styled } from '@mui/material/styles'; // src/components/FlowSelector.tsx var AccountBox_default = createSvgIcon(/* @__PURE__ */ jsx("path", { d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-7 3c1.93 0 3.5 1.57 3.5 3.5S13.93 13 12 13s-3.5-1.57-3.5-3.5S10.07 6 12 6m7 13H5v-.23c0-.62.28-1.2.76-1.58C7.47 15.82 9.64 15 12 15s4.53.82 6.24 2.19c.48.38.76.97.76 1.58z" }), "AccountBox"); var Cloud_default = createSvgIcon(/* @__PURE__ */ jsx("path", { d: "M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96" }), "Cloud"); var CloudQueue_default = createSvgIcon(/* @__PURE__ */ jsx("path", { d: "M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96M19 18H6c-2.21 0-4-1.79-4-4s1.79-4 4-4h.71C7.37 7.69 9.48 6 12 6c3.04 0 5.5 2.46 5.5 5.5v.5H19c1.66 0 3 1.34 3 3s-1.34 3-3 3" }), "CloudQueue"); var client = axios.create({ baseURL: import.meta.env.VITE_API_URL || "https://production.deepvue.tech", headers: { "Content-Type": "application/json" } }); async function initiateDigiLockerSession(apiKey, clientId, redirectUrl) { const res = await client.post( "/v1/kyc/digilocker/initiate-session", { consent: "Y", purpose: "KYC", redirect_url: redirectUrl }, { headers: { "x-api-key": apiKey, "client-id": clientId } } ); return res.data; } async function getDigiLockerAccessToken(transactionId, code, apiKey, clientId) { const res = await client.post( "/v1/kyc/digilocker/access-token", { consent: "Y", purpose: "KYC", initial_deepvue_transaction_id: transactionId, digilocker_code: code }, { headers: { "x-api-key": apiKey, "client-id": clientId } } ); return res.data; } async function getEAadhaarData(transactionId, apiKey, clientId) { const res = await client.post( "/v1/kyc/digilocker/eaadhaar", { consent: "Y", purpose: "KYC", initial_deepvue_transaction_id: transactionId }, { headers: { "x-api-key": apiKey, "client-id": clientId } } ); return res.data; } async function initiateSession(apiKey, clientId) { const res = await client.get( "/v2/ekyc/aadhaar/sdk/initiate-session", { headers: { "x-api-key": apiKey, "client-id": clientId } } ); return res.data; } async function updateSessionStatus(sessionId, status, apiKey, clientId, aadhaar_reference_id) { const params = { session_id: sessionId, status }; const res = await client.get( `/v2/ekyc/aadhaar/sdk/update-session`, { params, headers: { "x-api-key": apiKey, "client-id": clientId } } ); return res.data; } async function getSessionStatus(sessionId, apiKey, clientId) { const res = await client.get( `/v2/ekyc/aadhaar/sdk/session-status`, { params: { session_id: sessionId }, headers: { "x-api-key": apiKey, "client-id": clientId } } ); return res.data; } // src/assets/Logo.svg?base64 var Logo_default = 'data:image/svg+xml,<svg width="77" height="90" viewBox="0 0 77 90" fill="none" xmlns="http://www.w3.org/2000/svg">%0A<path d="M19.5312 12.0884L38.3566 0.972656V23.2307L19.5312 12.0884Z" fill="%23EA637D"/>%0A<path d="M0.679688 23.2302L19.5311 12.0879V34.3459L0.679688 23.2302Z" fill="%23E84278"/>%0A<path d="M0.679688 45.4885V23.2305L19.5311 34.3462L0.679688 45.4885Z" fill="%23EA637D"/>%0A<path d="M57.2029 12.0879V34.3459L38.3516 23.2302L57.2029 12.0879Z" fill="%23CE78C2"/>%0A<path d="M38.3516 0.972656L57.2029 12.0884L38.3516 23.2307V0.972656Z" fill="%23E84278"/>%0A<path d="M76.0623 23.2305V45.4885L57.2109 34.3462L76.0623 23.2305Z" fill="%23CE78C2"/>%0A<path d="M57.2109 12.0879L76.0623 23.2302L57.2109 34.3459V12.0879Z" fill="%236B2B80"/>%0A<path d="M76.0623 45.4863V67.7178L57.2109 56.602L76.0623 45.4863Z" fill="%23CE78C2"/>%0A<path d="M57.2109 56.6035L76.0623 67.7192L57.2109 78.8615V56.6035Z" fill="%236B2B80"/>%0A<path d="M38.3566 89.9787L19.5312 78.863L38.3566 67.7207V89.9787Z" fill="%23EA637D"/>%0A<path d="M38.3516 67.7207L57.4818 78.8239L38.3516 89.9787V67.7207Z" fill="%23E84278"/>%0A<path d="M0.679688 45.488L19.5311 34.3457V56.6037L0.679688 45.488Z" fill="%23FF83B0"/>%0A<path d="M0.679688 67.7178V45.4863L19.5311 56.602L0.679688 67.7178Z" fill="%23CE78C2"/>%0A<path d="M19.5311 78.8615L0.679688 67.7192L19.5311 56.6035V78.8615Z" fill="%236B2B80"/>%0A<path d="M38.3906 67.7996L57.4942 56.7461V78.8232L38.3906 67.7996Z" fill="%23CE78C2"/>%0A<path d="M76.1687 45.4177L57.6864 34.3984L57.5 56.7467L76.1687 45.4177Z" fill="%23FF83B0"/>%0A</svg>%0A'; var Logo = () => /* @__PURE__ */ jsx( Box, { component: "img", src: Logo_default, alt: "DeepVue Logo", sx: { height: 30, width: "auto", filter: "drop-shadow(0px 2px 4px rgba(0,0,0,0.1))", transition: "transform 0.2s ease", "&:hover": { transform: "scale(1.05)" } } } ); var FlowSelector = ({ apiKey, clientId, onSelectAadhaar, onSelectDigiLocker, autoDetectCallback = true, singleFlow, showFlowSelector }) => { const theme = useTheme(); const sdkCallbackUrl = `${window.location.origin}/callback.html`; const [isRedirecting, setIsRedirecting] = useState(false); const [sessionId, setSessionId] = useState(null); const [sessionReady, setSessionReady] = useState(false); useEffect(() => { const initializeSession = async () => { setSessionReady(false); try { const existingSessionId = localStorage.getItem("deepvue_session_id"); if (existingSessionId) { try { const sessionStatus = await getSessionStatus( existingSessionId, apiKey, clientId ); if (sessionStatus.status === "aadhaar_otp_send_success" && sessionStatus.aadhaar_reference_id) { const nowMs = Date.now(); const expMs = sessionStatus.aadhaar_reference_id_exp; if (expMs && nowMs < expMs) { setSessionId(existingSessionId); setSessionReady(true); return; } else { localStorage.removeItem("deepvue_session_id"); } } else if (sessionStatus.status === "aadhaar_otp_verification_success" || sessionStatus.status === "digilocker_success") { localStorage.removeItem("deepvue_session_id"); } } catch (statusError) { console.error("Failed to check session status:", statusError); localStorage.removeItem("deepvue_session_id"); } } const response = await initiateSession(apiKey, clientId); if (response?.session_id) { localStorage.setItem("deepvue_session_id", response.session_id); setSessionId(response.session_id); setSessionReady(true); } else { console.error("No session_id in response:", response); setSessionReady(false); } } catch (error) { console.error("Failed to initialize session:", error); if (error instanceof Error && error.message.includes("already in the required status")) { const existing = localStorage.getItem("deepvue_session_id"); if (existing) { setSessionId(existing); setSessionReady(true); return; } } localStorage.removeItem("deepvue_session_id"); setSessionId(null); setSessionReady(false); } }; initializeSession(); }, [apiKey, clientId]); useEffect(() => { if (!autoDetectCallback) return; const checkDigiLockerCallback = () => { const callbackReceived = sessionStorage.getItem( "digilocker_callback_received" ); const flowActive = sessionStorage.getItem("digilocker_flow_active"); if (callbackReceived === "true" && flowActive === "true") { if (onSelectDigiLocker) onSelectDigiLocker(); return; } const urlParams = new URLSearchParams(window.location.search); const code = urlParams.get("code"); const state = urlParams.get("state"); if (code && state) { sessionStorage.setItem("digilocker_callback_code", code); sessionStorage.setItem("digilocker_callback_state", state); sessionStorage.setItem("digilocker_callback_received", "true"); sessionStorage.setItem("digilocker_flow_active", "true"); sessionStorage.setItem("digilocker_api_key", apiKey); sessionStorage.setItem("digilocker_client_id", clientId); window.history.replaceState( {}, document.title, window.location.pathname ); if (onSelectDigiLocker) onSelectDigiLocker(); return; } }; checkDigiLockerCallback(); }, [autoDetectCallback, onSelectDigiLocker, apiKey, clientId]); const handleDigilocker = async () => { if (!sessionReady || !sessionId) { alert( "Session initialization failed. Please refresh the page and try again." ); return; } try { setIsRedirecting(true); await updateSessionStatus( sessionId, "method_digilocker_selected", apiKey, clientId ); sessionStorage.setItem("digilocker_flow_active", "true"); sessionStorage.setItem("digilocker_api_key", apiKey); sessionStorage.setItem("digilocker_client_id", clientId); const response = await initiateDigiLockerSession( apiKey, clientId, sdkCallbackUrl ); if (!response.data.authorization_url) { throw new Error("No authorization URL received from DigiLocker"); } const authUrl = new URL(response.data.authorization_url); setTimeout(() => { window.location.replace(authUrl.toString()); }, 3e3); } catch (error) { console.error("DigiLocker error:", error); alert("Failed to start DigiLocker session. Please try again."); setIsRedirecting(false); sessionStorage.removeItem("digilocker_flow_active"); sessionStorage.removeItem("digilocker_api_key"); sessionStorage.removeItem("digilocker_client_id"); } }; const handleAadhaar = async () => { if (!sessionReady || !sessionId) { alert( "Session initialization failed. Please refresh the page and try again." ); return; } try { const sessionStatus = await getSessionStatus(sessionId, apiKey, clientId); if (sessionStatus.status === "aadhaar_otp_send_success" && sessionStatus.aadhaar_reference_id) { const nowMs = Date.now(); const expMs = sessionStatus.aadhaar_reference_id_exp; if (expMs && nowMs < expMs) { onSelectAadhaar && onSelectAadhaar(); return; } else { localStorage.removeItem("deepvue_session_id"); const newSession = await initiateSession(apiKey, clientId); if (newSession?.session_id) { localStorage.setItem("deepvue_session_id", newSession.session_id); setSessionId(newSession.session_id); setSessionReady(true); await updateSessionStatus( newSession.session_id, "method_aadhaar_selected", apiKey, clientId ); } else { setSessionReady(false); } } } await updateSessionStatus( sessionId, "method_aadhaar_selected", apiKey, clientId ); if (onSelectAadhaar) onSelectAadhaar(); } catch (error) { console.error("Failed to check/update session status:", error); try { const newSession = await initiateSession(apiKey, clientId); if (newSession?.session_id) { localStorage.setItem("deepvue_session_id", newSession.session_id); setSessionId(newSession.session_id); setSessionReady(true); await updateSessionStatus( newSession.session_id, "method_aadhaar_selected", apiKey, clientId ); } else { setSessionReady(false); } } catch { setSessionReady(false); } if (onSelectAadhaar) onSelectAadhaar(); } }; if (isRedirecting) { return /* @__PURE__ */ jsx( Box, { sx: { display: "flex", justifyContent: "center", alignItems: "center", minHeight: "100vh", backgroundColor: theme.palette.background.default }, children: /* @__PURE__ */ jsx(Fade, { in: true, timeout: 500, children: /* @__PURE__ */ jsxs( Paper, { elevation: 4, sx: { width: "100%", maxWidth: 450, p: theme.spacing(5), borderRadius: theme.spacing(2), backgroundColor: "#ffffff", textAlign: "center" }, children: [ /* @__PURE__ */ jsx( CloudQueue_default, { sx: { fontSize: 64, color: theme.palette.primary.main, mb: 2 } } ), /* @__PURE__ */ jsx(Typography, { variant: "h5", fontWeight: "bold", gutterBottom: true, children: "Connecting to DigiLocker" }), /* @__PURE__ */ jsx(Typography, { variant: "body1", color: "text.secondary", sx: { mb: 4 }, children: "Please wait while we securely connect you to DigiLocker..." }), /* @__PURE__ */ jsx( CircularProgress, { size: 40, thickness: 4, sx: { color: theme.palette.primary.main } } ) ] } ) }) } ); } if (singleFlow && showFlowSelector === false) { return /* @__PURE__ */ jsx(Fragment, {}); } if (singleFlow && showFlowSelector) { return /* @__PURE__ */ jsx( Box, { sx: { display: "flex", justifyContent: "center", alignItems: "center", p: { xs: 1.5, sm: 3 }, backgroundColor: theme.palette.grey[50] }, children: /* @__PURE__ */ jsxs( Paper, { elevation: 4, sx: { width: "100%", maxWidth: 420, p: { xs: theme.spacing(2), sm: theme.spacing(4) }, borderRadius: theme.spacing(2), backgroundColor: "#ffffff", textAlign: "center", boxShadow: "0 8px 24px rgba(0,0,0,0.08)" }, children: [ /* @__PURE__ */ jsx( Typography, { variant: "h6", fontWeight: "bold", gutterBottom: true, sx: { color: theme.palette.primary.main, mb: 0.5 }, children: singleFlow === "aadhaar" ? "Aadhaar eKYC Verification" : "DigiLocker Verification" } ), /* @__PURE__ */ jsx( Typography, { variant: "body2", color: "text.secondary", sx: { mb: 3, maxWidth: "420px", mx: "auto", lineHeight: 1.5 }, children: singleFlow === "aadhaar" ? "Verify your identity using your Aadhaar number and OTP" : "Verify your identity using your Digilocker E-Aadhaar" } ), /* @__PURE__ */ jsxs( Box, { sx: { p: 2, borderRadius: theme.spacing(1.5), border: `1px solid ${theme.palette.primary.main}`, backgroundColor: theme.palette.primary.light + "08", transition: "all 0.2s ease", position: "relative", overflow: "visible", "&:hover": { backgroundColor: theme.palette.primary.light + "12", transform: "translateY(-2px)", boxShadow: "0 4px 12px rgba(0,0,0,0.05)" }, cursor: "pointer" }, children: [ singleFlow === "digilocker" && /* @__PURE__ */ jsx( Chip, { label: "Recommended", size: "small", sx: { position: "absolute", top: 2, right: 2, background: theme.palette.success.light + "15", color: theme.palette.success.main, fontWeight: 500, fontSize: "0.7rem", height: "22px", boxShadow: "none", border: `1px solid ${theme.palette.success.light + "40"}`, backdropFilter: "blur(4px)", zIndex: 1, "& .MuiChip-label": { px: 1.2, py: 0.3 }, "& .MuiChip-icon": { color: theme.palette.success.light, marginLeft: "4px", marginRight: "-4px" }, "&:hover": { background: theme.palette.success.light + "25" } } } ), singleFlow === "aadhaar" ? /* @__PURE__ */ jsx( AccountBox_default, { sx: { fontSize: 32, color: theme.palette.primary.main, mb: 1 } } ) : /* @__PURE__ */ jsx( Cloud_default, { sx: { fontSize: 32, color: theme.palette.info.main, mb: 1 } } ), /* @__PURE__ */ jsx(Typography, { variant: "subtitle1", fontWeight: "600", gutterBottom: true, children: singleFlow === "aadhaar" ? "Aadhaar eKYC" : "DigiLocker" }), /* @__PURE__ */ jsx( Typography, { variant: "body2", color: "text.secondary", sx: { mb: 1.5, fontSize: "0.875rem" }, children: singleFlow === "aadhaar" ? "Verify your identity using your Aadhaar number and OTP" : "Verify your identity using your Digilocker E-Aadhaar" } ), /* @__PURE__ */ jsxs( Button, { fullWidth: true, variant: "contained", size: "medium", disabled: !sessionReady, sx: { textTransform: "none", fontWeight: 600, py: 1, borderRadius: theme.spacing(1), fontSize: "0.875rem", "&:hover": { backgroundColor: theme.palette.primary.dark } }, onClick: singleFlow === "aadhaar" ? handleAadhaar : handleDigilocker, children: [ "Continue with", " ", singleFlow === "aadhaar" ? "Aadhaar" : "DigiLocker" ] } ) ] } ) ] } ) } ); } return /* @__PURE__ */ jsx( Box, { sx: { display: "flex", justifyContent: "center", alignItems: "center", p: { xs: 1.5, sm: 3 }, backgroundColor: theme.palette.grey[50] }, children: /* @__PURE__ */ jsxs( Paper, { elevation: 4, sx: { width: "100%", maxWidth: 420, p: { xs: theme.spacing(2), sm: theme.spacing(4) }, borderRadius: theme.spacing(2), backgroundColor: "#ffffff", textAlign: "center", boxShadow: "0 8px 24px rgba(0,0,0,0.08)" }, children: [ /* @__PURE__ */ jsx( Typography, { variant: "h6", fontWeight: "bold", gutterBottom: true, sx: { color: theme.palette.primary.main, mb: 0.5 }, children: "Choose Your Verification Method" } ), /* @__PURE__ */ jsx( Typography, { variant: "body2", color: "text.secondary", sx: { mb: 3, maxWidth: "420px", mx: "auto", lineHeight: 1.5 }, children: "Select your preferred secure eKYC method to verify your identity" } ), /* @__PURE__ */ jsxs(Stack, { spacing: 2, children: [ /* @__PURE__ */ jsxs( Box, { sx: { p: 2, borderRadius: theme.spacing(1.5), border: `1px solid ${theme.palette.primary.main}`, backgroundColor: theme.palette.primary.light + "08", transition: "all 0.2s ease", position: "relative", overflow: "visible", "&:hover": { backgroundColor: theme.palette.primary.light + "12", transform: "translateY(-2px)", boxShadow: "0 4px 12px rgba(0,0,0,0.05)" }, cursor: "pointer" }, children: [ /* @__PURE__ */ jsx( Chip, { label: "Recommended", size: "small", sx: { position: "absolute", top: 2, right: 2, background: theme.palette.success.light + "15", color: theme.palette.success.main, fontWeight: 500, fontSize: "0.7rem", height: "22px", boxShadow: "none", border: `1px solid ${theme.palette.success.light + "40"}`, backdropFilter: "blur(4px)", zIndex: 1, "& .MuiChip-label": { px: 1.2, py: 0.3 }, "& .MuiChip-icon": { color: theme.palette.success.light, marginLeft: "4px", marginRight: "-4px" }, "&:hover": { background: theme.palette.success.light + "25" } } } ), /* @__PURE__ */ jsx( Cloud_default, { sx: { fontSize: 32, color: theme.palette.info.main, mb: 1 } } ), /* @__PURE__ */ jsx(Typography, { variant: "subtitle1", fontWeight: "600", gutterBottom: true, children: "DigiLocker" }), /* @__PURE__ */ jsx( Typography, { variant: "body2", color: "text.secondary", sx: { mb: 1.5, fontSize: "0.875rem" }, children: "Verify your identity using your Digilocker E-Aadhaar" } ), /* @__PURE__ */ jsx( Button, { fullWidth: true, variant: "contained", size: "medium", disabled: !sessionReady, sx: { textTransform: "none", fontWeight: 600, py: 1, borderRadius: theme.spacing(1), fontSize: "0.875rem", "&:hover": { backgroundColor: theme.palette.primary.dark } }, onClick: handleDigilocker, children: "Continue with DigiLocker" } ) ] } ), /* @__PURE__ */ jsx( Typography, { variant: "caption", color: "text.secondary", sx: { position: "relative", display: "block", my: 1, "&::before, &::after": { content: '""', position: "absolute", top: "50%", width: "25%", height: "1px", backgroundColor: theme.palette.divider }, "&::before": { left: 0 }, "&::after": { right: 0 } }, children: "OR" } ), /* @__PURE__ */ jsxs( Box, { sx: { p: 2, borderRadius: theme.spacing(1.5), border: `1px solid ${theme.palette.grey[300]}`, backgroundColor: theme.palette.grey[50], transition: "all 0.2s ease", "&:hover": { backgroundColor: theme.palette.grey[100], transform: "translateY(-2px)", boxShadow: "0 4px 12px rgba(0,0,0,0.05)" }, cursor: "pointer" }, children: [ /* @__PURE__ */ jsx( AccountBox_default, { sx: { fontSize: 32, color: theme.palette.primary.main, mb: 1 } } ), /* @__PURE__ */ jsx(Typography, { variant: "subtitle1", fontWeight: "600", gutterBottom: true, children: "Aadhaar eKYC" }), /* @__PURE__ */ jsx( Typography, { variant: "body2", color: "text.secondary", sx: { mb: 1.5, fontSize: "0.875rem" }, children: "Verify your identity using your Aadhaar number and OTP" } ), /* @__PURE__ */ jsx( Button, { fullWidth: true, variant: "outlined", size: "medium", disabled: !sessionReady, sx: { textTransform: "none", fontWeight: 600, py: 1, borderRadius: theme.spacing(1), fontSize: "0.875rem", borderColor: theme.palette.info.main, color: theme.palette.info.main, "&:hover": { borderColor: theme.palette.info.dark, backgroundColor: theme.palette.info.light + "12" } }, onClick: handleAadhaar, children: "Continue with Aadhaar" } ) ] } ) ] }), /* @__PURE__ */ jsx(Divider, { sx: { my: 4, opacity: 0.6 } }), /* @__PURE__ */ jsxs( Box, { sx: { display: "flex", alignItems: "center", justifyContent: "center", gap: 1.5 }, children: [ /* @__PURE__ */ jsx( Typography, { variant: "caption", sx: { color: theme.palette.text.secondary, fontSize: "0.75rem", letterSpacing: "0.5px", fontWeight: 500 }, children: "Powered By" } ), /* @__PURE__ */ jsx(Logo, {}) ] } ) ] } ) } ); }; var CheckCircle_default = createSvgIcon(/* @__PURE__ */ jsx("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m-2 15-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8z" }), "CheckCircle"); var Error_default = createSvgIcon(/* @__PURE__ */ jsx("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m1 15h-2v-2h2zm0-4h-2V7h2z" }), "Error"); var ResultRow = styled(Box)(({ theme }) => ({ display: "flex", alignItems: "center", padding: theme.spacing(1.5, 0), "&:last-child": { borderBottom: "none" }, [theme.breakpoints.down("sm")]: { flexDirection: "column", alignItems: "flex-start", gap: theme.spacing(1) } })); var DigiLockerFlow = ({ apiKey, clientId, redirectUrl, autoProcessCallback = true }) => { const theme = useTheme(); const isMobile = useMediaQuery(theme.breakpoints.down("sm")); const [isLoading, setIsLoading] = useState(false); const [verificationResult, setVerificationResult] = useState(null); const [error, setError] = useState(""); const [redirectCount, setRedirectCount] = useState(5); const [processingStatus, setProcessingStatus] = useState(""); const cleanupSession = () => { if (verificationResult || error) { localStorage.removeItem("deepvue_session_id"); sessionStorage.removeItem("digilocker_callback_code"); sessionStorage.removeItem("digilocker_callback_state"); sessionStorage.removeItem("digilocker_api_key"); sessionStorage.removeItem("digilocker_client_id"); sessionStorage.removeItem("digilocker_callback_received"); sessionStorage.removeItem("digilocker_flow_active"); } }; useEffect(() => { return () => { cleanupSession(); }; }, [verificationResult, error]); useEffect(() => { if (!autoProcessCallback) return; const processCallbackData = async () => { try { const callbackCode = sessionStorage.getItem("digilocker_callback_code"); const callbackState = sessionStorage.getItem( "digilocker_callback_state" ); const storedApiKey = sessionStorage.getItem("digilocker_api_key"); const storedClientId = sessionStorage.getItem("digilocker_client_id"); const callbackReceived = sessionStorage.getItem( "digilocker_callback_received" ); if (callbackCode && callbackState && storedApiKey && storedClientId && callbackReceived === "true") { sessionStorage.removeItem("digilocker_callback_received"); sessionStorage.removeItem("digilocker_flow_active"); await handleCompleteDigilockerJourney(callbackCode, callbackState); } } catch (error2) { console.error("Error in auto-processing callback:", error2); setError("Failed to auto-process DigiLocker callback"); cleanupSession(); } }; processCallbackData(); const handleMessage = async (event) => { if (event.origin !== window.location.origin) return; if (event.data.type === "DIGILOCKER_CALLBACK") { const { digilockerCode: code, transactionId: txId } = event.data; if (code && txId) { await handleCompleteDigilockerJourney(code, txId); } } }; window.addEventListener("message", handleMessage); return () => { window.removeEventListener("message", handleMessage); cleanupSession(); }; }, [autoProcessCallback, apiKey, clientId]); const handleCompleteDigilockerJourney = async (code, txId) => { setIsLoading(true); setError(""); setProcessingStatus("Getting access token..."); setVerificationResult(null); const sessionId = localStorage.getItem("deepvue_session_id"); try { setProcessingStatus("Authenticating with DigiLocker..."); const tokenResponse = await getDigiLockerAccessToken( txId, code, apiKey, clientId ); if (tokenResponse?.code === 200 && tokenResponse?.sub_code === "SUCCESS") { setProcessingStatus("Fetching your Aadhaar data..."); const aadhaarResponse = await getEAadhaarData(txId, apiKey, clientId); if (aadhaarResponse?.code === 200 && aadhaarResponse?.sub_code === "SUCCESS") { setProcessingStatus("Verification completed successfully!"); setVerificationResult(aadhaarResponse); if (sessionId) { try { await updateSessionStatus( sessionId, "digilocker_success", apiKey, clientId ); } catch (updateError) { console.error("Failed to update session status:", updateError); } } const timer = setInterval(() => { setRedirectCount((prev) => { if (prev <= 1) { clearInterval(timer); cleanupSession(); window.location.href = redirectUrl; return 0; } return prev - 1; }); }, 1e3); return () => clearInterval(timer); } else { throw new Error( aadhaarResponse?.message || "Failed to fetch Aadhaar data" ); } } else { throw new Error(tokenResponse?.message || "Failed to get access token"); } } catch (error2) { console.error("DigiLocker flow error:", error2); const errorResponse = error2?.response?.data || { message: error2?.message || "An error occurred during verification", code: error2?.response?.status || 500 }; if (sessionId) { try { await updateSessionStatus( sessionId, "digilocker_failure", apiKey, clientId ); } catch (updateError) { console.error("Failed to update session status:", updateError); } } setError(errorResponse.message); setProcessingStatus("Verification failed"); cleanupSession(); } finally { setIsLoading(false); setProcessingStatus(""); } }; const transformValue = (val) => { if (val == null) return ""; if (typeof val === "boolean") return val ? "Yes" : "No"; return val; }; const renderData = (obj) => { if (!obj || typeof obj !== "object") { return []; } const data = { maskedNumber: obj.masked_uid, name: obj.proof_of_identity?.name, dateOfBirth: obj.proof_of_identity?.dob, gender: obj.proof_of_identity?.gender, address: obj.proof_of_address, photo: obj.photo }; const fieldsToShow = [ { key: "maskedNumber", label: "Aadhaar Number" }, { key: "name", label: "Name" }, { key: "dateOfBirth", label: "Date Of Birth" }, { key: "gender", label: "Gender" }, { key: "address", label: "Address" }, { key: "photo", label: "Photo" } ]; return fieldsToShow.flatMap(({ key, label }, idx) => { const value = data[key]; if (key === "photo" && typeof value === "string") { return [ /* @__PURE__ */ jsxs(ResultRow, { children: [ /* @__PURE__ */ jsx( Typography, { variant: "subtitle2", sx: { width: "180px", fontWeight: 600 }, children: label } ), /* @__PURE__ */ jsx( Box, { component: "img", src: `data:image/jpeg;base64,${value}`, alt: "Aadhaar Photo", sx: { width: 100, height: "auto", borderRadius: 1 } } ) ] }, key), idx < fieldsToShow.length - 1 && /* @__PURE__ */ jsx(Divider, {}, `${key}-div`) ]; } if (key === "address" && value && typeof value === "object") { const addressParts = [ value.care_of, value.house, value.street, value.locality, value.vtc, value.district, value.state, value.pincode, value.country ].filter(Boolean).join(", "); return [ /* @__PURE__ */ jsxs(ResultRow, { children: [ /* @__PURE__ */ jsx( Typography, { variant: "subtitle2", sx: { width: "180px", fontWeight: 600 }, children: label } ), /* @__PURE__ */ jsx(Typography, { variant: "body2", children: addressParts }) ] }, key), idx < fieldsToShow.length - 1 && /* @__PURE__ */ jsx(Divider, {}, `${key}-div`) ]; } return [ /* @__PURE__ */ jsxs(ResultRow, { children: [ /* @__PURE__ */ jsx( Typography, { variant: "subtitle2", sx: { width: "180px", fontWeight: 600 }, children: label } ), /* @__PURE__ */ jsx(Typography, { variant: "body2", children: transformValue(value) }) ] }, key), idx < fieldsToShow.length - 1 && /* @__PURE__ */ jsx(Divider, {}, `${key}-div`) ]; }); }; const displayData = verificationResult?.data ?? verificationResult; useEffect(() => { if (displayData && !error) { const timer = setInterval(() => { setRedirectCount((prev) => { if (prev <= 1) { clearInterval(timer); window.location.href = redirectUrl; return 0; } return prev - 1; }); }, 1e3); return () => clearInterval(timer); } }, [displayData, redirectUrl, error]); return /* @__PURE__ */ jsx(Box, { sx: { display: "flex", justifyContent: "center", p: 4 }, children: /* @__PURE__ */ jsxs( Paper, { elevation: 4, sx: { width: "100%", maxWidth: 450, p: theme.spacing(4), borderRadius: theme.spacing(2), backgroundColor: "#ffffff" }, children: [ isLoading && /* @__PURE__ */ jsxs( Box, { sx: { display: "flex", flexDirection: "column", alignItems: "center", py: 4 }, children: [ /* @__PURE__ */ jsx(CircularProgress, { size: 40, sx: { mb: 2 } }), /* @__PURE__ */ jsx(Typography, { variant: "body1", sx: { mb: 1 }, children: processingStatus || "Processing your DigiLocker verification..." }), /* @__PURE__ */ jsx(Typography, { variant: "body2", color: "text.secondary", children: "Please wait while we securely verify and fetch your information." }) ] } ), !isLoading && verificationResult && !error && /* @__PURE__ */ jsx(Fade, { in: true, timeout: 500, children: /* @__PURE__ */ jsxs(Box, { children: [ /* @__PURE__ */ jsx( Box, { sx: { display: "flex", alignItems: "center", gap: 1, mb: 3 }, children: /* @__PURE__ */ jsxs( Typography, { variant: "h5", fontWeight: 600, sx: { display: "flex", alignItems: "center", gap: 1 }, children: [ /* @__PURE__ */ jsx(CheckCircle_default, { color: "success" }), "Verification Successful" ] } ) } ), displayData && typeof displayData === "object" ? /* @__PURE__ */ jsxs(Fragment, { children: [ /* @__PURE__ */ jsx( Box, { sx: { maxHeight: isMobile ? "60vh" : "50vh", overflowY: "auto", pr: 1, "&::-webkit-scrollbar": { width: "8px" }, "&::-webkit-scrollbar-track": { background: alpha(theme.palette.primary.main, 0.1), borderRadius: "4px" }, "&::-webkit-scrollbar-thumb": { background: alpha(theme.palette.primary.main, 0.3), borderRadius: "4px", "&:hover": { background: alpha(theme.palette.primary.main, 0.5) } } }, children: renderData(displayData) } ), !error && /* @__PURE__ */ jsxs(Alert, { severity: "info", sx: { mt: 2 }, children: [ "Redirecting to ", redirectUrl, " in ", redirectCount, " seconds..." ] }) ] }) : /* @__PURE__ */ jsx( Alert, { severity: "error", variant: "filled", sx: { borderRadius: 2 }, children: "No data returned" } ) ] }) }), error && !isLoading && /* @__PURE__ */ jsxs(Fragment, { children: [ /* @__PURE__ */ jsx( Box, { sx: { display: "flex", alignItems: "center", gap: 1, mb: 3 }, children: /* @__PURE__ */ jsxs( Typography, { variant: "h5", fontWeight: 600, sx: { display: "flex", alignItems: "center", gap: 1 }, children: [ /* @__PURE__ */ jsx(Error_default, { sx: { color: "error.main" } }), "Verification Failed" ] } ) } ), /* @__PURE__ */ jsx(Alert, { severity: "error", variant: "filled", sx: { borderRadius: 2 }, children: error }) ] }) ] } ) }); }; export { DigiLockerFlow, FlowSelector }; //# sourceMappingURL=index.js.map //# sourceMappingURL=index.js.map