微信小程序开发中个人总结
1.网络请求封装
function json2Form(json) {
var str = [];
for (var p in json) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
}
return str.join("&");
}
/**
* 网络请求
* @param app(token,url)
* @param method请求方式
* @param params请求参数
* @param
*/
function request(app, urlPath, method, params, onsuccess, onfail) {
wx.showLoading({
title: '加载中',
mask: true
});
wx.request({
url: app.globalData.url + urlPath,
method: method,
header: {
'content-type': method == 'POST' ?
'application/x-www-form-urlencoded' : 'application/json'
},
data: method == 'POST' ? json2Form(params) : params,
success: function (res) {
if (urlPath == 'wx/cust/getOneQueueByShopId' || urlPath == 'wx/cust/deletequeue' || urlPath == 'wx/cust/deletequeue') {
onsuccess(res)
wx.hideLoading()
}
else if (res.data.state) {
wx.hideLoading()
onsuccess(res.data)
} else {
if (res.data.code === '110') {
wx.hideLoading()
wx.showToast({
title: '登录失效,请刷新界面',
icon: 'none'
})
checkLogin(app)
} else {
wx.hideLoading()
wx.showToast({
title: '请求错误:' + res.data.message,
icon: 'none'
})
}
}
}, fail: function (res) {
console.log(res)
onfail(res.data)
setTimeout(function () {
wx.hideLoading()
wx.showToast({
title: res.errMsg,
icon: 'none'
})
}, 1000)
}
})
}
2.微信小程序支付
function wxpay(app, orderId, couponsId, redirectUrl) {
wx.request({
url: app.globalData.url + 'wx/pay/info',
data: {
token: app.globalData.token,
orderId: orderId,
couponsId: couponsId,
payType: 2
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: 'POST',
success: function (res) {
if (res.data.state) {
var retData = res.data.data;
// 发起支付
wx.requestPayment({
timeStamp: retData.timeStamp,
nonceStr: retData.nonceStr,
package: retData.packageValue,
signType: retData.signType,
paySign: retData.paySign,
success: function (res) {
wx.redirectTo({
url: '/pages/service/pay-success/index?status=1&&orderId=' + orderId
})
},
fail: function (res) {
if (res.errMsg == "requestPayment:fail cancel") {
wx.request({
url: app.globalData.url + 'wx/pay/cancel',
data: {
token: app.globalData.token,
payId: retData.payId
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: 'POST',
success: function (res) {
},
fail: function (e) {
}
});
}
wx.redirectTo({
url: '/pages/service/pay-success/index?status=0&&orderId=' + orderId
})
}
})
} else {
wx.showToast({title: '发起支付失败:' + res.data.message});
}
}
})
}
// header: {"Content-Type": "application/x-www-form-urlencoded"}不同请求的请求头部不一样
网友评论