当前位置:   article > 正文

开发笔记 | JAVA获取微信步数+日周月排行榜的实现_java获取微信步数api

java获取微信步数api

目录

功能描述

微信步数同步

获取我当日的步数

日排行,周排行,月排行榜的实现


功能描述

实现微信步数的同步(也就是获取当前的微信步数更新至数据库)

实现获取我当日的微信步数的查询

实现按照日排行,周排行,月排行榜的功能

主要思路:通过前端传递的encryptedData加密数据包,解密后得到微信步数,此文中的方式,为前端获取微信步数并将加密数据包发送后端解析。

注意的点:数据库表设计为,一个用户,一天一条步数信息,在当天,第一次获取微信步数后为新增,之后同步均为更新,在根据不同条件获取排名时,将同一个用户,处于这个时间段内的步数相加后排序得出排名。

微信步数同步

请求参数实体

  1. @Data
  2. public class StepDTO implements Serializable {
  3. @ApiModelProperty(value = "小程序用户id",required=true)
  4. @NotBlank(message = "小程序用户id不能为空")
  5. private String appUserId;
  6. @ApiModelProperty(value = "微信昵称",required=true)
  7. @NotBlank(message = "微信昵称不能为空")
  8. private String nickName;
  9. //前端传递的步数数据包 用于解密获取步数
  10. @ApiModelProperty(value = "数据包",required=true)
  11. @NotBlank(message = "前端数据包不能为空")
  12. private String encryptedData;
  13. @ApiModelProperty(value = "iv" ,required=true)
  14. @NotBlank(message = "iv不能为空")
  15. private String iv;
  16. @ApiModelProperty(value = "session_key" ,required=false)
  17. private String sessionKey;
  18. @ApiModelProperty(value = "步数")
  19. private String step;
  20. }

返回结果实体

  1. @Data
  2. public class BizStep extends BaseEntity{
  3. private static final long serialVersionUID = 1L;
  4. @ApiModelProperty(value = "小程序用户id")
  5. private String appUserId;
  6. @ApiModelProperty(value = "微信昵称")
  7. private String wechatName;
  8. @ApiModelProperty(value = "姓名")
  9. private String name;
  10. @ApiModelProperty(value = "步数")
  11. private Integer step;
  12. @ApiModelProperty(value = "头像")
  13. private String avatar ;
  14. @ApiModelProperty(value = "session_key")
  15. private String sessionKey;
  16. @ApiModelProperty(value = "手机号码")
  17. private String mobile;
  18. }

微信步数VO

  1. @Data
  2. public class WxRunDataBO {
  3. @ApiModelProperty("stepInfoList")
  4. private List<StepInfoListBO> stepInfoList;
  5. @ApiModelProperty("stepInfoList")
  6. private WatermarkBO watermark;
  7. }
  8. @Data
  9. public class StepInfoListBO {
  10. @ApiModelProperty("timestamp")
  11. private Long timestamp;
  12. @ApiModelProperty("step")
  13. private Integer step;
  14. }

控制层

  1. @Resource
  2. private BizStepService bizStepService;
  3. @PostMapping("/synchronize")
  4. public ResponseEntity<BizStep> uploadStep(@RequestBody @Valid StepDTO stepDTO) {
  5. return ResultUtil.success("同步步数功",this.bizStepService.uploadStep(stepDTO));
  6. }

service

业务层

  1. @Resource
  2. @Lazy
  3. private AccountClient accountClient;
  4. @Resource
  5. private BizStepMapper bizStepMapper;
  6. @Transactional(rollbackFor = Exception.class)
  7. public BizStep uploadStep(StepDTO stepDTO) {
  8. Assert.isTrue(LocalTime.now().isBefore(LocalTime.parse("22:00:00")), "每日同步步数截止时间为22:00");
  9. //获取微信用户数据 此处的目的为获取用户的sessionKey
  10. WxUser wxUser = accountClient.getById(stepDTO.getAppUserId());
  11. stepDTO.setSessionKey(wxUser.getSessionKey());
  12. //获取用户步数
  13. String step = this.decryptWeChatStep(stepDTO);
  14. BizStep bizStep = new BizStep();
  15. //step入库
  16. if (StrUtil.isNotBlank(step)) {
  17. LocalDateTime localDateTime = LocalDateTime.now();
  18. String today = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(localDateTime);
  19. bizStep =
  20. this.getOne(Wrappers.lambdaQuery(BizStep.class).eq(BizStep::getAppUserId,
  21. stepDTO.getAppUserId())
  22. .apply("to_char(created_date,'yyyy-MM-dd') = {0}", today));
  23. if (null != bizStep) {
  24. //如果今天舒徐不为空则更新
  25. bizStep.setStep(Integer.valueOf(step));
  26. this.updateById(bizStep);
  27. //入果用户头像更改,需要更新历史数据的头像 保持一致性
  28. if (!wxUser.getAvatar().equals(bizStep.getAvatar())) {
  29. this.update(Wrappers.lambdaUpdate(BizStep.class).eq(BizStep::getAppUserId, stepDTO.getAppUserId())
  30. .set(BizStep::getAvatar, wxUser.getAvatar()));
  31. }
  32. //保持昵称的一致性 如果昵称改变保持历史数据的一致
  33. if (!wxUser.getNickName().equals(bizStep.getName())) {
  34. this.update(Wrappers.lambdaUpdate(BizStep.class).eq(BizStep::getAppUserId, stepDTO.getAppUserId())
  35. .set(BizStep::getName, wxUser.getNickName()));
  36. }
  37. } else {
  38. BizStep newBizStep = new BizStep();
  39. //如果今天数据为空则新增
  40. newBizStep.setAppUserId(stepDTO.getAppUserId());
  41. newBizStep.setWechatName(wxUser.getNickName());
  42. newBizStep.setName(wxUser.getNickName());
  43. newBizStep.setAvatar(wxUser.getAvatar());
  44. newBizStep.setSessionKey(wxUser.getSessionKey());
  45. newBizStep.setStep(Integer.valueOf(step));
  46. newBizStep.setMobile(wxUser.getMobile());
  47. this.save(newBizStep);
  48. return newBizStep;
  49. }
  50. }
  51. return bizStep;
  52. }
  53. /**
  54. * 微信步数同步
  55. *
  56. * @param stepDTO
  57. * @return
  58. */
  59. public String decryptWeChatStep(StepDTO stepDTO) {
  60. String step = "0";
  61. byte[] encrypData = Base64.decodeBase64(stepDTO.getEncryptedData());
  62. byte[] ivData = Base64.decodeBase64(stepDTO.getIv());
  63. byte[] sessionKeyB = Base64.decodeBase64(stepDTO.getSessionKey());
  64. try {
  65. AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
  66. Cipher cipher = Cipher.getInstance(TRANSFORMATION);
  67. SecretKeySpec keySpec = new SecretKeySpec(sessionKeyB, AES);
  68. cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
  69. byte[] doFinal = cipher.doFinal(encrypData);
  70. String result = new String(doFinal);
  71. WxRunDataBO wxRunDataBO = JSON.parseObject(result, WxRunDataBO.class);
  72. List<StepInfoListBO> stepInfoList = wxRunDataBO.getStepInfoList();
  73. Assert.isTrue(stepInfoList.size() > 0, "微信没有您今日的步数");
  74. StepInfoListBO stepInfoListBO = stepInfoList.get(stepInfoList.size() - 1);
  75. log.info("stepInfoListBO={}", stepInfoListBO);
  76. Long timestamp = stepInfoListBO.getTimestamp();
  77. step = String.valueOf(stepInfoListBO.getStep());
  78. log.info("step={}", step);
  79. } catch (Exception e) {
  80. log.error("解析步数报错", e);
  81. throw new IllegalArgumentException("微信步数解析异常");
  82. }
  83. return step;
  84. }

获取我当日的步数

入参实体(结果实体同上BizStep)

  1. @Data
  2. public class MineStepDTO {
  3. @ApiModelProperty(value = "小程序用户id",required=true)
  4. @NotBlank(message = "小程序用户id不能为空")
  5. private String appUserId;
  6. }

controller层

  1. @PostMapping("/getStep")
  2. @ApiOperation(value = "获取我当天的步数" , notes = "")
  3. @PreAuthorize("hasRole('MINI_APP')")
  4. public ResponseEntity<BizStep> getMineStep(@RequestBody @Valid MineStepDTO mineStepDTO) {
  5. return ResultUtil.success(this.bizStepService.getMineStep(mineStepDTO));
  6. }

 service

对我方步数表的查询

  1. public BizStep getMineStep(MineStepDTO mineStepDTO) {
  2. LocalDateTime localDateTime = LocalDateTime.now();
  3. String today = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(localDateTime);
  4. BizStep bizStep = this.getOne(Wrappers.lambdaQuery(BizStep.class).eq(BizStep::getAppUserId, mineStepDTO.getAppUserId())
  5. .apply("to_char(created_date,'yyyy-MM-dd') = {0}", today));
  6. if (null == bizStep) {
  7. //如果今日无数据 返回0步
  8. BizStep newBizStep = new BizStep();
  9. //如果今天数据为空则新增
  10. newBizStep.setAppUserId(mineStepDTO.getAppUserId());
  11. newBizStep.setStep(0);
  12. return newBizStep;
  13. }
  14. return bizStep;
  15. }

日排行,周排行,月排行榜的实现

请求实体

  1. @Data
  2. public class RankDTO implements Serializable {
  3. @ApiModelProperty(value = "排序方式 月month 周week 日day", required = true)
  4. @NotBlank(message = "请选择排序方式")
  5. private String type;
  6. @ApiModelProperty(value = "小程序用户id", required = true)
  7. @NotBlank(message = "小程序用户id不能为空")
  8. private String appUserId;
  9. //当前页,默认第一页
  10. @ApiModelProperty(value = "当前页")
  11. private Integer currPage = 1;
  12. //每页记录数,默认为10
  13. @ApiModelProperty(value = "显示条数")
  14. private Integer size = 100000;
  15. }

 controller

  1. @PostMapping("/rank")
  2. public ResponseEntity<List<StepRankVO>> getRank(@RequestBody @Valid RankDTO rankDTO) {
  3. return ResultUtil.success(this.bizStepService.getRank(rankDTO));
  4. }

service

  1. public StepRankVO getRank(RankDTO rankDTO) {
  2. StepRankVO stepRankVO = new StepRankVO();
  3. //时间条件
  4. String startDate = "";
  5. String endDate = "";
  6. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  7. Calendar calendar = Calendar.getInstance();
  8. calendar.setTimeInMillis(System.currentTimeMillis());
  9. if (MONTH.equals(rankDTO.getType())) {
  10. calendar.add(Calendar.MONTH, 0);
  11. calendar.set(Calendar.DAY_OF_MONTH, 1);
  12. startDate = dateFormat.format(calendar.getTime()) + " 00:00:00";
  13. calendar.add(Calendar.MONTH, 1);
  14. calendar.set(Calendar.DAY_OF_MONTH, 0);
  15. endDate = dateFormat.format(calendar.getTime()) + " 23:59:59";
  16. }
  17. if (WEEK.equals(rankDTO.getType())) {
  18. calendar.setFirstDayOfWeek(Calendar.MONDAY);
  19. calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
  20. startDate = dateFormat.format(calendar.getTime()) + " 00:00:00";
  21. calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
  22. endDate = dateFormat.format(calendar.getTime()) + " 23:59:59";
  23. }
  24. if (DAY.equals(rankDTO.getType())) {
  25. calendar.add(Calendar.DATE, 0);
  26. String today = dateFormat.format(calendar.getTime());
  27. startDate = today + " 00:00:00";
  28. endDate = today + " 23:59:59";
  29. }
  30. Page<RankResultVO> ranks = this.bizStepMapper.getRank(new Page<>(rankDTO.getCurrPage(), rankDTO.getSize()), startDate, endDate);
  31. if (CollectionUtil.isNotEmpty(ranks.getRecords())) {
  32. stepRankVO.setRankList(ranks.getRecords());
  33. RankResultVO myRankVO = new RankResultVO();
  34. List<RankResultVO> myRank = ranks.getRecords().stream().filter(e -> rankDTO.getAppUserId().equals(e.getAppUserId())).collect(Collectors.toList());
  35. if (CollectionUtil.isNotEmpty(myRank)) {
  36. BeanUtils.copyProperties(myRank.get(0), myRankVO);
  37. }
  38. stepRankVO.setMine(myRankVO);
  39. }
  40. return stepRankVO;
  41. }

mapper

  1. @Mapper
  2. public interface BizStepMapper extends BaseMapper<BizStep> {
  3. Page<RankResultVO> getRank(Page<RankResultVO> page, @Param("startDate") String startDate, @Param("endDate") String endDate);
  4. }

xml

  1. <select id="getRank" resultType="com.vo.mp.RankResultVO">
  2. SELECT
  3. rank ( ) over ( ORDER BY t.step DESC ) AS rank,
  4. t.step,
  5. t.app_user_id,
  6. t.NAME,
  7. t.avatar
  8. FROM
  9. (
  10. SELECT
  11. sum( a.step ) AS step,
  12. a.app_user_id,
  13. a.NAME,
  14. a.avatar
  15. FROM
  16. ssyy_biz_step a
  17. where
  18. to_char(created_date,'yyyy-MM-dd HH24:MI:ss') <![CDATA[>=]]> #{startDate}
  19. and
  20. to_char(created_date,'yyyy-MM-dd HH24:MI:ss')<![CDATA[<=]]> #{endDate}
  21. GROUP BY
  22. a.app_user_id,
  23. a.NAME,
  24. a.avatar
  25. ) t
  26. </select>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/308167
推荐阅读
相关标签
  

闽ICP备14008679号