E企盈营销工具技术服务商 热线:4006-838-530

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

E企盈直播平台营销卖货系统

官方APIhttps://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啦,就是这么简单,我们看看运行结果:运行结果 简单吧~,哪里写的不清楚可以留言交流

赞(0) 打赏
未经允许不得转载:E企盈小程序开发-热线:4006-838-530 » 微信小程序开发-获取微信运动步数
分享到: 更多 (0)
E企盈小程序直播营销卖货系统
E企盈直播平台营销卖货系统

评论 抢沙发

E企盈小程序开发

联系我们联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏