Administrator
发布于 2025-10-11 / 13 阅读
0
0

微信小程序在 app.js 中定义全局登录函数

// 在 app.js 中定义全局登录函数

App({

// 全局登录函数

loginWithRedirect: async function(redirectUrl = '') {

try {

// 获取临时登录凭证

const loginRes = await this.login();

// 调用后端登录接口

const authRes = await this.auth(loginRes.code);

// 存储登录凭证

this.saveAuthInfo(authRes);

// 处理跳转逻辑

return this.handleRedirect(redirectUrl);

} catch (error) {

console.error('登录失败:', error);

return { success: false, error };

}

},

// 内部登录方法

login: function() {

return new Promise((resolve, reject) => {

wx.login({

success: res => res.code ? resolve(res) : reject(new Error('获取code失败'),

fail: reject

});

});

},

// 认证方法

auth: function(code) {

return new Promise((resolve, reject) => {

wx.request({

url: 'https://api.example.com/auth',

method: 'POST',

data: { code },

success: res => resolve(res.data),

fail: reject

});

});

},

// 存储认证信息

saveAuthInfo: function(authData) {

wx.setStorageSync('token', authData.token);

this.globalData.hasLogin = true;

},

// 跳转处理

handleRedirect: function(redirectUrl) {

const targetUrl = redirectUrl || '/pages/index/index';

// 判断页面是否需要登录

const protectedPages = ['/pages/profile/profile', '/pages/orders/orders'];

const isProtected = protectedPages.includes(targetUrl);

// 执行跳转

if (isProtected) {

wx.redirectTo({ url: targetUrl });

} else {

wx.switchTab({ url: targetUrl });

}

return {

success: true,

redirectUrl: targetUrl

};

},

// 全局数据

globalData: {

hasLogin: false,

redirectUrl: ''

}

});

//--------------

// 在需要登录的页面调用

const loginResult = await getApp().loginWithRedirect('/pages/user/user');

if (loginResult.success) {

console.log(`登录成功,将跳转到: ${loginResult.redirectUrl}`);

} else {

console.error('登录失败:', loginResult.error);

}

//----------

// 场景1:在页面加载时检查登录状态

Page({

onShow() {

if (!getApp().globalData.hasLogin) {

const pages = getCurrentPages();

const currentPage = pages[pages.length - 1].route;

this.redirectToLogin(currentPage);

}

},

redirectToLogin(currentPage) {

getApp().loginWithRedirect(currentPage).then(res => {

if (!res.success) {

wx.showToast({

title: '登录失败,请重试',

icon: 'none'

});

}

});

}

});

// 场景2:在按钮点击事件中触发登录

handleUserAction() {

getApp().loginWithRedirect('/pages/orders/orders');

}


评论