tg-auth
v1.0.1
Published
Telegram Auth
Readme
tg-auth
Telegram 登录授权 Vue 组件(H5 + uni-app App)。
安装
npm install tg-auth将静态授权页拷贝到宿主项目(须部署在 tgAuthDomain 对应站点,路径与 authBasePath 一致):
npx tg-auth-copy-static --target src/static/htmlTelegram Bot 后台需登记授权页的 origin。
组件用法
点击区域由组件内部处理;默认 slot 仅用于展示(图标、文字等)。
<script setup>
import { TgAuth } from 'tg-auth';
const tgAuthDomain = 'https://h5.example.com';
const botId = '123456789';
function onAuth(user) {
// H5:Telegram 用户对象(含 id、first_name、hash 等)
console.log(user);
}
</script>
<template>
<TgAuth
:tg-auth-domain="tgAuthDomain"
:bot-id="botId"
@authorized="onAuth"
>
<span>TG 登录</span>
</TgAuth>
</template>Props
| 属性 | 说明 | 默认 |
|------|------|------|
| tg-auth-domain | 静态授权页所在站点域名 | '' |
| bot-id | Telegram Bot ID | '' |
| auth-base-path | 静态页部署路径 | /static/html |
| iframe-breakpoint | 视口宽度 ≥ 该值时使用 iframe(px) | 580 |
| app-auth-options | App 模式传给 tgauth-app.html 的参数 | {} |
事件
| 事件 | 说明 |
|------|------|
| authorized | 仅 H5:授权成功,参数为 Telegram 用户对象 |
uni-app App
App 端(window === undefined)点击后会通过 plus.runtime.openURL 打开系统浏览器中的 tgauth-app.html,授权成功后以深链返回 App,不会触发 authorized,需在 App 入口自行解析 URL 参数 arg。
app-auth-options 示例(urlScheme 必填):
<TgAuth
:tg-auth-domain="tgAuthDomain"
:bot-id="botId"
:app-auth-options="{
page: 'login',
lang: 'zh',
urlScheme: 'myapp://',
}"
>
<span>TG 登录</span>
</TgAuth>深链格式:{urlScheme}{page}?arg={encodeURIComponent(JSON.stringify(user))}
本地示例
仓库内附带可运行的 H5 演示(example/):
npm run dev:example(首次或更新 static/ 后也可手动执行 npm run copy-static:example。)
浏览器用终端输出的 Network 地址(如 http://192.168.1.100:5173)打开,在 BotFather /setdomain 登记同一 host 后测试登录。详见 example/README.md。
工具函数
import {
TgAuth,
TG_AUTH_RESULT_REGEX,
parseTgAuthResult,
} from 'tg-auth';
// parseTgAuthResult('eyJpZCI6MTIz...') => { id: 123, ... }发布
发布前会自动执行 npm run build(prepublishOnly)。
