在我的项目中微信小程序单独需要一个登录页面并包含微信快捷登录,而在app中已经有原生登录页面,只需判断是否包含登录,如果已登录原生安卓或苹果端使用js方法把token信息带入即可,我的实现方法如下
在iOS原生中监听webview页面的加载,在加载完成后进行登录信息传参
//传入用户token信息
NSString *promptToken = [NSString stringWithFormat:@"getToken(\"%@\")",[[JYUserManager shareUser] getAuthorization]];
[_webView evaluateJavaScript:promptToken completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"传Token:%@",promptToken);
}];
//传入用户userid信息
NSString *userId = [NSString stringWithFormat:@"userId(\"%@\")",[[JYUserManager shareUser] getUserId]];
[_webView evaluateJavaScript:userId completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"传userId");
}];
然后回到uni代码中App.vue下
// #ifdef H5
window['getToken'] = val => {
uni.setStorageSync('accessToken', val);
},
window['userId'] = val => {
uni.setStorageSync('userId', val);
}
// #endif
},
需要注意的是这个用户的身份信息token有过期的可能性,所以需要配合后台接口检查token是否过期以及进行更新.
微信小程序快捷登录流程
在微信平台中,首先需要遵循微信的登录流程规则大致流程图如下所示:
具体在uni-app中实现如下
- 获取到微信临时登录凭证
//获取微信凭证Openid
uni.login({
provider: 'weixin',
success: function(res) {
console.log('微信登录凭证' + res.code);
//存储凭证
uni.setStorageSync('wxCode', res.code);
- 微信授权登录
点击微信图标登录通过授权拿到微信的encryptedData和iv信息
onGetPhoneNumber(e){
if(e.detail.errMsg=="getPhoneNumber:fail user deny"){ //用户拒绝授权
//拒绝授权后弹出一些提示
this.$mHelper.toast('微信授权未成功');
}
else{
console.log(e.detail);
//允许授权
this.wx_encryptedData = e.detail.encryptedData;
this.wx_iv = e.detail.iv;
console.log('登录code'+uni.getStorageSync('wxCode'));
console.log(this.wx_encryptedData);
console.log('iv'+this.wx_iv);
}
},
-
接下来配合后台接口将code,encryptedData,iv等参数信息传给后台,然后就OK了.需要注意code这个临时凭证后台使用后就会失效了,如果登录失败或者身份过期重新登录临时凭证需要重新获取后再传给后台.