登录步骤
step1: 获取本地微信信息
step2: 获取本地用户信息
step3: 获取用户头像和昵称
setp4: 获取code
step5: 远程登录
业务说明(首次访问)
首次访问时获取不到微信信息和用户信息,需要用户授权获取头像和昵称(本地保存为微信信息)。
拿到头像和昵称信息后再通过wx.login()获取code。
再请求远程接口传递参数(头像、昵称、code),服务端注册新用户并返回用户信息(含openId,本地保存为用户信息)。
业务说明(再次访问)
再次访问时可以获取到本地微信信息和本地用户信息,无需远程登录
以下是代码
// step1: 获取本地微信信息
// step1: 获取本地微信信息
getLocalWxinfo() {
let result = localstorageJS.getStorageInfoSync('wxinfo')
if(result.status==1) {
console.log('Get Local wxinfo Success')
let wxinfo = result.data
this.setData({
wxinfo: wxinfo,
hasAuthorized: true
})
}else {
console.warn('Get Local wxinfo Failure')
}
},
// step2: 获取本地用户信息
// step2: 获取本地用户信息
getLocalUserinfo() {
let result = localstorageJS.getStorageInfoSync('userinfo')
let accessToken = localstorageJS.getStorageInfoSync('accessToken')
let refreshToken = localstorageJS.getStorageInfoSync('refreshToken')
if(result.status==1) {
console.log('Get Local userinfo Success')
let userinfo = result.data
this.setData({
userinfo: userinfo,
accessToken: accessToken.data,
refreshToken: refreshToken.data,
hasLogin: true
})
}else {
console.warn('Get Local userinfo Failure')
}
},
// step3: 获取用户头像和昵称
// step3: 获取用户头像和昵称
onGetUserInfo: function (e) {
var that = this
// 判断是否授权
if(that.data.hasAuthorized) {
// 获取code
that.wxLogin()
}else {
wx.getUserProfile({
desc: '用于完善用户资料',
success: (res) => {
console.log('wx.getUserProfile success', res)
let wxinfo = res.userInfo
// 页面缓存
this.setData({
wxinfo: wxinfo,
hasAuthorized: true // 表示微信用户已经授权获取用户名和昵称
})
// 本地存储
let key = 'wxinfo'
localstorageJS.setStorageInfo(wxinfo, key)
// 获取code
that.wxLogin()
},
fail (err) {
console.error('wx.getUserProfile failure', err)
}
})
}
},
// setp4: 获取code
// setp4: 获取code
wxLogin() {
var that = this
wx.login({
success (res) {
console.log('wx.login success', res)
if (res.code) {
that.remoteLogin(res.code)
} else {
console.log('wx.login get code failure', res.errMsg)
}
},
fail (err) {
console.error('wx.login failure', err)
}
})
},
// step5: 远程登录
远程登录成功后除了返回用户信息,本代码还返回token信息(看自己项目需求)
// step5: 远程登录
remoteLogin(code) {
var that = this
let url = '........'
wx.request({
url: url,
method: 'POST',
header: {
'content-type': 'application/json'
},
data: {
address: code,
logo: that.data.wxinfo.avatarUrl,
name: that.data.wxinfo.nickName
},
success(res) {
console.log('remote login wx.request success', res)
let code = res.data.code
if(code==0) {
// 获取用户信息成功
let userinfo = res.data.data.userInfo
let accessToken = res.data.data.accessToken
let refreshToken = res.data.data.refreshToken
// 页面缓存
that.setData({
userinfo: userinfo,
hasLogin: true, // 表示已经远程登录成功
})
// 本地存储
let key = 'userinfo'
localstorageJS.setStorageInfo(userinfo, key)
localstorageJS.setStorageInfo(accessToken, 'accessToken')
localstorageJS.setStorageInfo(refreshToken, 'refreshToken')
}else {
}
},
fail(err) {
console.error('remote login wx.request failure', err)
}
})
},
另外提供本地缓存的工具类代码
localstorageJS
// 获取本地存储信息(同步,有返回)
function getStorageInfoSync(key) {
let result = {status:0, message:'Get Storage Info Failure', data:null}
try {
var info = wx.getStorageSync(key)
if (info) {
result = {status:1, message:'Get Storage Info Success', data:info}
}
} catch (e) {
result = {status:0, message:'Get Storage Info Error', data:null}
}
return result
}
// 存储用户基本信息(异步,无返回)
function setStorageInfo(info, key) {
wx.setStorage({
key: key,
data: info,
success: res => {
console.log('wx.setStorage success', res)
},
fail: err => {
console.error('wx.setStorage failure', err)
},
complete: res => {
console.log('wx.setStorage complete')
}
})
}
module.exports = {
setStorageInfo,
getStorageInfoSync
}
另附Python写的服务器端登录处理逻辑
服务器环境(flask+tornado+sqlite)
# 用户登录(新用户注册后返回用户信息,老用户直接返回用户信息)
@app.route('/appfls/wxlogin', methods=['POST'])
def appflswxlogin():
if request.method == 'POST':
try:
# 获取小程序端传递的数据
JSCODE = request.form['code']
nickname = request.form['nickname']
avatarurl = request.form['avatarurl']
# 根据code获取openid
APPID = '......'
SECRET = '......'
authorization_code = 'authorization_code'
url = 'https://api.weixin.qq.com/sns/jscode2session?appid='+APPID+'&secret='+SECRET+'&js_code='+JSCODE+'&grant_type='+authorization_code
res = requests.request('GET',url)
if(res.status_code==200):
openid = res.json()['openid']
else:
app.logger.error('##### Get openid error.')
app.logger.error(str(res.status_code))
return {'status':0, 'message':'Get openid error.'} # status==0 异常,==1 正常
# 连接数据库
con = sqlite3.connect("./db/appfls.s3db") # 不同项目使用不同的数据库
# 根据openid查询用户信息
con.row_factory = sqlite3.Row
cur = con.cursor()
ssql = "select * from tbl_user where openid='" + openid+"' order by id desc"
app.logger.info('##### Query user by openid.')
app.logger.info(ssql)
cur.execute(ssql)
rows = cur.fetchone()
# 用户不存在则创建
if(rows is None):
app.logger.info('##### The user does NOT exist.')
isql = "insert into tbl_user ('openid','nickname','avatarurl') values (?,?,?)" # 创建新用户
app.logger.info('##### Create a new user.')
app.logger.info(isql)
cur.execute(isql, (openid,nickname,avatarurl))
con.commit()
cur.close()
else:
app.logger.info('##### The user already exists.')
except Exception as e:
app.logger.error('##### Wechat login exception.')
app.logger.error(str(e))
return {'status':0, 'message':'Wechat login exception.', 'exception':str(e)}
else:
return {'status':1, 'message':'Wechat login success.', 'openid':openid}
finally:
# 关闭数据库连接
con.close()
else:
app.logger.error('##### NOT post request.')
return {'status':0, 'message':'NOT post request.'}
另附退出登录处理逻辑
退出时清空缓存,重置页面数据
// 退出登录
onLogout: function (e) {
var that = this
wx.showModal({
title: '提示',
content: '退出登录吗?',
success (res) {
if (res.confirm) {
console.log('用户点击确定')
try {
wx.clearStorageSync()
console.log('wx.clearStorageSync success')
that.setData({
hasLogin: false,
userinfo: null,
hasAuthorized: false,
wxinfo: null,
accessToken: null,
refreshToken: null
})
} catch(e) {
console.error('wx.clearStorageSync failure', e)
}
} else if (res.cancel) {
console.log('用户点击取消')
}
}
})
},