1. 基本功能:
点击授权按钮,就可使用自己的微信账号进行登录,第三方网站或应用就可以获取用户基本信息(如昵称、头像等),简化账号密码登录流程
2. 三种授权方式:
- PC版扫码授权
- H5版授权
- 小程序插件版授权
3. 第三方网站获取微信小程序授权流程:
4.小程序的登录授权流程:
5. 实现代码:
// Promise封装用户的数据信息
const wxgetUserInfo = function () {
return new Promise((resolve, reject) => {
wx.getUserInfo({
lang: 'zh_CN',
success(res) {
resolve(res);
},
fail(res) {
reject(res);
}
})
});
}
// 判断用户是否登录
const checkLogin = function () {
let res = getApp().globalData.userSession.token ? true : false;
let res1 = getApp().globalData.isLog;
let res2 = res && res1;
if (res2) {
let newTime = Math.round(new Date() / 1000);
if (getApp().globalData.expiresTime < newTime) return false;
}
return res2;
}
// 注销
const logout = function () {
getApp().globalData.userSession.token = '';
getApp().globalData.isLog = false;
}
//检查用户是否授权了用户信息(scope.userInfo)-存入缓存
const chekWxLogin = function () {
return new Promise((resolve, reject) => {
wx.getSetting({
success(res) {
if (!res.authSetting['scope.userInfo']) {
return reject({
authSetting: false
});
} else {
wx.getStorage({
key: 'cache_key',
success(res) {
if (checkLogin()) {
return resolve({
userinfo: getApp().globalData.userInfo,
isLogin: true
});
} else {
wxgetUserInfo().then(userInfo => {
userInfo.cache_key = res.data;
return resolve({
userInfo: userInfo,
isLogin: false
});
}).catch(res => {
return reject(res);
})
}
},
fail() {
getCodeLogin((code) => {
wxgetUserInfo().then(userInfo => {
userInfo.code = code;
return resolve({
userInfo: userInfo,
isLogin: false
});
}).catch(res => {
return reject(res);
})
});
}
})
}
},
fail(res) {
return reject(res);
}
})
})
}
//授权过后自动登录
const autoLogin = function () {
return new Promise((resolve, reject) => {
wx.getStorage({
key: 'cache_key',
success(res) {
wxgetUserInfo().then(userInfo => {
userInfo.cache_key = res.data;
return resolve(userInfo);
}).catch(res => {
return reject(res);
})
},
fail() {
getCodeLogin((code) => {
wxgetUserInfo().then(userInfo => {
userInfo.code = code;
return resolve(userInfo);
}).catch(res => {
return reject(res);
})
});
}
});
})
}
// 获取登录时需要的 code
const getCodeLogin = function (successFn) {
wx.login({
success(res) {
successFn(res);
}
})
}
注: wx.login()方法:调用接口获取登录凭证(code)。
通过凭证进而换取用户登录态信息,包括用户的唯一标识(openid)及本次登录的会话密钥(session_key)等。用户数据的加解密通讯需依赖会话密钥完成。