当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 微信小程序获取微信运动步数的实例代码

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

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

微信小程序api-微信运动

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

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

小程序端代码

get3rdsession: function () {
  let that = this
  wx.request({
   url: 'https://localhost/login.php',
   data: {
    code: this.data.code
   },
   method: 'get', // options, get, head, post, put, delete, trace, connect
   success: function (res) {
    var sessionid = res.data;
    that.setdata({ sessionid: sessionid })
    wx.setstoragesync('sessionid', sessionid)
    that.decodeuserinfo()
   }
  })
 },
 decodeuserinfo: function () {
  let that = this
  wx.request({
   url: 'https://localhost/decrypt.php',
   data: {
    encrypteddata: that.data.encrypteddata,
    iv: that.data.iv,
    session: wx.getstoragesync('sessionid')
   },
   method: 'get', // options, get, head, post, put, delete, trace, connect
   // header: {}, // 设置请求的 header
   success: function (res) {
    let todaystep = res.data.stepinfolist.pop()
    that.setdata({
     step: todaystep.step
    });
   }
  })
 },
 onload: function () {
  let that = this
  wx.login({
   success: function (res) {
    let code = res.code
    that.setdata({ code: code })
    wx.getwerundata({//解密微信运动
     success(res) {
      const wrunencrypteddata = res.encrypteddata
      that.setdata({ encrypteddata: wrunencrypteddata })
      that.setdata({ iv: res.iv })
      that.get3rdsession()//解密请求函数
     }
    })
   }
  })
 }

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

login.php部分代码

$appid = '你的appid';
$appsecret = '你的appsecret';

$url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appsecret.'&js_code='.$_get['code'].'&grant_type=authorization_code';

$content = file_get_contents($url);
$content = json_decode($content);
echo $content->session_key;

decrypt.php部分代码

$pc = new wxbizdatacrypt($appid, $sessionkey);
$errcode = $pc->decryptdata($encrypteddata, $iv, $data );

if ($errcode == 0) {
  print($data . "\n");
} else {
  print($errcode . "\n");
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网