最近因为公司业务一直在做微信小程序的项目,趁此机会将最近踩过的一些坑总结记录下。 微信小程序登陆相关 前端调用wx.login(),获取临时登录凭证code 通过wx.request()将code发给服务器
|
最近因为公司业务一直在做微信小程序的项目,趁此机会将最近踩过的一些坑总结记录下。 微信小程序登陆相关![]()
//app.js
const NOLOGINCODE = 1000003 //未登录
const SUCCESS = 1000001 //成功
App({
onLaunch: function () {
var loginFlag = wx.getStorageSync('sessionId');
var that = this;
if (loginFlag) {
// 检查 session_key 是否过期
wx.checkSession({
// session_key 有效(未过期)
success: function () {
var userInfo = wx.getStorageSync('wxUserInfo')
if (userInfo) {
that.globalData.hasUserInfo = true
}
},
// session_key 过期
fail: function () {
// session_key过期,重新登录
that.doLogin();
}
});
} else {
// 无skey,作为首次登录
this.doLogin();
}
},
doLogin() {
this.log().then(res => {
this.$post('/auth', { code: res.code, }, false).then(data => {
wx.setStorageSync('sessionId', data.sessionId);
})
})
},
/**
*微信登录 获取code值,并将code传递给服务器
* @returns
*/
log() {
return new Promise(resolve => {
wx.login({
success(res) {
if (res.errMsg === "login:ok") {
resolve(res)
} else {
wx.showToast({
title: '微信登录失败',
icon: 'none',
duration: 1200
})
}
},
fail() {
wx.showToast({
title: '微信登录接口调用失败',
icon: 'none',
duration: 1200
})
}
})
})
},
globalData: {
baseurl: 'https://www.fake.shop'
}
})
复制代码
网络请求封装微信小程序中网络请求的api是wx.request(),但是这个请求是个异步回调的形式,每次发请求都要写好长一串,而且如果是嵌套的发请求,就会发现代码写的及其臃肿,所以将其 Promisefy是及其有必要的。 代码如下:
$get(url, data = {}, needToken = true) {
let SUCCESS = 200
var that = this
needToken ? (data.token = wx.getStorageSync('ToKen')) : ''
return new Promise((resolve, reject) => {
wx.request({
url: that.globalData.baseurl + url,
method: "GET",
header: {
'content-type': 'application/json'
},
data: data,
success(e) {
if (e.data.code == SUCCESS) {
resolve(e.data)
return
}
},
fail(e) {
wx.showModal({
title: '提示',
content: '请求失败',
showCancel: false
})
reject(e)
}
})
})
},
$post(url, data = {}, needToken = true) {
let that = this
let SUCCESS = 200
let TimeOut = 1000
var that = this
needToken ? (data.token = wx.getStorageSync('ToKen')) : ''
return new Promise((resolve, reject) => {
wx.request({
url: that.globalData.baseurl + url,
method: "POST",
//此处可以根据接口文档设置header头
// header: {
// 'content-type': 'application/x-www-form-urlencoded'
// },
data: data,
success(e) {
if (e.statusCode == SUCCESS) {
if (e.data.code == SUCCESS) {
resolve(e.data)
}
else {
reject(e)
wx.showModal({
title: '提示',
content: e.data.msg,
showCancel: false,
success: function (res) {
if (res.confirm) {
if (e.data.code == TimeOut) { //根据实际业务返回的code码判断是否过期
// 登录过期
that.doLogin();
}
}
}
})
}
} else {
wx.showModal({
title: '提示',
content: e.data.error,
showCancel: false
})
reject(e)
}
},
fail(e) {
console.log(e)
wx.showModal({
title: '提示',
content: '请求失败',
showCancel: false
})
reject(e)
},
complete(e) {
}
})
})
},
复制代码
微信公共号支付(微信浏览器)虽然是写小程序踩坑指南,但是在微信内的H5页面支付和小程序内掉起支付还是有相似之处的,顺便记录一下。 应用场景
准备
业务流程时序图
主要流程
code的获取
|
