微信小程序封装接口

1、config.js

/**
 * 小程序配置文件
 */

const host = 'http://10.10.13.191:8089'

const config = {
  host,
}


module.exports = config

2、app.js

//封装api
import api from "./utils/api/api"
const config = require('./config')

App({

    onLaunch(opts) {
        var that = this;
        that.checkNewVersion();
        //调用API从本地缓存中获取数据
        var logs = wx.getStorageSync('logs') || [];
        logs.unshift(Date.now());
        wx.setStorageSync('logs', logs);

        //微信登陆功能
        this.wxlogin();
        //判断是否由分享进入小程序
        if (opts.scene == 1007 || opts.scene == 1008) {
            this.globalData.share = true
            wx.navigateTo({
                url: '/pages/sublogin/sublogin',
            })
        } else {
            this.globalData.share = false
        };
        this.globalData.shareOpts = opts;
        wx.getSystemInfo({
            success: (res) => {
                this.globalData.height = res.statusBarHeight
            }
        })
    },
    // 检查版本更新
    checkNewVersion: function () {
        // 获取小程序更新机制兼容
        if (wx.canIUse("getUpdateManager")) {
            const updateManager = wx.getUpdateManager();
            updateManager.onCheckForUpdate(function (res) {
                // 请求完新版本信息的回调
                if (res.hasUpdate) {
                    updateManager.onUpdateReady(function () {
                        wx.showModal({
                            title: "更新提示",
                            content: "新版本已经准备好,是否重启应用?",
                            success: function (res) {
                                if (res.confirm) {
                                    // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
                                    updateManager.applyUpdate();
                                }
                            }
                        });
                    });
                    updateManager.onUpdateFailed(function () {
                        // 新的版本下载失败
                        wx.showModal({
                            title: "已经有新版本了哟~",
                            content: "新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~"
                        });
                    });
                }
            });
        } else {
            // 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示
            wx.showModal({
                title: "提示",
                content: "当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。"
            });
        }
    },
    wxlogin() {
        var that = this;
        wx.login({
            success: (res) => {//先获取code
                var code = res.code;
                this.getUserOpenId(code);
            },
            fail: (res) => {

            },
        })
    },
    onShow(opts) {
        console.log('App Show', opts)
        //判断是否由分享进入小程序
        if (opts.scene == 1007 || opts.scene == 1008) {
            this.globalData.share = true
            wx.navigateTo({
                url: '/pages/sublogin/sublogin',
            })
        } else {
            this.globalData.share = false
        };
        this.globalData.shareOpts = opts;
    },
    onHide() {
        console.log('App Hide')
    },
    getApi: new api(),
    globalData: {
        menulist: [],
        height: 0,
        share: false,
        hasLogin: false,
        openId: null,
        token: null,
        userInfo: null,
        location: '',
        servsers: '',
        imgservsers: '',
        appid: 'wx9f783fae71fc2416',
        shareOpts: null,
        phoneNumber: '',
        // amap: amap,
        // //高德key
        // amapKey:'3eeeb6a15d3d050bff425b312d42fb3b',
        // mch_id: '10000100',
        // device_info: 'WEB',
        // ak: "q8Hx6jH5Q6x5Squwx8hTgab96wsyLyij",
    },
    // 调用后台接口 传过去code获取openId
    getUserOpenId(code) {
        var code = code;
        const self = this
        wx.request({
            url: config.host + '/wechat/getOpenId.do',
            data: {
                'code': code
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success(res) {
                // console.log('拉取openid成功', res)
                self.globalData.openId = res.data.data.openId;
                wx.setStorage({
                    key: "openId",
                    data: res.data.data.openId
                })
                // self.getUserInfo();
            },
            fail(res) {
                console.log('拉取用户openid失败,将无法正常使用开放接口等服务', res);
                wx.showToast({
                    title: '拉取用户openid失败',
                    icon: 'none',
                    duration: 1500,
                })
            }
        })
    },
    //获取用户信息
    getUserInfo() {
        wx.getUserInfo({
            success: (res) => {
                console.log(res.userInfo);
                var userInfo = res.userInfo;
                this.globalData.userInfo = userInfo;
                var userInfoJSON = JSON.stringify(userInfo);
                wx.setStorage({
                    key: 'userInfo',
                    data: userInfoJSON,
                })
                this.userInfoSetInSQL(userInfo);
            },
            fail(res) {
                console.log('获取用户信息失败');
                wx.showModal({
                    title: '提示',
                    content: '您尚未进行授权,请点击确认按钮跳到授权界面',
                    confirmColor: '#F7262D',
                    success: (res) => {
                        console.log(res);
                        if (res.confirm) {
                            wx.navigateTo({
                                url: '/pages/login/login',
                            })
                        } else if (res.cancel) {
                            wx.navigateBack({
                                delta: -1
                            })
                        } else {
                            wx.navigateBack({
                                delta: -1
                            })
                        }
                    }
                })
            }
        })
    },
    //储存用户的openId到数据库
    userInfoSetInSQL(userInfo) {
        var that = this;
        var openId = this.globalData.openId;
        var id = wx.getStorageSync('user').id
        wx.request({
            url: config.host + '/wechat/login.do',
            data: {
                'id': id,
                'openId': openId,
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
                console.log(res)
                if (res.data.code == 0) {
                    wx.showToast({
                        title: '登陆成功',
                        icon: 'success',
                        duration: 1000,
                        mask: true,
                    })
                    //存入user
                    var user = res.data.user;
                    wx.setStorage({
                        key: 'user',
                        data: user,
                    })
                    wx.navigateTo({
                        url: '../home/home',
                    })
                }
                else {
                    //判断缓存中有没有数据
                    try {
                        var value = wx.getStorageSync('user')
                        if (value) {
                            console.log("+++++", value)
                            wx.navigateTo({
                                url: '/pages/home/home',
                            })
                        } else {
                            wx.navigateTo({
                                url: '/pages/login/login',
                            })
                        }
                    } catch (e) {
                        wx.navigateTo({
                            url: '/pages/login/login',
                        })
                    }
                }
            }
        })
    },
    
})

3、新建utils>api文件夹(api.js、request.js)

3.1  api.js

import request from "./request"
const config = require('../../config.js')

class api {
    constructor() {
        this.baseUrl = config.host
        this.request = new request
        this.request.setErrorhandle(this.errorhandle)
    }
    errorhandle(err) {
        if (err.data.message) {
            wx.showToast({
                title: err.data.message,
                icon: 'none',
                duration: 1500
            })
        }
    }
    //获取手机号码
    getPhone(param) {
        return this.request.getRequest(`${this.baseUrl}/wechat/getPhone.do`, param, false)
            .then(res => res.data)
    }
    //登录
    loginByPwd(param) {
        return this.request.postRequest(`${this.baseUrl}/wechat/loginByPwd`, param, false)
            .then(res => res.data)
    }
    //获取流调信息核查列表+未核查的条数
    getLiuDiaoNum(param) {
        return this.request.getRequest(`${this.baseUrl}/fy/info/list`, param, true)
            .then(res => res.data)
    }
    //获取提前报备核实--未核查的条数
    getVerifyNum(param) {
        return this.request.getRequest(`${this.baseUrl}/fy/info/list`, param, true)
            .then(res => res.data)
    }
    //常态化隔离措施--字典项
    getIsolationMeasures(param) {
        return this.request.getRequest(`${this.baseUrl}/system/dict/data/list`, param, true)
            .then(res => res.data)
    }
    //常态化涉疫类型--字典项
    getWadeDiseaseType(param) {
        return this.request.getRequest(`${this.baseUrl}/system/dict/data/list`, param, true)
            .then(res => res.data)
    }
    //根据身份证查询
    getByIdCard(param) {
        return this.request.getRequest(`${this.baseUrl}/fy/userinfo/getByIdCard`, param, true)
            .then(res => res.data)
    }
    //人员核查--上报
    report(param) {
        return this.request.postRequest(`${this.baseUrl}/fy/info`, param, true)
            .then(res => res.data)
    }
    //人员核查--核查
    verification(param) {
        return this.request.putRequest(`${this.baseUrl}/fy/info`, param, true)
            .then(res => res.data)
    }
    //人员核查--核查返回
    verificationReturn(param) {
        return this.request.putRequest(`${this.baseUrl}/fy/info`, param, true)
            .then(res => res.data)
    }
    //获取省市县街道
    getCity(param) {
        return this.request.getRequest(`${this.baseUrl}/system/cityinfo/list`, param, true)
            .then(res => res.data)
    }
    //获取城区、乡镇
    getStreetlist() {
        return this.request.getRequest(`${this.baseUrl}/grid/gridfyvillage/streetlist`, false)
            .then(res => res.data)
    }
    //获取网格
    getGridlist(param) {
        return this.request.getRequest(`${this.baseUrl}/grid/gridfyvillage/gridlist`, param, false)
            .then(res => res.data)
    }
    //获取小区、村庄
    getVillagelist(param) {
        return this.request.getRequest(`${this.baseUrl}/grid/gridfyvillage/villagelist`, param, false)
            .then(res => res.data)
    }
    //获取待隔离转运
    getWaitlist(param) {
        return this.request.getRequest(`${this.baseUrl}/fy/info/transport/list`, param, true)
            .then(res => res.data)
    }
    //待隔离转运详情 弹窗--提交
    application(param) {
        return this.request.postRequest(`${this.baseUrl}/fy/application`, param, true)
            .then(res => res.data)
    }


}
export default api

3.2  request.js

class request {
    constructor() {

    }
    // 异常处理
    setErrorhandle(handle) {
        this.errorhandle = handle
    }
    // get请求
    getRequest(url, data, istoken) {
        if (istoken == false) {
            return this.requestAll(url, data, 'GET', false)
        } else {
            return this.requestAll(url, data, 'GET', true)
        }
    }
    // post请求
    postRequest(url, data, istoken) {
        if (istoken == false) {
            return this.requestAll(url, data, 'POST', false)
        } else {
            return this.requestAll(url, data, 'POST', true)
        }
    }
    // put请求
    putRequest(url, data, istoken) {
        if (istoken == false) {
            return this.requestAll(url, data, 'PUT', false)
        } else {
            return this.requestAll(url, data, 'PUT', true)
        }
    }
    requestAll(url, data, method, istoken) {
        var header = {};
        // 获取token
        if (istoken) {
            var token = wx.getStorageSync('token');
            header = {
                'content-type': 'application/json',
                Authorization: token
            }
        } else {
            header = {
                'content-type': 'application/json',
            }
        }
        return new Promise((resolve, reject) => {
            wx.request({
                url: url,
                data: data,
                header: header,
                method: method,
                success: res => {
                    if (res.statusCode == 200) {
                        // 未登录code 跳转登录页
                        if (res.data.code == 401) {
                            // 跳转登录页
                            var user = wx.setStorageSync('user', '');
                            wx.showToast({
                                title: "长时间未登录,请重新登录!",
                                icon: 'none',
                                duration: 2000
                            })
                            setTimeout(function () {
                                wx.navigateTo({
                                    url: '/pages/index/index',
                                })
                            },2000);
                        } else {
                            // 正常返回
                            resolve(res)
                        }
                    } else {
                        if (this.errorhandle != null) {
                            this.errorhandle(res)
                        }
                    }
                },
                fail: res => {
                    if (this.errorhandle != null) {
                        this.errorhandle(res)
                    }
                    reject(res)
                }
            })
        })
    }
}
export default request

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值