fix: 使用飞书官方 QR SDK,扫码后不打开浏览器

使用飞书官方 LarkSSOSDKWebQRCode-1.0.3.js 生成二维码,
飞书APP会识别为登录二维码并在APP内直接处理,
不会打开任何浏览器窗口。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
root
2026-02-26 11:13:43 +08:00
parent 457b1d75f0
commit 474c532666
+82 -55
View File
@@ -1,37 +1,89 @@
import { useState, useEffect, useRef } from 'react'
import { Dialog, Toast } from 'antd-mobile'
import { QRCodeSVG } from 'qrcode.react'
import { useNavigate } from 'react-router-dom'
import styles from './QRCodeLogin.module.css'
// 声明飞书 QR SDK 类型
declare global {
interface Window {
QR?: (config: {
id: string
goto: string
width?: string
height?: string
style?: string
}) => {
matchOrigin: (origin: string) => boolean
matchData: (data: any) => boolean
}
}
}
interface QRCodeLoginProps {
visible: boolean
onClose: () => void
}
// 动态加载飞书 QR SDK
const loadFeishuQRSDK = (): Promise<void> => {
return new Promise((resolve, reject) => {
if (window.QR) {
resolve()
return
}
// 检查是否已经加载过
const existingScript = document.getElementById('feishu-qr-sdk')
if (existingScript) {
existingScript.addEventListener('load', () => resolve())
existingScript.addEventListener('error', () => reject(new Error('Failed to load Feishu QR SDK')))
return
}
const script = document.createElement('script')
script.id = 'feishu-qr-sdk'
script.src = 'https://lf-package-cn.feishucdn.com/obj/feishu-static/lark/passport/qrcode/LarkSSOSDKWebQRCode-1.0.3.js'
script.onload = () => resolve()
script.onerror = () => reject(new Error('Failed to load Feishu QR SDK'))
document.head.appendChild(script)
})
}
export default function QRCodeLogin({ visible, onClose }: QRCodeLoginProps) {
const navigate = useNavigate()
const [qrcodeUrl, setQrcodeUrl] = useState('')
const [sessionId, setSessionId] = useState('')
const [status, setStatus] = useState<'loading' | 'pending' | 'scanning' | 'success' | 'expired'>('loading')
const [status, setStatus] = useState<'loading' | 'pending' | 'scanning' | 'success'>('loading')
const qrContainerRef = useRef<HTMLDivElement>(null)
const qrObjRef = useRef<any>(null)
const pollTimerRef = useRef<NodeJS.Timeout | null>(null)
const sessionIdRef = useRef<string>('')
useEffect(() => {
if (visible) {
initQrcodeLogin()
initQRCode()
}
return () => {
// 清理
if (qrContainerRef.current) {
qrContainerRef.current.innerHTML = ''
}
if (pollTimerRef.current) {
clearTimeout(pollTimerRef.current)
}
}
}, [visible])
const initQrcodeLogin = async () => {
const initQRCode = async () => {
setStatus('loading')
try {
// 生成登录二维码
// 加载飞书 QR SDK
await loadFeishuQRSDK()
if (!window.QR) {
throw new Error('QR SDK not loaded')
}
// 生成登录会话
const response = await fetch('/api/v1/auth/qrcode-login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -43,19 +95,31 @@ export default function QRCodeLogin({ visible, onClose }: QRCodeLoginProps) {
const result = await response.json()
if (result.code === 0) {
setQrcodeUrl(result.data.auth_url)
setSessionId(result.data.session_id)
const authUrl = result.data.auth_url
sessionIdRef.current = result.data.session_id
// 清空容器
if (qrContainerRef.current) {
qrContainerRef.current.innerHTML = ''
}
// 使用飞书官方 QR SDK 创建二维码
qrObjRef.current = window.QR({
id: 'feishu-qrcode-container',
goto: authUrl,
width: '200',
height: '200',
})
setStatus('pending')
// 开始轮询登录状态
startPolling(result.data.session_id)
} else {
Toast.show(result.message || '生成二维码失败')
setStatus('expired')
}
} catch (error) {
console.error('生成二维码失败:', error)
Toast.show('生成二维码失败')
setStatus('expired')
}
}
@@ -80,9 +144,6 @@ export default function QRCodeLogin({ visible, onClose }: QRCodeLoginProps) {
onClose()
navigate('/dashboard')
}, 500)
} else if (result.data.status === 'expired') {
setStatus('expired')
Toast.show('二维码已过期,请刷新重试')
} else if (result.data.status === 'scanning') {
setStatus('scanning')
// 继续轮询
@@ -91,8 +152,6 @@ export default function QRCodeLogin({ visible, onClose }: QRCodeLoginProps) {
// pending,继续轮询
pollTimerRef.current = setTimeout(poll, 2000)
}
} else if (result.message?.includes('过期')) {
setStatus('expired')
} else {
// 继续轮询
pollTimerRef.current = setTimeout(poll, 2000)
@@ -117,8 +176,6 @@ export default function QRCodeLogin({ visible, onClose }: QRCodeLoginProps) {
return '已扫码,请在手机上确认'
case 'success':
return '登录成功!'
case 'expired':
return '二维码已过期'
default:
return ''
}
@@ -132,55 +189,25 @@ export default function QRCodeLogin({ visible, onClose }: QRCodeLoginProps) {
return '#faad14'
case 'success':
return '#52c41a'
case 'expired':
return '#ff4d4f'
default:
return '#999'
}
}
const handleRefresh = () => {
if (pollTimerRef.current) {
clearTimeout(pollTimerRef.current)
}
initQrcodeLogin()
}
return (
<Dialog
visible={visible}
content={
<div className={styles.qrcodeContainer}>
{status === 'loading' && <div className={styles.loading}>正在生成二维码...</div>}
<div id="feishu-qrcode-container" ref={qrContainerRef} className={styles.qrcode}></div>
{qrcodeUrl && status !== 'loading' && (
<>
<div className={styles.qrcode}>
<QRCodeSVG
value={qrcodeUrl}
size={200}
level="M"
includeMargin={false}
/>
</div>
<div className={styles.status} style={{ color: getStatusColor() }}>
{getStatusText()}
</div>
<div className={styles.status} style={{ color: getStatusColor() }}>
{getStatusText()}
</div>
{(status === 'expired') && (
<div className={styles.actions}>
<button className={styles.refreshBtn} onClick={handleRefresh}>
刷新二维码
</button>
</div>
)}
<p className={styles.tip}>
💡 打开飞书 APP,扫一扫登录
</p>
</>
)}
<p className={styles.tip}>
💡 打开飞书 APP,扫一扫登录
</p>
</div>
}
onClose={onClose}