其他分享
首页 > 其他分享> > Uni-app 之网络请求封装、响应数据加密解密

Uni-app 之网络请求封装、响应数据加密解密

作者:互联网

一、效果图

 

 二、http.js网络请求封装

import {
    config
} from '../config.js'

import md5 from 'js-md5'
import { aes_encrypt, aes_decrypt } from '@/utils/aes_endecrypt.js';
import {Base64} from '@/utils/base64.js'

export const apiResquest = (prams) => { //prams 为我们需要调用的接口API的参数 下面会贴具体代码

    //设置接口验证
    var timestamp = new Date().getTime(), token = md5(timestamp + config.APITOKEN)
    token = aes_encrypt(token + '_' + timestamp)
    let headerData = {}
    let dataObj = null
    //因为我们的GET和POST请求结构不同这里我们做处理,大家根据自己后台接口所需结构灵活做调整吧
    if (prams.method === "GET") {
        headerData = {
            'content-type': 'application/json',
            'token': token
        }
    } else {
        headerData = {
            'content-type': 'application/x-www-form-urlencoded',
            'token': token
        }
        dataObj = prams.query
    }
    return new Promise((resolve, reject) => {
        // 判断环境
        let url = (config.env=='develop'?config.test_url:config.base_url) + prams.url; //请求的网络地址和局地的api地址组合
        uni.showLoading({
            title: '加载中',
            mask: true
        })
        return uni.request({
            url: url,
            data: dataObj,
            method: prams.method,
            header: headerData,
            success: (res) => {
                //解密
                var data = JSON.parse(Base64.decode(aes_decrypt(Base64.decode(res.data))))
                console.log(data)
                uni.hideLoading()
                //这里是成功的返回码,大家根据自己的实际情况调整
                if (data.code == -2) {
                    uni.showToast({
                        title: data.message,
                        duration: 3000,
                        icon: "none"
                    })
                    return;
                }
                resolve(data);
            },
            fail: (err) => {
                reject(err);
                console.log(err)
                uni.hideLoading()
            }
        });
    })
}

三、服务端加密

function myAseEncode($txt, $key="")
{
    return base64_encode(openssl_encrypt($txt,"AES-128-ECB",$key,0));
}

function myAseDecode($txt, $key="")
{
    return openssl_decrypt($txt,"AES-128-ECB",$key,0);
}
/**
 * 返回数据
 * @param int $code
 * @param string $message
 * @param array $data
 */
function returnMsg($code = 200,$message = '',$data = [])
{
    $return['code'] = (int)$code;
    $return['message'] = $message;
    //$return['data'] = is_array($data) ? $data : ['info'=>$data];
    $return['data'] = $data;
    die(json_encode(myAseEncode(base64_encode(json_encode($return)))));
}

 

标签:return,url,config,app,封装,token,Uni,data,prams
来源: https://www.cnblogs.com/yang-2018/p/16221041.html