文章目录

  • 一、wxjava是什么
  • 二、使用步骤
    • 1.引入依赖
    • 2.配置yml
    • 3.小程序的配置
    • 4.后端的业务逻辑代码
      • controller
      • service
      • impl
      • dto
    • 5.前端的业务逻辑代码
      • 新建项目
      • 微信开发者工具

提示:以下是本篇文章正文内容,下面案例可供参考

一、wxjava是什么

WxJava - 微信开发 Java SDK,支持微信支付、开放平台、公众号、企业号/企业微信、小程序等的后端开发。
官方的gitee仓库地址
官方的github仓库地址
官方的关于微信小程序的demo

二、使用步骤

1.引入依赖

导入wxjava的maven依赖

<dependency><groupId>com.github.binarywang</groupId><artifactId>weixin-java-miniapp</artifactId><version>4.3.0</version>
</dependency>

2.配置yml

wx:miniapp:configs:- appid: #微信小程序的appidsecret: #微信小程序的Secrettoken: #微信小程序消息服务器配置的tokenaesKey: #微信小程序消息服务器配置的EncodingAESKeymsgDataFormat: JSON

3.小程序的配置

WxMaProperties 用于读取yml配置的信息

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;import java.util.List;@Data
@ConfigurationProperties(prefix = "wx.miniapp")
public class WxMaProperties {private List<Config> configs;@Datapublic static class Config {/*** 设置微信小程序的appid*/private String appid;/*** 设置微信小程序的Secret*/private String secret;/*** 设置微信小程序消息服务器配置的token*/private String token;/*** 设置微信小程序消息服务器配置的EncodingAESKey*/private String aesKey;/*** 消息格式,XML或者JSON*/private String msgDataFormat;}}

WxMaConfiguration

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.message.WxMaMessageHandler;
import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.io.File;
import java.util.List;
import java.util.stream.Collectors;@Slf4j
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)
public class WxMaConfiguration {private final WxMaProperties properties;@Autowiredpublic WxMaConfiguration(WxMaProperties properties) {this.properties = properties;}@Beanpublic WxMaService wxMaService() {List<WxMaProperties.Config> configs = this.properties.getConfigs();if (configs == null) {throw new WxRuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!");}WxMaService maService = new WxMaServiceImpl();maService.setMultiConfigs(configs.stream().map(a -> {WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
//                WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool());// 使用上面的配置时,需要同时引入jedis-lock的依赖,否则会报类无法找到的异常config.setAppid(a.getAppid());config.setSecret(a.getSecret());config.setToken(a.getToken());config.setAesKey(a.getAesKey());config.setMsgDataFormat(a.getMsgDataFormat());return config;}).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));return maService;}@Beanpublic WxMaMessageRouter wxMaMessageRouter(WxMaService wxMaService) {final WxMaMessageRouter router = new WxMaMessageRouter(wxMaService);router.rule().handler(logHandler).next().rule().async(false).content("订阅消息").handler(subscribeMsgHandler).end().rule().async(false).content("文本").handler(textHandler).end().rule().async(false).content("图片").handler(picHandler).end().rule().async(false).content("二维码").handler(qrcodeHandler).end();return router;}private final WxMaMessageHandler subscribeMsgHandler = (wxMessage, context, service, sessionManager) -> {service.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder().templateId("此处更换为自己的模板id").data(Lists.newArrayList(new WxMaSubscribeMessage.MsgData("keyword1", "339208499"))).toUser(wxMessage.getFromUser()).build());return null;};private final WxMaMessageHandler logHandler = (wxMessage, context, service, sessionManager) -> {log.info("收到消息:" + wxMessage.toString());service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为:" + wxMessage.toJson()).toUser(wxMessage.getFromUser()).build());return null;};private final WxMaMessageHandler textHandler = (wxMessage, context, service, sessionManager) -> {service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回复文本消息").toUser(wxMessage.getFromUser()).build());return null;};private final WxMaMessageHandler picHandler = (wxMessage, context, service, sessionManager) -> {try {WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", "png",ClassLoader.getSystemResourceAsStream("tmp.png"));service.getMsgService().sendKefuMsg(WxMaKefuMessage.newImageBuilder().mediaId(uploadResult.getMediaId()).toUser(wxMessage.getFromUser()).build());} catch (WxErrorException e) {e.printStackTrace();}return null;};private final WxMaMessageHandler qrcodeHandler = (wxMessage, context, service, sessionManager) -> {try {final File file = service.getQrcodeService().createQrcode("123", 430);WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file);service.getMsgService().sendKefuMsg(WxMaKefuMessage.newImageBuilder().mediaId(uploadResult.getMediaId()).toUser(wxMessage.getFromUser()).build());} catch (WxErrorException e) {e.printStackTrace();}return null;};}

这个是官方demo里面的,就是读取application.yml配置的信息进行初始化
其实里面很多内容你自己可以提取出来单独封装。后面会一一实现

4.后端的业务逻辑代码

controller

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.example.wxjava.common.result.R;
import com.example.wxjava.domain.dto.WxUserInfo;
import com.example.wxjava.service.UserInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;/*** @author 成大事* @since 2022/7/27 22:44*/
@Slf4j
@RestController
@RequestMapping("/wx/user")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class WxUserInfoController {private final WxMaService wxMaService;private final UserInfoService userInfoService;/*** 登陆接口*/@GetMapping("/login")public R<WxMaJscode2SessionResult> login(@RequestParam("code") String code) {return userInfoService.login(code);}/*** <pre>* 获取用户信息接口* </pre>*/@PostMapping("/getUserInfo")public R<WxMaUserInfo> getUserInfo(@RequestBody WxUserInfo userInfo) {return userInfoService.getUserInfo(userInfo);}
}

R 是我自己封装的统一返回类。大家可以自行设置返回类型

service

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.example.wxjava.common.result.R;
import com.example.wxjava.domain.dto.WxUserInfo;/*** @author 成大事* @since 2022/7/27 22:47*/
public interface UserInfoService {/*** 登录* @param code code* @return   WxMaJscode2SessionResult*/R<WxMaJscode2SessionResult> login(String code);/*** 获取用户信息* @param userInfo  包含一些加密的信息* @return  WxMaUserInfo*/R<WxMaUserInfo> getUserInfo(WxUserInfo userInfo);
}

impl

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.example.wxjava.common.result.R;
import com.example.wxjava.domain.dto.WxUserInfo;
import com.example.wxjava.service.UserInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** @author 成大事* @since 2022/7/27 22:48*/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UserInfoServiceImpl implements UserInfoService {private final WxMaService wxMaService;/*** 登录* @param code code* @return   WxMaJscode2SessionResult*/@Overridepublic R<WxMaJscode2SessionResult> login(String code) {try {WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);log.info(session.getSessionKey());log.info(session.getOpenid());//TODO 可以增加自己的逻辑,关联业务相关数据return R.ok(session);} catch (WxErrorException e) {log.error(e.getMessage(), e);return R.error(e.toString());} finally {WxMaConfigHolder.remove();//清理ThreadLocal}}@Overridepublic R<WxMaUserInfo> getUserInfo(WxUserInfo userInfo) {// 用户信息校验if (!wxMaService.getUserService().checkUserInfo(userInfo.getSessionKey(), userInfo.getRawData(), userInfo.getSignature())) {WxMaConfigHolder.remove();//清理ThreadLocalreturn R.error("user check failed");}// 解密用户信息WxMaUserInfo wxMaUserInfo = wxMaService.getUserService().getUserInfo(userInfo.getSessionKey(), userInfo.getEncryptedData(), userInfo.getIv());WxMaConfigHolder.remove();//清理ThreadLocalreturn R.ok(wxMaUserInfo);}
}

dto

这个其实是我测试的时候,一个对象,测试wxjava解密用户的信息。因为后端接收json对象需要对象或者map接收。

@Data
@Accessors(chain = true)
public class WxUserInfo implements Serializable {private String appid;private String sessionKey;/*** 签名信息*/private String signature;/*** 非敏感的用户信息*/private String rawData;/*** 加密的数据*/private String encryptedData;/*** 加密密钥*/private String iv;
}

目录结构

5.前端的业务逻辑代码

因为我前端也不是很好。所以就一个简单的demo
前端使用的是uniapp。大家可以去官网学习查看uniapp

新建项目

使用HBuilder X 新建一个uniapp的项目

然后在index.vue编写逻辑代码
大家可以将我这个拷贝过去。完美匹配我上面的后端代码

<template><view class="content"><button @click="login()">微信登录</button></view>
</template><script>export default {data() {return {title: 'Hello',sessionKey: ''}},onLoad() {},methods: {async login(){let that = this //保存当前作用域await uni.login({ //直接用这个调用微信接口onlyAuthorize:true,success:function(response){ // 用微信登录的话就要去微信开发工具console.log(response) //这里打印就说明接口调用成功了,然后看message login :ok//微信登录就完了,后面就是获取用户信息uni.request({url: 'http://localhost:8888/wx/user/login',data: {code: response.code},success(res) {console.log("sessionkey",res)that.sessionKey = res.data.data.sessionKey}})}})await uni.getUserProfile({desc:'测试用例',success:function(res){console.log("res",res)uni.request({url: 'http://localhost:8888/wx/user/getUserInfo',method: 'POST',dataType: 'json',data: {rawData: res.rawData,signature: res.signature,encryptedData: res.encryptedData,iv: res.iv,sessionKey: that.sessionKey},success(resc) {console.log("登录成功",resc)}})}})}}}
</script><style></style>

微信开发者工具

直接选择运行到微信开发者工具

然后在微信开发者工具

点击测试:

可以看到。调用起来了。
然后看控制台:

我们的第二个接口也完美调用。返回了用户的信息。虽然uniapp的接口可以直接获取用户的信息。
但是如果后端想要获取到这些信息。

  • 一种是前端发过来。
  • 一种是先登录。然后返回前端一个sessionkey。然后前端将rawData,signature,encryptedData,还有iv发过了。我们自己使用wxjava进行解析。

ok,到这儿就结束了。

【Springboot】整合wxjava实现 微信小程序:授权登录相关推荐

  1. SpringBoot微信小程序授权登录

    SpringBoot微信小程序授权登录 一.appId 1.1.自己是管理者:微信公众平台,申请或登录自己的微信小程序,在开发者管理中即可看到 2.2.自己是开发者:让管理员将自己加入到小程序开发者管 ...

  2. 基于Uniapp+SpringBoot实现微信小程序授权登录

    手把手教你做微信小程序授权登录交互 一.uni.login请求临时code 二.uni.request向后台交换数据 三.源代码 前台:在GetUserInfo中添加接口 后台:SpringBoot后 ...

  3. SpringCloud 微信小程序授权登录 获取openId SessionKey【SpringCloud系列13】

    SpringCloud 大型系列课程正在制作中,欢迎大家关注与提意见. 自我提升方法推荐:神奇的早起 早上 5:00 -5:20 起床刷牙 5:30-6:00 晨练(跑步.跳绳.骑自行车.打球等等) ...

  4. 微信登录小程序授权显示服务器出错,微信小程序授权登录解决方案的代码实例(含未通过授权解决方案)...

    本文实例为大家分享了微信小程序授权登录解决方案的具体代码,供大家参考,具体内容如下 getUserInfoF:function(){ var that = this; wx.getSetting({ ...

  5. 微信小程序授权登录 组件的封装

    微信小程序授权登录 组件的封装 新建components文件 写wxml文件 wxss部分 js部分 json引用 页面使用 页面js 授权登录 流程如下: 因为多个页面功能需要登录状态 所以做了个组 ...

  6. uniapp微信小程序授权登录和获取微信绑定的手机号码

    uniapp微信小程序授权登录和获取微信绑定的手机号码 弹出授权的弹框 <view class="weixinOk" @tap="getUserProfile&qu ...

  7. 微信小程序授权登录取消授权重新授权处理方法 附可用代码

    微信小程序授权登录基本是小程序的标配了,但是官方的demo,取消授权后,就不能再重新点击登录,除非重新加载小程序才可以,这下怎么办? 我们可以先在首页引导用户点击,然后跳转到一个新的页面,在新的页面进 ...

  8. 新版微信小程序授权登录流程及问题汇总(getUserProfile)

    问题来源:前不久去面试的时候有面试官问我你有自己的博客啥的吗?只能很尴尬的说没有.其实一直想有一个属于自己的博客啥的去记录自己在开发过程中遇到的问题,正好现在微信小程序比较流行,就花了两天自己搞了一个 ...

  9. 微信小程序授权登录第一次总是失败,第二次登录便正常了

    微信小程序授权登录第一次总是失败,第二次登录便正常了 错误流程 调用 用户点击授权用户信息按钮 ===> 调用wx.login( )生成code发送给后台生成session_key解密 ===& ...

  10. 微信小程序授权登录报错encryted_data或iv不合法,前端坑^-^~~

    微信小程序授权登录原来用的wx.getUserInfo(),在用户未授权过的情况下调用此接口,将不再出现授权弹窗, 会直接进入 fail 回调(详见<公告>).在用户已授权的情况下调用此接 ...

最新文章

  1. ms17-010 php版本,那年MS17-010
  2. 豆瓣评分9.4!这一部纪录片,探秘中国人迹罕至的未至之境!
  3. [Java基础]字节流读数据
  4. php如何逐条读取数据库,php从数据库中读取特定的行(实例)
  5. Kafka是什么、主要应用在什么场景?
  6. iOS学习笔记32 - 锚点
  7. 12.MongoDB之固定集合(Capped Collections)
  8. jQuery 仿抖音时钟罗盘转动效果
  9. 亚马逊美国站UL2849电动自行车标准测试报告
  10. 分门别类刷leetcode——栈、队列、堆(C++实现)
  11. 电脑每次开机都要硬盘自检percent complete
  12. C语言:记录在主线程中停止子线程
  13. 初始C语言——求算法,求1-1/2+1/3-1/4+……+1/99-1/100的值
  14. 解决Authorization not available. Check if polkit service...问题
  15. 中国探月计算机考试时间,关于选拔2020年波兰罗兹大嫦娥三号登月时间 学暑期实习实训项目学员的通知...
  16. scss混合器实现全局更换主题以及相关背景图
  17. 计算机应用基础素材文件tf5-2,计算机应用基础素材文件TF5-16
  18. 智慧楼宇系统:解决园区/写字楼90%的管理问题
  19. babylon 画线_【温故知新】——BABYLON.js学习之路·前辈经验(一)
  20. 基于mediapipe的动作捕捉和Unity的球棍模型同步

热门文章

  1. 时空信息驱动智慧城市建设与运营
  2. 从游戏中得到动态内存数据
  3. ps制作开关按钮图标
  4. 【文献阅读】Graph-Based Visual Saliency部分翻译
  5. Springboot在线考试管理系统 计算机毕设源码62754
  6. 计算机室的管理制度和管理职责,计算机教室管理制度和管理员职责.doc
  7. Altium Designer输出生产文件Gerber、IPC、NC Drill、坐标文件--AD
  8. 535.TinyURL 的加密与解密
  9. 炫酷计算机网络科技,程序员必看:13个GitHub开源又炫酷的计算机视觉项目
  10. 什么是Java序列化和反序列化?