官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/werun/wx.getWeRunData.html
可以通过wx.getWeRunData获取用户过去三十天的微信运动步数。
前提
使用这个接口有两个前提:
- 需先调用wx.login接口进行登录,请参考之前的博客:https://blog.csdn.net/joyce_lcy/article/details/83380515
- 调用前需要用户授权scope.werun,请参考之前的博客:https://blog.csdn.net/joyce_lcy/article/details/83345549
登录部分需要通过登录拿到token,在之后的请求头部带上token信息,以便在后端知道是哪个用户。
wx.getWeRunData
wx.getWeRunData成功回调的参数res有两个属性encryptedData
和iv
,需要传到后端进行解密。
解密后的Json结构如下:
- timestap:时间戳,表示数据所对应的时间
- step:当天的微信步数
{
"stepInfoList": [
{
"timestamp": 1445866601,
"step": 100
},
{
"timestamp": 1445876601,
"step": 120
}
]
}
后端可以进行处理,得到类似于下图的数据,再将需要展示的数据返回给前端。
完整代码示例如下:
const app = getApp()
Page({
onLoad: function () {
const self = this;
wx.login({
success: function (res) {
if (res.code) {
wx.request({
url: "https://www.xxx.com.cn/api/auth/login",
method: 'POST',
data: {
code: res.code
},
success: function (res) {
app.globalData.userInfo.token = res.data.token;
app.globalData.userInfo.session_key = res.data.session_key;
self.getWeRunData();
}
})
}
}
});
},
getWeRunData: function(){
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) {
wx.request({
url: "https://www.xxx.com.cn/api/getWeRunData",
method: 'POST',
header: {
"accept": "application/json",
"Authorization": app.globalData.userInfo.token
},
data: {
encryptedData: res.encryptedData,
iv: res.iv,
session_key: app.globalData.userInfo.session_key
},
success: function (res) {
console.log("步数:" + res.data.data.steps);
wx.showModal({
title: '步数',
content: res.data.data.steps + '',
})
}
})
},
fail: function (res) {
wx.showModal({
title: '提示',
content: '请先关注“微信运动”公众号并设置数据来源,以获取并提供微信步数数据',
showCancel: false,
confirmText: '知道了'
})
}
})
},
fail(){
wx.showModal({
title: '提示',
content: '请开启获取微信步数权限',
showCancel: false,
confirmText: '知道了'
})
}
})
}
}
})
}
})