let siteinfo = require('../config');
let util = require('util');
const md5Util = require('md5')
const BASE_URL= siteinfo.siteroot + '/';
const SECRET = siteinfo.miniapp
const getSign = obj => {
let keys = Object.keys(obj)
let params = []
keys.sort()
keys.forEach(e => {
if (!util.isNull(obj[e])) {
params.push(e + '=' + util.trim(obj[e]))
}
})
params.push('key=' + SECRET)
let paramStr = params.join('&')
let signResult = md5Util.md5(paramStr).toUpperCase()
return signResult
}
function request(url, method, data, success, fail) {
if (!fail && !success && typeof data === 'function') {
success = data;
data = {publickey:util.getRandom(6)}
data.sign = getSign(data)
}else if (!fail) {
if (typeof data === 'function') {
fail = success
success = data
data = ""
} else if (typeof data === 'object') {
data.sign = getSign(data)
} else {
console.log("传递参数类型不正确");
}
}
var wxtask = wx.request({
url: BASE_URL + url,
header: {
'content-type':'application/json',
'Cookie':'PHPSESSID='+ wx.getStorageSync('session_id'),
},
method: method,
data: data,
success: function (res) {
switch (res.data.code) {
case 200:
success(res.data)
break
case 204:
success(res.data)
break
case 301:
wx.showModal({
content: res.data.msg,showCancel: false,
success: function (rel) {
wx.redirectTo({url: res.data.url})
}
})
break
case 302:
wx.showModal({
content: res.data.msg,
success: function (rel) {
if (rel.confirm) {
wx.navigateTo({url: res.data.url})
}
}
})
break
case 303:
wx.showModal({
content: res.data.msg,showCancel: false,
success: function (rel) {
if (rel.confirm) {
wx.switchTab({url: res.data.url})
}
}
})
break
case 404:
wx.showModal({
content: res.data.msg,showCancel:false,
success: function (rel) {
wx.navigateBack({delta:1})
}
})
break
case 401:
wx.navigateTo({ url: '/pages/helper/login' })
break
case 403:
wx.showModal({content:res.data.msg,showCancel:false})
break
case 500:
wx.redirectTo({url:'/pages/helper/error?msg=' + res.data.msg})
default:
break
}
},
fail: function (res) {
if (fail) {
fail(res)
}
}
})
return wxtask;
}
function Get(url, data, success, fail) {
return new Promise((resolve, reject) => {
return request(url, "GET", data, success, fail)
})
}
function Post(url, data, success, fail) {
return new Promise((resolve, reject) => {
return request(url, 'POST', data, success, fail)
})
}
function Put(url, data, success, fail) {
return new Promise((resolve, reject) => {
return request(url, 'PUT', data, success, fail)
})
}
function Delete(url, data, success, fail) {
return new Promise((resolve, reject) => {
return request(url, 'DELETE', data, success, fail)
})
}
exports.Get = Get;
exports.Post = Post;
exports.Put = Put;
exports.Delete = Delete;