uniapp+egg.js获取微信步数(wx.getWeRunData)

uniapp

  1. 调用uni.login()获取code

  2. 调用wx.getWeRunData()获取encryptedData、iv

  3. 请求后端接口,传递code、encryptedData、iv参数

    created() {
    			let copyThis = this;
    			// 调用微信登录方法获取code
    			uni.login({
    				provider: 'weixin',
    				success(res) {
    					//调用微信步数接口获取(encryptedData、iv)
    					wx.getWeRunData({
    						success(res2){
    							//调用后端接口,传递参数
    							uni.request({
    								url: 'http://127.0.0.1:7001',
    								data: {
    									code: res.code,
    									encryptedData:res2.encryptedData,
    									iv:res2.iv
    								},
    								success(res3) {
    									let {date,step} = res3.data.data;
    									copyThis.opts2.title.name = step[step.length-1].toString();
    									copyThis.chartData.categories = date;
    									copyThis.chartData.series[0].data = step;
    									copyThis.chartsShow =  true;
    								}
    							})
    						}
    					})
    				}
    			});
    		}

    egg.js

  4. 获取前端传递过来的参数

  5. 去小程序开发平台拿到appId、AppSecretuniapp+egg.js获取微信步数(wx.getWeRunData)_第1张图片

  6. 请求微信接口传递appid、secret(AppSecret)、js_code(code)参数

    https://api.weixin.qq.com/sns/jscode2sessionappid=${appId}&secret=${AppSecret}&js_code=${code}&grant_type=authorization_code
  7. 引入WXBizDataCrypt解密文件,new WXBizDataCrypt传递参数appId、session_key。下载文件

  8. decryptData(encryptedData, iv)获取解密JSON数据。

    'use strict';
    
    const { Controller } = require('egg');
    const WXBizDataCrypt = require('./WXBizDataCrypt');
    const datetime = require('silly-datetime'); //npm i silly-datetime --save 时间格式化库
    
    class HomeController extends Controller {
        async index() {
            const { ctx } = this;
            // 获取前端传递参数
            const { code, encryptedData, iv } = ctx.query;
            // 小程序平台复制appId、AppSecret
            const appId = 'wx2b5d4b45d5464fd3';
            const AppSecret = 'e7c02d8b31c38501dfaa4b86afec768b';
            const URL = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${AppSecret}&js_code=${code}&grant_type=authorization_code`;
            // 请求微信接口,获取session_key
            const { data: { session_key } } = await ctx.curl(URL, {
              method: 'get',
              dataType: 'json',
            });
            // 引入WXBizDataCrypt文件,new出实例传递参数
            const pc = new WXBizDataCrypt(appId, session_key);
            const { stepInfoList } = pc.decryptData(encryptedData, iv);
            const date = [];
            const step = [];
            stepInfoList.forEach(item => {
              // 修改日期格式
              date.push(datetime.format(new Date(item.timestamp * 1000), 'YYYY-MM-DD'));
              step.push(item.step);
            });
            ctx.body = {
              code: 200,
              msg: '成功',
              data: {
                date,
                step,
              },
            };
          }
    }
    module.exports = HomeController;

你可能感兴趣的:(uni-app,小程序)