// 請求方法
function request(url, data = {}, method = "GET") {
return new Promise(function(resolve, reject) {
wx.request({
url: url,
data: data,
method: method,
header: {
"Content-Type": "application/x-www-form-urlencoded",
"token": wx.getStorageSync('token')
},
success: function(res) {
if (res.statusCode == 200) {
resolve(res)
// TODO
} else {
reject(res.errMsg);
}
},
fail: function(err) {
reject(err)
console.log("request failed", err)
}
})
});
}
/**
* 微信授權登錄
*/
function loginByWeixin() {
return new Promise(function(resolve, reject) {
wx.login({
success: function(res) {
if (res.code) {
this.request('url', {
code: res.code
}).then((res) => {
if (res.statusCode === 200) {
wx.setStorageSync('openid', res.data.openid); //存儲openid
wx.setStorageSync('token', res.data.openid); //存儲token
wx.setSotrageSync('userInfo', res.data.userInfo); //存儲用戶信息
// 其他業務邏輯
}
});
}
},
fail: function(err) {
reject(err);
}
})
})
}
// 微信支付
function requestPayParam(url, data = {}) {
this.request(url, data, 'GET').then(function(res) {
if (res.state === 1) {
wx.requestPayment({
'timeStamp': res.timeStamp,
'nonceStr': res.nonceStr,
'package': res.package,
'signType': res.signType,
'paySign': res.paySign,
'success': function(res) {
// 其他業務邏輯
wx.redirectTo({
url: 'success',
})
},
'fail': function(err) {
wx.redirectTo({
url: 'fail',
})
},
})
}
});
}
【微信小程序】Promise請求等方法的封裝
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.