getWeRunData接口可以获取“微信运动”最近三十天的步数。简单来说主要下面几步:1、调用
wx.login得到session_key,后面解密运动步数需要用到。由于session_key静默登陆即可获取,也就不需要引导用户点击授权登录按钮了
onload(){
let that = this;
wx.login({
success(res) {
if (res.code) {
//根据返回的code,调用后端接口解密session_key
that.$func.api(that.$apiConfig.getSessionKey(),{
code: res.code,
},res => {
if(res.statusCode === 200){
//得到session_key,调用获取运动步数的方法
that.getWeRunData(res.data.session_key);
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
},
})
}
2、通过wx.getSetting查看是否开启了获取运动步数的权限,如果没有开启,就调用wx.authorize弹出授权窗口来进行授权,授权成功,调用wx.getWeRunData,得到encryptedData和iv,然后配合刚才的session_key调用后台接口进行解密,就能得到运动步数:
getWeRunData: function(session_key){
var that = this;
wx.getSetting({
success: function (res) {
if(res.authSetting['scope.werun']===false){
wx.showModal({
title: '提示',
content: '请开启获取微信步数权限',
showCancel: false,
confirmText: '知道了'
})
}else{
wx.authorize({
scope: 'scope.werun',
success () {
wx.getWeRunData({
success: function (res) {
that.$func.api(that.$apiConfig.decodeWechat(),{
sessionKey:session_key,
encryptedData:res.encryptedData,
iv:res.iv,
},res => {
var stepInfoList = res.data.stepInfoList; //最近三十天步数列表
//得到最近一天的步数存储到global中,tab1页面也用到了。
getApp().globalData.weRunData = stepInfoList[stepInfoList.length-1].step;
})
},
fail: function (res) {
wx.showModal({
title: '提示',
content: '请先关注“微信运动”公众号并设置数据来源,以获取并提供微信步数数据',
showCancel: false,
confirmText: '知道了'
})
}
})
},
fail(){
wx.showModal({
title: '提示',
content: '请开启获取微信步数权限',
showCancel: false,
confirmText: '知道了'
})
}
})
}
}
})
},
