自学内容网 自学内容网

telegram 小程序开发之旅(一)

Next.js App项目开发 telegram 小程序

将 telegram 的内置对象通过 context 挂载到全局,在 provides 下新建 TelegramProvider

"use client";
import Script from "next/script";
import { createContext, useContext, useEffect, useMemo, useState } from "react";
export interface ITelegramUser {
  id: number;
  first_name: string;
  last_name: string;
  username: string;
  language_code: string;
}

export interface IWebApp {
  initData: string;
  initDataUnsafe: {
    query_id: string;
    user: ITelegramUser;
    auth_date: string;
    hash: string;
  };
  version: string;
  platform: string;
  colorScheme: string;
  themeParams: {
    link_color: string;
    button_color: string;
    button_text_color: string;
    secondary_bg_color: string;
    hint_color: string;
    bg_color: string;
    text_color: string;
  };
  isExpanded: boolean;
  viewportHeight: number;
  viewportStableHeight: number;
  isClosingConfirmationEnabled: boolean;
  headerColor: string;
  backgroundColor: string;
  BackButton: {
    isVisible: boolean;
  };
  MainButton: {
    text: string;
    color: string;
    textColor: string;
    isVisible: boolean;
    isProgressVisible: boolean;
    isActive: boolean;
  };
  HapticFeedback: any;
  openTelegramLink: any;
}

export interface ITelegramContext {
  webApp?: IWebApp;
  user?: ITelegramUser;
}

export const TelegramContext = createContext<ITelegramContext>({});

export const TelegramProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const [webApp, setWebApp] = useState<IWebApp | null>(null);

  useEffect(() => {
    const app = (window as any).Telegram?.WebApp;
    if (app) {
      app.ready();
      setWebApp(app);
    }
  }, []);

  const value = useMemo(() => {
    return webApp
      ? {
          webApp,
          unsafeData: webApp.initDataUnsafe,
          user: webApp.initDataUnsafe.user,
        }
      : {};
  }, [webApp]);

  return (
    <TelegramContext.Provider value={value}>
      <Script
        src="https://telegram.org/js/telegram-web-app.js"
        strategy="beforeInteractive"
      />
      {children}
    </TelegramContext.Provider>
  );
};

export const useTelegram = () => useContext(TelegramContext);
将 TelegramProvider 挂载到 app 下的 layout.tsx 全局组件上
import type { Metadata } from "next"; 
import { Inter } from "next/font/google";
import "./globals.css";
import { Providers } from "@/providers/TelegramProvider"; 
const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "xxx",
  description: "xxx website",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en"> 
      <body className={inter.className}>
        <Providers>
          <div className="max-width-[1920px] mx-auto w-full h-full">
            {children}
          </div>
        </Providers>
      </body> 
    </html>
  );
}
页面中使用
import { useTelegram } from "@/providers/TelegramProvider";
...
const Page = () => {
const { webApp } = useTelegram();
const initData = useMemo(() => webApp && webApp.initData, [webApp]);
getUser(initData);
}

const getUser = (initData: string) => {
  return fetcher(null, `${getHost()}/user/info`, {
    method: "GET",
    headers: new Headers({
      "Content-Type": "application/json",
      Authorization: `tma ${initData}`,
    }),
  });
};

原文地址:https://blog.csdn.net/cmy120813/article/details/140625031

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!