1.login.wxml 點擊登錄按鈕 調(diào)用獲取授權(quán)的函數(shù)
<view class="login-container">
<image src="/images/pet.jpg" class="pet"></image>
<button class="btn-login" type="primary" open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="getUserInfo">授權(quán)登錄</button>
</view>
2.login.js 獲取用戶的信息 微信頭像、昵稱、地區(qū)等
將這些userInfo存入全局變量中
同時獲取openid:當(dāng)用戶點擊登錄頁面的按鈕后進行授權(quán)登錄,如果成功窟蓝,會有一個code,然后再向后臺請求偏形。
//授權(quán)
? getUserInfo: function(e) {
? ? console.log(e)
? ? let self = this;
? ? app.globalData.userInfo = e.detail.userInfo
? ? console.log('****用戶基本信息*****')
? ? console.log(app.globalData.userInfo)
? ? self.getOpenId();
? },
? //獲取用戶openid
? getOpenId: function() {
? ? let self = this
? ? wx.login({
? ? ? timeout: 10000,
? ? ? success: (result) => {
? ? ? ? if (result.code) {
? ? ? ? ? wx.request({
? ? ? ? ? ? url: `http://10.110.5.35:3000/getUserOpenId`,
? ? ? ? ? ? data: {
? ? ? ? ? ? ? code: result.code
? ? ? ? ? ? },
? ? ? ? ? ? success: res => {
? ? ? ? ? ? ? console.log(res)
? ? ? ? ? ? ? wx.reLaunch({
? ? ? ? ? ? ? ? url: '/pages/index/index',
? ? ? ? ? ? ? })
? ? ? ? ? ? }
? ? ? ? ? })
? ? ? ? }
? ? ? },
? ? ? fail: () => {},
? ? ? complete: () => {}
? ? });
? }
3.后臺
//獲取用戶openid
router.get("/getUserOpenId",?async?(ctx,?next)?=>?{
??let?params?=?ctx.request.query;
??console.log('*****params*****')
??console.log(params)
??const?appId?=?'';?//?AppID(小程序ID)
??const?appSecret?=?'';//?AppSecret(小程序密鑰)
??try?{
????const?res?=?await?koa2Req({
??????url:?`https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${params.code}&grant_type=authorization_code`
????})
????let?data?=?JSON.parse(res.body);
????ctx.body?=?{
??????"success":?true,
??????"data":?data
????};
??}?catch?(error)?{
????console.log(error)
????ctx.body?=?{
??????"success":?false,
??????"message":?error
????};
??}
})
4.再首頁index.js中判斷用戶是否登錄的方法就是判斷全局userInfo是否為null
onLoad: function() {
? ? let self = this;
? ? let userInfo = app.globalData.userInfo;
? ? console.log('%%%%用戶%%%%%%')
? ? console.log(userInfo)
? ? if(userInfo == null){
? ? ? console.log('用戶未登錄,跳轉(zhuǎn)到登錄頁面')
? ? ? ? wx.redirectTo({
? ? ? ? ? url: '/pages/login/login',
? ? ? ? })
? ? }
? },