微信小程序获取获取用户微信运动数据

15 篇文章 0 订阅
9 篇文章 0 订阅

官方API地址

https://developers.weixin.qq.com/miniprogram/dev/api/wx.getWeRunData.html
推荐一篇博文:https://www.cnblogs.com/liqinghuan/p/9184222.html

实现步骤

1.调用小程序API:wx.login获取code和sessionKey;
2.调用小程序API: wx.getWeRunData获取微信运动数据(加密的)
3.解密步骤2的数据;

这里我后台的代码块用的是PHP语言(PHP是世界上最好的语言)

先奉上微信代码块

const util = require('../../utils/util.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    run_day:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //1、调用小程序API:wx.login获取code和sessionKey;
    var that = this;
    wx.login({
      success: function (resLogin) {
        console.log(resLogin.code);
        if (resLogin.code) {
          wx.request({
            url: 'https://www.****.cn/weirun/onlogin',
            data: {
              code: resLogin.code
            },
            success: function (resSession) {
              console.log(resSession);//session_key
              //2、调用小程序API: wx.getWeRunData获取微信运动数据(加密的);
              wx.getWeRunData({
                success(resRun) {
                  const encryptedData = resRun
                  console.info(resRun);
                  //3、解密步骤2的数据;
                  wx.request({
                    url: 'https://www.*****.cn/weirun/Decrypt',
                    data: {
                      encryptedData: resRun.encryptedData,
                      iv: resRun.iv,
                      code: resLogin.code
                    },
                    method: 'GET',
                    // header: {}, // 设置请求的 header
                    success: function (resDecrypt) {
                      that.setData({ run_day: resDecrypt.data });
                      console.log(that.data.run_day);
                    }
                  });
                }
              })
            }
          })
        } else {
          console.log('获取用户登录态失败!' + res.errMsg)
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})

接下来是PHP代码块

<?php
namespace App\Http\Controllers\WeRun;
use App\Http\Controllers\Controller as BaseController;
use App\Http\Controllers\PHP\WXBizDataCrypt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class RunController extends BaseController
{
    protected $crontab;
    protected $user;
    protected $appid="wxa2d68e****32ec56"; //小程序Appid
    protected $appsecret="cc3e33e924677********fb168813426"; //小程序秘钥
    public function __construct()
    {
    }
    public function onlogin(Request $request){
        $code=$request->all('code');
        if (!empty($code)){
            $sessionKey=$this->GetSession("wxa2d68e****32ec56", "cc3e33e924677********fb168813426",$code['code']);
            $arr=json_decode($sessionKey,true);
            if (!empty($sessionKey))
            {
            	//三种方法
                //1.
                //$_SESSION[$code['code']]=$arr['session_key'];
                //2.
                //session()->put($code['code'],$arr['session_key']);
                //$sess=session()->get($code['code']);
                //3.
                Redis::setex('code:'.$code['code'],3600,$arr['session_key']);
                $user=Redis::get('code:'.$code['code']);
                $data=[
                    'msg'=>'登录成功',
                    'info'=>$user
                ];
                return json_encode($data);
            }
        }
    }
    public function GetSession($appid,$appsecret,$code){
        $url= "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code";
        $arr = $this->http_curl($url);
        if (!empty($arr))
        {
            return json_encode($arr);
        }
        return null;
    }
    protected function http_curl($url, $arr = '', $type = 'get', $res = 'json')
    {
        $ch = curl_init();
        //设置curl的参数
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        }
        //采集
        $output = curl_exec($ch);
        if ($res == 'json') {
            if ($err = curl_errno($ch)) {
                //要在关闭之前获得curl_errno
                curl_close($ch);
                //请求失败,返回错误信息
                return $err;
            } else {
                //请求成功
                return json_decode($output, true);
            }
        }
    }

    /**
     * @param Request $request
     * @return string
     * 微信获取加密的用户步数
     */
    public function Decrypt(Request $request){

        $rqt = $request->all();
        $appid="wxa2d68ed24d32ec56";
        $sessionKey = Redis::get('code:'.$rqt["code"]); //取出OnLogin的sessionKey
        $rawData = $this->AES_decrypt($appid,$rqt['encryptedData'], $sessionKey, $rqt['iv']);
        if (!empty($rawData)){
            return json_encode($rawData);
        }
        return json_encode("解密失败");
    }

    /**
     * @param $appid
     * @param $encryptedData
     * @param $sessionKey
     * @param $iv
     * @return string
     * 解密算法
     */
    public function AES_decrypt($appid,$encryptedData,$sessionKey,$iv){
        $datacrypt=new WXBizDataCrypt($appid,$sessionKey);
        $errCode = $datacrypt->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            $arr_s=json_decode($data,true);
            $arr=$arr_s['stepInfoList'];
            $array=[];
            if($arr){
                foreach ($arr as $k=>$v){
                    $array[date("Y-m-d H:i:s",$v['timestamp'])]=$v['step'];
                }
            }
            return $array;
        } else {
            return json_encode($errCode);
        }

    }
}
//引入一个官方的PHP语言解密代码(里面有demo。看了就懂)
//https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html

在快写完的时候,PHP报解密的类找不到,但是我的命名空间没有问题,解决方法: composer dump-autoload

上面就是获取微信运动数据的所有代码,有哪些不对的地方欢迎评论,谢谢!~

在这里插入图片描述

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值