小程序实现授权完整流程

 

小程序实现授权完整流程_第1张图片小程序html页面


    1、同意当前小程序获取我的微信头像;
    2、同意当前小程序获取我的微信昵称等其他信息;
    

小程序js页面

const util = require('../../utils/util.js');
Page({
    data: {

    },
    onLoad: function (options) {

    },
    getInfo(e){
        if(!e.detail.userInfo){
            wx.showModal({
                title: '提示',
                content: '您拒绝了授权部分功能无法使用',
                showCancel: false
            })
            return;
        }else{
            wx.setStorageSync('userInfo', e.detail.userInfo);
            this.login()
        }
    },
    login(){
        let token = wx.getStorageSync('token');
        console.log(token)
        let tokenStr = util.baseApi2 +'/user/check-token';
        let loginStr = util.baseApi2+'user/wxapp/login';
        let that = this;
        if(token){
            util.fetchData2(tokenStr,{token}).then((res)=>{
                if(res.code!=0){
                    wx.removeStorageSync('token');
                    that.login();
                }else{
                    wx.navigateBack({});
                }
            })
        }else{
            wx.login({
                success: (res)=>{
                    util.fetchData2(loginStr,{code: res.code,type: 2}).then((data)=>{
                        console.log(data)
                        if(data.code==1000){
                            that.register()
                        }else if(data.code!=0){
                            wx.showModal({
                                title: '提示',
                                content: '请求出错',
                                showCancel: false
                            })
                            return;
                        }else{
                            wx.setStorageSync('token', data.data.token);
                            wx.setStorageSync('uid', data.data.uid);
                            wx.navigateBack({
                                
                            })
                        }
                    })
                }
            })
        }
    },
    register(){
        let that = this;
        let regStr = util.baseApi2+'/user/wxapp/register/complex';
        wx.login({
            success: (res)=>{
                let code = res.code;
                wx.getUserInfo({
                    success: (data)=>{
                        let iv = data.iv;
                        let encryptedData = data.encryptedData;
                        util.fetchData2(regStr,{
                            code,
                            iv,
                            encryptedData
                        }).then((res)=>{
                            that.login();                 
                        })
                    }
                })
            }
        })
    }
})

注意部分接口来自于api工厂

你可能感兴趣的:(小程序)