Advertisement
Wonkiest29

Untitled

May 5th, 2025
349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. "use client"
  2. // import { useEffect, useState } from "react";
  3. import { useEffect, useState } from "react";
  4. import { useSignal, initData, type User } from '@telegram-apps/sdk-react';
  5.  
  6. export function useTelegram() {
  7.   // Use the SDK's signals to access Telegram data
  8.   const initDataRaw = useSignal(initData.raw);
  9.   const initDataState = useSignal(initData.state);
  10.   const [isLoading, setIsLoading] = useState(true);
  11.   const [error, setError] = useState<string | null>(null);
  12.   const [tg, setTg] = useState<any>(null);
  13.   const [isBrowser, setIsBrowser] = useState(false);
  14.  
  15.   const user = initDataState?.user;
  16.  
  17.   useEffect(() => {
  18.     // This effect runs only on the client side
  19.     setIsBrowser(typeof window !== 'undefined');
  20.     if (typeof window !== 'undefined') {
  21.       setTg(window.Telegram?.WebApp);
  22.       console.log('Telegram.WebApp:', window.Telegram?.WebApp);
  23.       console.log('InitData:', initDataRaw, initDataState);
  24.       console.log("🔄 useTelegram init:", {
  25.         initDataRaw: !!initDataRaw,
  26.         user: !!user,
  27.         tg: !!window.Telegram?.WebApp
  28.       });
  29.     }
  30.   }, []);
  31.  
  32.   useEffect(() => {
  33.     if (!isBrowser) return;
  34.    
  35.     // Debug logging when dependencies change
  36.     console.log("🔍 useTelegram effect triggered:", {
  37.       initDataRaw: !!initDataRaw,
  38.       user: !!user && user.id
  39.     });
  40.    
  41.     // Check if Telegram data is available
  42.     if (initDataRaw && initDataState?.user) {
  43.       console.log("✅ Telegram data available, starting authentication");
  44.       authenticateTelegramUser();
  45.     } else if (initDataRaw === null) {
  46.       // API loaded but we're not in Telegram
  47.       console.log("❌ Page opened outside Telegram Mini App");
  48.       setIsLoading(false);
  49.     } else {
  50.       console.log("⏳ Waiting for Telegram API to load...");
  51.     }
  52.   }, [initDataRaw, initDataState, isBrowser]);
  53.  
  54.   async function authenticateTelegramUser() {
  55.     try {
  56.       if (!initDataRaw || !initDataState?.user) {
  57.         console.log("❌ Cannot authenticate: missing data");
  58.         setIsLoading(false);
  59.         return;
  60.       }
  61.  
  62.       console.log("🔐 Starting Telegram user authentication...");
  63.       console.log("📊 User data:", {
  64.         id: initDataState.user.id,
  65.         firstName: initDataState.user.firstName,
  66.         username: initDataState.user.username
  67.       });
  68.       console.log("🔗 API URL:", `${process.env.NEXT_PUBLIC_API_URL}/api/auth/telegram`);
  69.      
  70.       const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/telegram`, {
  71.         method: 'POST',
  72.         headers: {
  73.           'Content-Type': 'application/json'
  74.         },
  75.         body: JSON.stringify({
  76.           initData: initDataRaw,
  77.           user: {
  78.             id: initDataState.user.id,
  79.             first_name: initDataState.user.firstName,
  80.             last_name: initDataState.user.lastName,
  81.             username: initDataState.user.username,
  82.             language_code: initDataState.user.languageCode,
  83.             is_premium: initDataState.user.isPremium
  84.           }
  85.         })
  86.       });
  87.      
  88.       console.log("📡 Response status:", response.status);
  89.      
  90.       if (!response.ok) {
  91.         const errorData = await response.json();
  92.         console.error("❌ Server error:", errorData);
  93.         throw new Error(errorData.message || 'Authentication failed');
  94.       }
  95.      
  96.       const data = await response.json();
  97.       console.log("✅ Auth response:", { success: data.success, hasJwt: !!data.jwt });
  98.      
  99.       // Save token to localStorage and cookie (client-side only)
  100.       if (isBrowser) {
  101.         localStorage.setItem("authToken", data.jwt);
  102.         const expiryDate = new Date(Date.now() + 24 * 60 * 60 * 1000);
  103.         document.cookie = `authToken=${data.jwt}; expires=${expiryDate.toUTCString()}; path=/; SameSite=Strict`;
  104.       }
  105.      
  106.       console.log("🎉 Telegram authentication successful!");
  107.       setIsLoading(false);
  108.     } catch (err) {
  109.       console.error("❌ Error during Telegram user authentication:", err);
  110.       setError(err instanceof Error ? err.message : "Authentication failed");
  111.       setIsLoading(false);
  112.     }
  113.   }
  114.  
  115.   return {
  116.     tg,
  117.     user,
  118.     initData: initDataState,
  119.     initDataRaw,
  120.     isLoading,
  121.     error
  122.   };
  123. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement