使用java获取微信运动步数

1 篇文章 0 订阅
1 篇文章 0 订阅

最近写小程序的时候遇到一个问题,获取对于java小白而言,获取微信运动步数还是有点困难,下面为大家介绍一下我是怎么获取微信运动步数的。

原理:

在这里插入图片描述
详情请去这个网址:
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html

解决:

首先微信小程序端需要通过wx.login来获取用户的session_key,该文件名为:app.js
App({
  onLaunch: function() {
    wx.login({
      success: result => {
        wx.request({
          url: 'http://localhost:8080/wx/login',
          data: {
            code: result.code
          },
          success: res => {
            //获取响应结果里的session_key
            this.globalData.sessionKey = res.result.session_key;
          },
          fail: err => {
            console.log(err);
          }
        })
      }
    })
  },
  globalData: {
    userInfo: null,
    sessionKey: null
  }
})
服务器端通过接受传过来的code,然后通过另外一个接口来获取用户的session_key和open_id,目前只会用到session_key.
    @GetMapping("/wx/login")
    public Result<?> wxLogin(String code) {
        String openId = "";
        JSONObject openIdObject = null;
        try {
            openId = new HttpRequestor().doGet(WxUtils.url + code + WxUtils.url0);
            //alibaba的json
            openIdObject = JSON.parseObject(openId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok(openIdObject);
    }

WxUtil文件,工具类借鉴:
https://blog.csdn.net/macex002/article/details/81200185?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

public class WxUtils {
    private static final String APP_ID = "小程序APPID";
    private static final String SECRET = "小程序SECRET";
    String openId = "";

    public static String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APP_ID + "&secret=" + SECRET + "&js_code=";
    public static String url0 = "&grant_type=authorization_code";

    // 步数转卡路里
    public static float getDistanceByStep(long steps) {
        return steps * 0.6f / 1000;
    }


    /**
     * 微信解密运动步数
     *
     * @param sessionKey
     * @param encryptedData
     * @param iv
     * @return
     */
    public static String decryptWeChatRunInfo(String sessionKey, String encryptedData, String iv) {
        String result = null;
        byte[] encrypData = Base64.decodeBase64(encryptedData);
        byte[] ivData = Base64.decodeBase64(iv);
        byte[] sessionKeyB = Base64.decodeBase64(sessionKey);
        try {
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(sessionKeyB, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] doFinal = cipher.doFinal(encrypData);
            result = new String(doFinal);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}

引用maven

		<!-- json -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>
微信端获取运动步数,通过后端的接口将encryptedData,iv,sessionKey发送给后端.后端来解密.
getRunData() {
    wx.getWeRunData({
      success: function (res) {
         wx.request({
          url: 'http://localhost:8080/wx/runData',
          method: 'post',
          header: {
        'content-type': 'application/json'
          },
          data: {
            iv: res.iv,
            encryptedData: res.encryptedData,
            sessionKey: app.globalData.sessionKey
          },
          success: res => {
             console.log(res);
          },
          fail: err => {
            wx.showModal({
              title: '提示',
              content: '请先关注“微信运动”公众号并设置数据来源,以获取并提供微信步数数据',
              showCancel: false,
              confirmText: '知道了'
            })
          }
        })
      }
    })
  }
后端接受到数据,通过AES解密
	@PostMapping("/runData")
    public Result<?> runData(@RequestBody WxEntity wxEntity) {
        String encryptedData = wxEntity.getEncryptedData();
        String iv = wxEntity.getIv();
        String sessionKey = wxEntity.getSessionKey();
        if (encryptedData == null && iv == null && sessionKey == null) {
            return Result.error("错误,没有数据");
        }
        String decrypt = null;
        //解密
        try {
            decrypt = WxUtils.decryptWeChatRunInfo(sessionKey, encryptedData, iv);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (decrypt == null) {
            log.info("解密失败");
        } else {
            log.info("解析成功");
        }
       JSONObject stepInfoListJson = JSON.parseObject(decrypt);
        //解析json,获取stepInfoList下面的步数
        JSONArray stepInfoList = JSON.parseArray(stepInfoListJson.getString("stepInfoList"));
        //获取今天的步数
        JSONObject today = Objects.requireNonNull(stepInfoList).getJSONObject(0);
        return Result.ok(today);
    }
微信小程序是一款非常流行的移动应用程序,它提供了许多功能和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解析部分需要进行具体的实现。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值