欢迎光临,了解微信小程序开发,就上易用通!

微信小程序--获取微信运动步数的实例代码

发布:2018-05-07 15:10浏览: 来源:网络 作者:cola

现在运动计步很火,无论是蚂蚁森林,还是微信上都很火爆,本文介绍了微信小程序微信运动步数的实例代码,分享给大家

微信小程序API-微信运动 
https://mp.weixin.qq.com/debug/wxadoc/dev/api/we-run.html#wxgetwerundataobject

思路:wx.login获取的code请求获取的session_key,wx.getWeRunData获取的iv,encryptData,将它们一起发送到后台解密就行了。

安全顾虑,因为只是示例所以直接传递session_key了,为了安全最好按照下图的方式加密后存储到Redis中再传递key。

微信小程序--获取微信运动步数的实例代码(图1)

 

小程序端代码

 

  1. get3rdSession: function () {
  2. let that = this
  3. wx.request({
  4. url: 'https://localhost/login.php',
  5. data: {
  6. code: this.data.code
  7. },
  8. method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
  9. success: function (res) {
  10. var sessionId = res.data;
  11. that.setData({ sessionId: sessionId })
  12. wx.setStorageSync('sessionId', sessionId)
  13. that.decodeUserInfo()
  14. }
  15. })
  16. },
  17. decodeUserInfo: function () {
  18. let that = this
  19. wx.request({
  20. url: 'https://localhost/decrypt.php',
  21. data: {
  22. encryptedData: that.data.encryptedData,
  23. iv: that.data.iv,
  24. session: wx.getStorageSync('sessionId')
  25. },
  26. method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
  27. // header: {}, // 设置请求的 header
  28. success: function (res) {
  29. let todayStep = res.data.stepInfoList.pop()
  30. that.setData({
  31. step: todayStep.step
  32. });
  33. }
  34. })
  35. },
  36. onLoad: function () {
  37. let that = this
  38. wx.login({
  39. success: function (res) {
  40. let code = res.code
  41. that.setData({ code: code })
  42. wx.getWeRunData({//解密微信运动
  43. success(res) {
  44. const wRunEncryptedData = res.encryptedData
  45. that.setData({ encryptedData: wRunEncryptedData })
  46. that.setData({ iv: res.iv })
  47. that.get3rdSession()//解密请求函数
  48. }
  49. })
  50. }
  51. })
  52. }

后台这使用的是官方PHP版本Demo:先处理login的请求,login.php直接返回session_key,然后再一起请求decrypt.php进行解密。

 

login.php部分代码

 

  1. $appid = '你的appid';
  2. $appsecret = '你的appsecret';
  3.  
  4. $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appsecret.'&js_code='.$_GET['code'].'&grant_type=authorization_code';
  5.  
  6. $content = file_get_contents($url);
  7. $content = json_decode($content);
  8. echo $content->session_key;
 

decrypt.php部分代码

 

  1. $pc = new WXBizDataCrypt($appid, $sessionKey);
  2. $errCode = $pc->decryptData($encryptedData, $iv, $data );
  3.  
  4. if ($errCode == 0) {
  5. print($data . "\n");
  6. } else {
  7. print($errCode . "\n");
  8. }




免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。