咫尺资讯站一一为您提供时下热门前沿动态

查看更多
大发国际官网> 微信小程序资讯> 微信小程序开发-获取微信运动步数

微信小程序开发-获取微信运动步数

阅读:343微信小程序

官方API

https://mp.weixin.qq.com/debug/wxadoc/dev/api/we-run.html#wxgetwerundataobject

步骤

最近做一个微信小程序需用到微信运动数据,根据文档,我写了一个demo;先总结一下步骤,流程简单如下:

 

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

我后台用C#的,其实其他语言原理一样,只有解密数据一个核心方法;

实现代码:

前端(小程序的 JS)
const util = require('../../utils/util.js')Page({  /**   * 页面的初始数据   */  data: {      runData:[],  },  /**   * 生命周期函数--监听页面加载   */  onLoad: function (options) {    //1、调用小程序API:wx.login获取code和sessionKey;    var that=this;    wx.login({      success: function (resLogin) {        if (resLogin.code) {          wx.request({            url: 'http://localhost:9281/wxapp/onlogin',            data: {              code: resLogin.code            },            success: function (resSession) {                //2、调用小程序API: wx.getWeRunData获取微信运动数据(加密的);              wx.getWeRunData({                success(resRun) {                  const encryptedData = resRun                  console.info(resRun);                  //3、解密步骤2的数据;                  wx.request({                    url: 'http://localhost:9281/wxapp/decrypt',                    data: {                      encryptedData: resRun.encryptedData,                      iv: resRun.iv,                      code: resLogin.code                    },                    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT                    // header: {}, // 设置请求的 header                    success: function (resDecrypt) {                      var runData = JSON.parse(resDecrypt.data.data)                      console.info(runData);                      if (runData.stepInfoList)                      {                        runData.stepInfoList = runData.stepInfoList.reverse()                        for (var i in runData.stepInfoList)                        {                          runData.stepInfoList[i].date = util.formatTime(new Date(runData.stepInfoList[i].timestamp*1000))                        }                        that.setData({ runData: runData.stepInfoList });                      }                                          }                  });                }              })            }          })        } else {          console.log('获取用户登录态失败!' + res.errMsg)        }      }    });  },})

以上的http://localhost:9281 是本地环境啦

后端(c# .net MVC)

//控制器 public class WxAppController : BaseController    {        /// <summary>        /// 登录,获取sessionKey,对应上面的http://localhost:9281/wxapp/onlogin        /// </summary>        /// <param name="code">code</param>        /// <returns></returns>        public ActionResult OnLogin(string code)        {            if (string.IsNullOrEmpty(code) == false)            {               var sessionKey=  WxAppHelper.GetSessionKey("你的appid", "你的appSecret", code);                if (string.IsNullOrEmpty(sessionKey) == false)                {                    //将sessionKey放入缓存,key是code                    CacheHelper.Set(code, sessionKey, 360);                     return WritingSuccess("登录成功");                }                            }            return WritingFailed("登录失败");        }        /// <summary>        /// 解密,对应上面的http://localhost:9281/wxapp/decrypt        /// </summary>        /// <returns></returns>        public ActionResult Decrypt()        {            string code = Request["code"];            string iv = Request["iv"];            string encryptedData = Request["encryptedData"];            string sessionKey = CacheHelper.Get(code); //取出OnLogin的sessionKey            string rawData = WxAppHelper.AES_decrypt(encryptedData, sessionKey, iv);            if (string.IsNullOrEmpty(rawData) == false)            {                return WritingSuccess("解密成功", rawData);            }            return WritingFailed("解密失败");        }//WxAppHelper的GetSession public static AppSession GetSession(string appid,string appSecret,string code)        {            string api = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";            string url = string.Format(api, appid, appSecret, code);            var sessionStr = HttpUtil.Get(url);            if (string.IsNullOrEmpty(sessionStr) == false)            {                return JsonHelper.Json2Object<AppSession>(sessionStr);            }            return null;        }/// <summary>        /// AES解密        /// </summary>        /// <param name="encryptedDataStr"></param>        /// <param name="key"></param>        /// <param name="iv"></param>        /// <returns></returns>        public static string  AES_decrypt(string encryptedDataStr, string key, string iv)        {            RijndaelManaged rijalg = new RijndaelManaged();            //-----------------                  //设置 cipher 格式 AES-128-CBC                  rijalg.KeySize = 128;            rijalg.Padding = PaddingMode.PKCS7;            rijalg.Mode = CipherMode.CBC;            rijalg.Key = Convert.FromBase64String(key);            rijalg.IV = Convert.FromBase64String(iv);            byte[] encryptedData = Convert.FromBase64String(encryptedDataStr);            //解密                  ICryptoTransform decryptor = rijalg.CreateDecryptor(rijalg.Key, rijalg.IV);            string result=null;            using (MemoryStream msDecrypt = new MemoryStream(encryptedData))            {                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))                {                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))                    {                        result= srDecrypt.ReadToEnd();                    }                }            }            return result;        }     //实体    public class AppSession    {        public string session_key;        public int expires_in;        public string openid;    }

ok啦,就是这么简单,我们看看运行结果:

运行结果

小程序
简单吧~,哪里写的不清楚可以留言交流

【温馨提示】大发国际应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至1223636800@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于大发国际应用观点。用户与作者的任何交易与本站无关,请知悉。

热门模板

咨询热线

400-078-9990