nomadro/apps/miniprogram/tt/src/utils/request.ts
eric 1d3e513ae2 Ship Douyin tt/ miniprogram: offline reader, clipboard privacy, README.
Add apps/miniprogram/tt as a standalone Douyin app with official usePrivacyCheck + tt.showModal/setClipboardData flow, single-chapter offline reader, and document console privacy setup for clipboard.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 15:17:52 +08:00

212 lines
6.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Taro from '@tarojs/taro'
import {
API_BASE,
APP_TARGET,
COMMUNITY_API_BASE,
GATEWAY_API_BASE,
STORAGE_OPENID,
STORAGE_TOKEN,
} from './config'
import { track } from './track'
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'TRACE' | 'CONNECT'
type RequestOptions = {
url: string
method?: Method
data?: Record<string, unknown> | string
header?: Record<string, string>
_retried?: boolean
}
/** Vite+regenerator 不认 async 内的 `as`(TSAsExpression),统一用 Reflect 取值 */
function field(data: unknown, key: string): unknown {
if (!data || typeof data !== 'object') return undefined
return Reflect.get(data, key)
}
function errMsg(data: unknown, fallback: string): string {
const msg = field(data, 'detail') ?? field(data, 'message') ?? field(data, 'error') ?? fallback
return typeof msg === 'string' ? msg : JSON.stringify(msg)
}
export function clearLogin() {
Taro.removeStorageSync(STORAGE_TOKEN)
Taro.removeStorageSync(STORAGE_OPENID)
}
/** 电子书 API(/api/ebook/auth|/api/ebook/pay|/api/ebook/books…)— 门户命名空间 */
export async function requestEbook<T = unknown>(options: RequestOptions): Promise<T> {
const token = Taro.getStorageSync(STORAGE_TOKEN)
const res = await Taro.request({
url: `${API_BASE}${options.url}`,
method: options.method || 'GET',
data: options.data,
timeout: 8000,
header: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
Pragma: 'no-cache',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(options.header || {}),
},
})
if (res.statusCode === 401 && !options._retried && !options.url.includes('/api/ebook/auth/login')) {
if (process.env.TARO_ENV === 'h5' || APP_TARGET === 'h5') {
throw new Error('需要登录')
}
clearLogin()
await ensureLogin(true)
return requestEbook<T>({ ...options, _retried: true })
}
if (res.statusCode >= 400) {
throw new Error(errMsg(res.data, '请求失败'))
}
return res.data
}
/** ebook 兼容别名 */
export const request = requestEbook
export async function ensureLogin(force = false): Promise<{ openid: string; token: string }> {
if (!force) {
const cachedOpenid = Taro.getStorageSync(STORAGE_OPENID)
const cachedToken = Taro.getStorageSync(STORAGE_TOKEN)
if (cachedOpenid && cachedToken) {
return { openid: cachedOpenid, token: cachedToken }
}
} else {
clearLogin()
}
let lastErr: unknown
for (let i = 0; i < 3; i++) {
try {
// 抖音:tt.login 可能返回 code 和/或 anonymousCode
const loginOpts: { force: boolean } = { force: true }
const loginRes = await Taro.login(loginOpts)
const code = String(field(loginRes, 'code') || '')
const anonymousCode = String(field(loginRes, 'anonymousCode') || '')
if (!code && !anonymousCode) {
throw new Error('抖音登录失败:未拿到 code')
}
const res = await Taro.request({
url: `${API_BASE}/api/ebook/auth/login`,
method: 'POST',
data: {
code,
...(anonymousCode ? { anonymous_code: anonymousCode } : {}),
platform: 'tt',
},
header: { 'Content-Type': 'application/json' },
})
if (res.statusCode >= 400) {
throw new Error(errMsg(res.data, '登录失败'))
}
const openid = String(field(res.data, 'openid') || '')
const token = String(field(res.data, 'token') || '')
const sessionReady = Boolean(field(res.data, 'session_ready'))
if (!openid || !token) {
throw new Error('登录失败:无 openid/token')
}
Taro.setStorageSync(STORAGE_OPENID, openid)
Taro.setStorageSync(STORAGE_TOKEN, token)
track('login_ok', {
label: force ? 'refresh' : 'login',
props: { session_ready: sessionReady ? 1 : 0 },
})
return { openid, token }
} catch (e) {
lastErr = e
if (i >= 2) {
const em = e instanceof Error ? e.message : String(e)
track('login_fail', {
label: 'login',
props: { msg: em.slice(0, 120) },
})
}
await new Promise((r) => setTimeout(r, 250 * (i + 1)))
}
}
throw lastErr || new Error('登录失败,请再试一次')
}
export function compareVersion(v1: string, v2: string): number {
const a = v1.split('.').map(Number)
const b = v2.split('.').map(Number)
const len = Math.max(a.length, b.length)
for (let i = 0; i < len; i++) {
const x = a[i] || 0
const y = b[i] || 0
if (x > y) return 1
if (x < y) return -1
}
return 0
}
export function checkIosPayReady(): boolean {
const sys = Taro.getSystemInfoSync()
if (sys.platform !== 'ios') return true
return compareVersion(sys.version || '0.0.0', '8.0.68') >= 0
}
/** 社群 API — nomadweb/wemini 签名 */
export async function requestCommunity<T = unknown>(options: {
url: string
method?: Method
data?: Record<string, unknown>
header?: Record<string, string>
}): Promise<T> {
const token = Taro.getStorageSync(STORAGE_TOKEN)
const res = await Taro.request({
url: `${COMMUNITY_API_BASE}${options.url}`,
method: options.method || 'GET',
data: options.data,
timeout: 8000,
header: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(options.header || {}),
},
})
if (res.statusCode >= 400) {
throw new Error(errMsg(res.data, '请求失败'))
}
return res.data
}
/** 兼容 community services/api.ts */
export async function requestCommunityCompat<T = unknown>(options: {
url: string
method?: Method
data?: Record<string, unknown>
header?: Record<string, string>
}): Promise<T> {
return requestCommunity<T>(options)
}
/** 统一网关 VIP */
export async function requestGateway<T = unknown>(
path: string,
opts: { method?: Method; data?: Record<string, unknown>; auth?: boolean } = {},
): Promise<T> {
const token = Taro.getStorageSync(STORAGE_TOKEN)
const res = await Taro.request({
url: `${GATEWAY_API_BASE}${path.startsWith('/') ? path : `/${path}`}`,
method: opts.method || 'GET',
data: opts.data,
header: {
'Content-Type': 'application/json',
...(opts.auth !== false && token ? { Authorization: `Bearer ${token}` } : {}),
},
})
if (res.statusCode >= 400) {
throw new Error(errMsg(res.data, `HTTP ${res.statusCode}`))
}
return res.data
}
export const ensureWxLogin = ensureLogin