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

官方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)
        }
      }
    });
  },
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

以上的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;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102

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

运行结果

运动步数 
简单吧~,哪里写的不清楚可以留言交流

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
微信小程序是一款非常流行的移动应用程序,它提供了许多功能和API供开发者使用。获取微信运动步数是其中的一个功能,以下是一个使用Java编写的微信小程序获取微信运动步数的实例代码。 ```java import java.net.URL; import java.net.HttpURLConnection; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; public class WeChatMiniProgram { public static void main(String[] args) { // 小程序的AppID String appId = "your_app_id"; // 登录凭证code String code = "your_code"; // 小程序的AppSecret String appSecret = "your_app_secret"; // 获取access_token的URL String accessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&grant_type=authorization_code&js_code=" + code; try { // 发送HTTP请求获取access_token URL url = new URL(accessTokenUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); // 读取返回的数据 InputStream inputStream = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder response = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { response.append(line); } // 解析返回的数据 String jsonString = response.toString(); // 提取access_token和openid String accessToken = // 从jsonString中提取access_token String openId = // 从jsonString中提取openId // 获取微信运动步数的URL String stepCountUrl = "https://api.weixin.qq.com/sns/more_info?access_token=" + accessToken + "&openid=" + openId; // 发送HTTP请求获取微信运动步数 URL stepUrl = new URL(stepCountUrl); HttpURLConnection stepConnection = (HttpURLConnection) stepUrl.openConnection(); stepConnection.setRequestMethod("GET"); stepConnection.connect(); // 读取返回的数据 InputStream stepInputStream = stepConnection.getInputStream(); InputStreamReader stepInputStreamReader = new InputStreamReader(stepInputStream, "UTF-8"); BufferedReader stepBufferedReader = new BufferedReader(stepInputStreamReader); StringBuilder stepResponse = new StringBuilder(); String stepLine; while ((stepLine = stepBufferedReader.readLine()) != null) { stepResponse.append(stepLine); } // 解析返回的数据 String stepJsonString = stepResponse.toString(); // 提取微信运动步数 int stepCount = // 从stepJsonString中提取微信运动步数 // 输出微信运动步数 System.out.println("微信运动步数:" + stepCount); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码中,通过发送HTTP请求获取微信小程序的`access_token`和`openId`,然后使用`access_token`和`openId`来发送第二个HTTP请求,获取微信运动步数。需要注意的是,你需要将代码中的`your_app_id`、`your_code`和`your_app_secret`替换为你自己的实际值。此外,代码中的JSON解析部分需要进行具体的实现。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值