Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- "use client"
- // import { useEffect, useState } from "react";
- import { useEffect, useState } from "react";
- import { useSignal, initData, type User } from '@telegram-apps/sdk-react';
- export function useTelegram() {
- // Use the SDK's signals to access Telegram data
- const initDataRaw = useSignal(initData.raw);
- const initDataState = useSignal(initData.state);
- const [isLoading, setIsLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const [tg, setTg] = useState<any>(null);
- const [isBrowser, setIsBrowser] = useState(false);
- const user = initDataState?.user;
- useEffect(() => {
- // This effect runs only on the client side
- setIsBrowser(typeof window !== 'undefined');
- if (typeof window !== 'undefined') {
- setTg(window.Telegram?.WebApp);
- console.log('Telegram.WebApp:', window.Telegram?.WebApp);
- console.log('InitData:', initDataRaw, initDataState);
- console.log("🔄 useTelegram init:", {
- initDataRaw: !!initDataRaw,
- user: !!user,
- tg: !!window.Telegram?.WebApp
- });
- }
- }, []);
- useEffect(() => {
- if (!isBrowser) return;
- // Debug logging when dependencies change
- console.log("🔍 useTelegram effect triggered:", {
- initDataRaw: !!initDataRaw,
- user: !!user && user.id
- });
- // Check if Telegram data is available
- if (initDataRaw && initDataState?.user) {
- console.log("✅ Telegram data available, starting authentication");
- authenticateTelegramUser();
- } else if (initDataRaw === null) {
- // API loaded but we're not in Telegram
- console.log("❌ Page opened outside Telegram Mini App");
- setIsLoading(false);
- } else {
- console.log("⏳ Waiting for Telegram API to load...");
- }
- }, [initDataRaw, initDataState, isBrowser]);
- async function authenticateTelegramUser() {
- try {
- if (!initDataRaw || !initDataState?.user) {
- console.log("❌ Cannot authenticate: missing data");
- setIsLoading(false);
- return;
- }
- console.log("🔐 Starting Telegram user authentication...");
- console.log("📊 User data:", {
- id: initDataState.user.id,
- firstName: initDataState.user.firstName,
- username: initDataState.user.username
- });
- console.log("🔗 API URL:", `${process.env.NEXT_PUBLIC_API_URL}/api/auth/telegram`);
- const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/telegram`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- initData: initDataRaw,
- user: {
- id: initDataState.user.id,
- first_name: initDataState.user.firstName,
- last_name: initDataState.user.lastName,
- username: initDataState.user.username,
- language_code: initDataState.user.languageCode,
- is_premium: initDataState.user.isPremium
- }
- })
- });
- console.log("📡 Response status:", response.status);
- if (!response.ok) {
- const errorData = await response.json();
- console.error("❌ Server error:", errorData);
- throw new Error(errorData.message || 'Authentication failed');
- }
- const data = await response.json();
- console.log("✅ Auth response:", { success: data.success, hasJwt: !!data.jwt });
- // Save token to localStorage and cookie (client-side only)
- if (isBrowser) {
- localStorage.setItem("authToken", data.jwt);
- const expiryDate = new Date(Date.now() + 24 * 60 * 60 * 1000);
- document.cookie = `authToken=${data.jwt}; expires=${expiryDate.toUTCString()}; path=/; SameSite=Strict`;
- }
- console.log("🎉 Telegram authentication successful!");
- setIsLoading(false);
- } catch (err) {
- console.error("❌ Error during Telegram user authentication:", err);
- setError(err instanceof Error ? err.message : "Authentication failed");
- setIsLoading(false);
- }
- }
- return {
- tg,
- user,
- initData: initDataState,
- initDataRaw,
- isLoading,
- error
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement