Files
lucky_shop/common/js/auth.js

151 lines
3.6 KiB
JavaScript

export default {
data() {
return {
authInfo: {}
}
},
methods: {
/**
* 获取用户登录凭证code
*/
getCode(callback) {
// 微信小程序
// #ifdef MP-WEIXIN
uni.login({
provider: 'weixin',
timeout: 3000,
success: res => {
if (res.code) {
this.$api.sendRequest({
url: '/weapp/api/weapp/authcodetoopenid',
data: {
code: res.code
},
success: res => {
if (res.code >= 0) {
if (res.data.openid) this.authInfo.weapp_openid = res.data
.openid;
if (res.data.unionid) this.authInfo.wx_unionid = res.data
.unionid;
typeof callback == 'function' && callback(this.authInfo);
} else {
this.$util.showToast({
title: res.message ? res.message : '小程序配置错误'
});
}
}
})
}
},
fail: (res) => {
// #ifdef MP-WEIXIN
let scene = wx.getLaunchOptionsSync().scene;
if ([1154, 1155].indexOf(scene) == -1) {
this.$util.showToast({
title: res.errMsg
});
}
// #endif
}
})
// #endif
// #ifdef MP-ALIPAY
uni.login({
timeout: 3000,
success: res => {
if (res.code) {
this.$api.sendRequest({
url: '/aliapp/api/aliapp/authcodetouserid',
data: {
code: res.code
},
success: res => {
if (res.code >= 0) {
if (res.data.user_id) this.authInfo.ali_openid = res.data
.user_id;
typeof callback == 'function' && callback(this.authInfo);
} else {
this.$util.showToast({
title: res.message ? res.message : '小程序配置错误'
});
}
}
})
}
},
fail: (err) => {
this.$util.showToast({
title: res.errMsg
});
}
})
// #endif
// #ifdef H5
if (this.$util.isWeiXin()) {
this.$api.sendRequest({
url: '/wechat/api/wechat/authcode',
data: {
redirect_url: location.href,
scopes: 'snsapi_userinfo'
},
success: res => {
if (res.code >= 0) {
location.href = res.data;
}
}
});
}
// #endif
// #ifdef H5_XCX_5G_QUICKAPP_COM || H5_XCX_AIGC_QUICKAPP_COM || H5_5G_AIGC_QUICKAPP_COM || H5_TEST_AIGC_QUICKAPP_COM
this._huaweiSignIn(callback);
// #endif
},
/**
* 华为快应用帐号登录
*/
async _huaweiSignIn(callback) {
try {
const HwService = require('@/common/js/hw-jssdk.js').default;
// 确保 HwService 已初始化
if (!HwService.isQuickAppEnv()) {
console.warn('[Auth] 非快应用环境,跳过华为帐号登录');
return;
}
const userInfo = await HwService.Account.signIn();
if (userInfo && userInfo.openId) {
// 将华为 openId 传给后端换取系统 token
this.$api.sendRequest({
url: '/wechat/api/quickapp/huawei_auth',
data: {
openid: userInfo.openId,
unionid: userInfo.unionId,
nickname: userInfo.displayName,
avatar: userInfo.avatarUrl,
gender: userInfo.gender
},
success: res => {
if (res.code >= 0) {
if (res.data.openid) this.authInfo.hw_openid = res.data.openid;
if (res.data.unionid) this.authInfo.hw_unionid = res.data.unionid;
typeof callback == 'function' && callback(this.authInfo);
} else {
this.$util.showToast({
title: res.message ? res.message : '华为帐号登录失败'
});
}
}
});
}
} catch (error) {
console.error('[Auth] 华为帐号登录失败:', error);
this.$util.showToast({
title: '华为帐号登录失败'
});
}
}
}
}