微信小程序的 request 封裝

背景

以前小程序代碼混亂,因此新項目一開始就準備弄個微信小程序的 request 的封裝php

流程

先來講說整個流程:html

  1. appjs 裏面已進入就去獲取用戶信息,若是沒有登陸則默認登陸,這裏不作錯誤處理
  2. 用戶必須贊成受權才能進行操做,若是不一樣意受權則會一直跳轉到受權頁面
  3. 在受權頁面點擊受權登陸後,調用登陸接口,成功後返回調起受權的頁面,

app.js

onLaunch 裏面獲取用戶信息vue

appSelf = this;
        // 應用程序第一次進入,獲取用戶信息,不作任何錯誤處理
        userInfo().then( (res)=>{
            console.log(res);// 打印結果
            if (!res.code) {
                appSelf.globalData.userInfo = res
            }
        }).catch( (errMsg)=>{
            console.log(errMsg);// 錯誤提示信息
        });

httpUtils.js

request 的封裝

const request = function (path, method, data, header) {
    let user_id = "";
    let token = "";
    try {
        user_id = wx.getStorageSync(USER_ID_KEY);
        token = wx.getStorageSync(TOKEN_KEY);
    } catch (e) {}
    header = header || {};
    let cookie = [];
    cookie.push("USERID=" + user_id);
    cookie.push("TOKEN=" + token);
    cookie.push("device=" + 1);
    cookie.push("app_name=" + 1);
    cookie.push("app_version=" + ENV_VERSION);
    cookie.push("channel=" + 1);
    header.cookie = cookie.join("; ");
    return new Promise((resolve, reject) => {
        wx.request({//後臺請求
            url: API_BASE_URL + path,
            header: header,
            method: method,
            data: data,
            success: function (res) {
                if (res.statusCode !== 200) {
                    reject(res.data)
                } else {
                    if (res.data.code === 20006) {
                        login().then( (res)=>{
                            resolve(res)
                        }).catch( (errMsg)=>{
                            reject(errMsg);
                        })
                    }
                    resolve(res.data)
                }
            },
            fail: function (res) {
                reject("not data");
            }
        });
    });
}

login

const login = function () {
    try {
        wx.removeStorageSync(USER_ID_KEY)
        wx.removeStorageSync(TOKEN_KEY)
    } catch (e) {}
    return new Promise((resolve, reject) => {
        wx.login({
            success: res => {
                let code = res.code;
                // 已經受權,能夠直接調用 getUserInfo 獲取頭像暱稱,不會彈框
                wx.getUserInfo({
                    withCredentials: true,
                    success: res => {
                        let userInfo = res.userInfo;
                        let name = userInfo.nickName;
                        let avatar = userInfo.avatarUrl;
                        let sex = userInfo.gender;
                        let data = {
                            code: code,
                            encryptedData: res.encryptedData,
                            iv: res.iv,
                            name: name,
                            avatar: avatar,
                            sex: sex,
                            from: FROM,
                        };
                        request("/api/user/login/byWeChatApplet", "POST", data).then( (res)=>{
                            if (!res.code) {
                                try {
                                    wx.setStorageSync(USER_ID_KEY, res.user_id);
                                    wx.setStorageSync(TOKEN_KEY, res.token)
                                } catch (e) {
                                    reject(JSON.stringify(e));
                                }
                            }
                            resolve(res)
                        }).catch( (errMsg)=>{
                            reject(errMsg)
                        });
                    },
                    fail: function (res) {
                        console.log(res);

                        if (res.errMsg && res.errMsg.startsWith("getUserInfo:fail") && res.errMsg.search("unauthorized") != -1) {
                            // 跳轉受權頁面
                            wx.navigateTo({
                                url: '/pages/auth/auth'
                            })
                            return;
                        }
                        wx.getSetting({
                            success: (res) => {
                                if (!res.authSetting["scope.userInfo"]) {
                                    // 跳轉受權頁面
                                    wx.navigateTo({
                                        url: '/pages/auth/auth'
                                    })
                                }
                            }
                        });
                    }
                })
            }
        })
    });
};

auth.js

受權頁面 jsgit

Page({
    data: {
    },
    onLoad: function () {
        self = this;
    },

    auth: function (e) {
        console.log(app.globalData.userInfo);
        if (e.detail.userInfo) {
            login().then( (res)=>{
                console.log(res);// 打印結果
                if (res.code) {
                    // 接口錯誤
                    return
                }
                // 跳轉回上一個頁面
                wx.navigateBack()
            }).catch( (errMsg)=>{
                console.log(errMsg);// 錯誤提示信息
            });
        }
    },

});

項目地址

https://github.com/lmxdawn/wx...github

一個 vue + thinkphp5.1 搭建的後臺管理:https://github.com/lmxdawn/vu...thinkphp

演示:
圖片描述小程序

相關文章
相關標籤/搜索