小程序前端接入微信登录与环境配置

This commit is contained in:
stu2not
2026-04-16 18:18:48 +08:00
parent 1b4c47f77a
commit db888df50f
7 changed files with 81 additions and 58 deletions

View File

@@ -1,4 +1,19 @@
import { request, BASE_URL } from './api'
import Taro from '@tarojs/taro'
import { request } from './api'
export interface WechatLoginPayload {
code: string
nickname?: string
avatar_url?: string
}
export interface LoginSession {
access_token: string
token_type: string
expires_in: number
user_id: number
}
export interface Parent {
user_id: number
@@ -11,22 +26,18 @@ export interface Parent {
}
// 微信登录
export async function wechatLogin(code: string): Promise<{ token: string; user_id: number }> {
// TODO: 实现微信登录 - 通过 code 换取 openid然后调用后端
// 这里先返回 mock 数据
const mockParent: Parent = {
user_id: 1,
openid: 'mock_openid_' + code,
nickname: '微信用户',
status: 1,
}
// 保存模拟 token
const token = 'mock_token_' + Date.now()
Taro.setStorageSync('token', token)
Taro.setStorageSync('user_id', mockParent.user_id)
return { token, user_id: mockParent.user_id }
export async function wechatLogin(data: WechatLoginPayload): Promise<LoginSession> {
const session = await request<LoginSession>('/auth/login', {
method: 'POST',
data,
})
Taro.setStorageSync('token', session.access_token)
Taro.setStorageSync('token_type', session.token_type)
Taro.setStorageSync('user_id', session.user_id)
Taro.setStorageSync('expires_in', session.expires_in)
return session
}
// 创建家长
@@ -66,10 +77,12 @@ export function getToken(): string {
// 清除 token
export function clearToken(): void {
Taro.removeStorageSync('token')
Taro.removeStorageSync('token_type')
Taro.removeStorageSync('user_id')
Taro.removeStorageSync('expires_in')
}
// 获取当前用户ID
export function getCurrentUserId(): number {
return Taro.getStorageSync('user_id') || 0
}
}