大家好,我们团队新研发了一个“健步走”功能,其中用到了微信运动的数据,今天和大家分享一下。
在开发之前,需要在小程序的“用户隐私保护指引”中设置收集微信运动步数,才可进行开发!
前端需要用到 uni.getWeRunData 拿到加密后的数据(encryptedData),将数据返给后端进行解密处理,处理后则可拿到当前用户包含今天在内的31天的运动数据!
代码中,简单写了获取权限判断,如果申请权限时用户拒绝了,则再次点击获取会打开小程序权限设置去开启权限等,具体可自行继续优化!
<button @click="getWeRunData()">获取步数</button>
<script>
export default {
components: {},
mixins: [],
data() {
return {
hasAuth: false, // 是否有授权(true:有;false:没有)
showSettingBtn: false, // 是否打开设置(true说明拒绝,点击需打开设置;false说明同意,不需要打开设置)
}
},
onShow() {
this.checkWeRunAuth(); // 检查微信运动授权
},
onLoad() {
},
methods: {
// 检查微信运动权限
checkWeRunAuth() {
uni.getSetting({
success: (res) => {
this.hasAuth = res.authSetting['scope.werun'] || false;
},
fail: (err) => {
console.error('获取权限设置失败:', err);
uni.showToast({
title: '权限检查失败',
icon: 'none'
});
}
});
},
// 获取微信运动数据
getWeRunData() {
// 先检查权限
if (!this.hasAuth) {
if (this.showSettingBtn) {
this.openSetting(); // 打开设置页面
} else {
this.requestWeRunAuth(); // 请求微信运动权限
}
return;
}
// 已有权限,直接获取数据
uni.getWeRunData({
success: (res) => {
// 此处需要将 encryptedData 发送到开发者服务器解密
// 这里仅作示例,实际开发中需要替换为真实的接口调用
console.log('获取微信运动加密数据成功:', res);
// 模拟服务器解密后返回的步数数据
this.stepCount = Math.floor(Math.random() * 10000) + 5000;
uni.showToast({
title: '获取步数成功',
icon: 'success'
});
},
fail: (err) => {
console.error('获取微信运动数据失败:', err);
uni.showToast({
title: '获取步数失败',
icon: 'none'
});
}
});
},
// 请求微信运动权限
requestWeRunAuth() {
uni.authorize({
scope: 'scope.werun',
success: () => {
this.hasAuth = true;
uni.showToast({
title: '权限获取成功',
icon: 'success'
});
this.getWeRunData(); // 权限获取成功后再次尝试获取数据
},
fail: (err) => {
console.error('用户拒绝授权');
this.hasAuth = false;
this.showSettingBtn = true;
uni.showModal({
title: '权限申请',
content: '需要获取微信运动权限才能获取您的步数数据',
showCancel: false,
confirmText: '知道了'
});
}
});
},
// 打开设置页面
openSetting() {
uni.openSetting({
success: (res) => {
if (res.authSetting['scope.werun']) {
this.hasAuth = true;
this.showSettingBtn = false;
this.tipsText = '请授权微信运动权限以获取步数数据';
uni.showToast({
title: '权限已开启',
icon: 'success'
});
this.getWeRunData();
} else {
uni.showToast({
title: '权限未开启',
icon: 'none'
});
}
},
fail: (err) => {
uni.showToast({
title: '打开设置失败',
icon: 'none'
});
}
});
}
}
}
</script>
最终调用后端解密接口,返回的用户31天运动数据。