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

2023-11-04



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

一、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: #微信小程序的appid
        secret: #微信小程序的Secret
        token: #微信小程序消息服务器配置的token
        aesKey: #微信小程序消息服务器配置的EncodingAESKey
        msgDataFormat: 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;

    @Data
    public 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;

    @Autowired
    public WxMaConfiguration(WxMaProperties properties) {
        this.properties = properties;
    }

    @Bean
    public 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;
    }

    @Bean
    public 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
     */
    @Override
    public 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
        }
    }

    @Override
    public R<WxMaUserInfo> getUserInfo(WxUserInfo userInfo) {

        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(userInfo.getSessionKey(), userInfo.getRawData(), userInfo.getSignature())) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return R.error("user check failed");
        }

        // 解密用户信息
        WxMaUserInfo wxMaUserInfo = wxMaService.getUserService().getUserInfo(userInfo.getSessionKey(), userInfo.getEncryptedData(), userInfo.getIv());
        WxMaConfigHolder.remove();//清理ThreadLocal
        return 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,到这儿就结束了。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐

  • GD32F103RC的ADC采样值偏大

    在最近的一个项目中 使用了GD32做控制器 初期调试ADC很顺利 但后期将代码组合后发现ADC的采样值都偏大了 经过反复调试 发现和一个引脚PB0有关 只要将PB0初始化或者外部有电路将电平拉低 PC0 PC1 PC2的ADC采样值就会变大
  • C++之shared_from_this用法以及类自引用this指针陷阱

    C 系列文章目录 文章目录 C 系列文章目录 前言 一 为什么需要enable shared from this 二 enable shared from this用法 总结 前言 shared ptr实现原理 shared ptr 从 P
  • uni-app 收获地址API报错:chooseAddress:fail the api need to be declared in …e requiredPrivateInfos field in

    一 代码 选择收获地址 async chooseAddress const res await uni chooseAddress catch err gt err console log res res 二 报错信息 三 原因 这是由于微
  • uniapp中uni.showToast最多显示多少个汉字?

    在 uni showToast 中 最多可以显示 14 个汉字 超出的就会被隐藏 而且隐藏的效果根据手机效果还不一样 有的是 有的直接没了 这是由于 uni showToast 会在屏幕上显示一个浮动的提示框 提示框的大小是有限的 所以最多
  • 2023-ChatGPT解析及使用方法

    什么是Chat GPT 我们能用它来干什么 Chat GPT是一款基于人工智能技术的自然语言处理模型 由OpenAI团队开发 它能够通过机器学习技术从海量文本数据中学习语言知识 实现自然语言生成 对话生成和语言理解等功能 使得机器能够更加智
  • DELETE语句

    DELETE 语句用于删除表中的行 语法 DELETE FROM table name WHERE some column some value 示例 DELETE FROM Websites WHERE name 百度 AND count
  • pytorch实战-图像分类(一)(数据预处理)

    目录 1 导入各种库 2 数据预处理 2 1数据读取 2 2图像增强 3 构建数据网络 3 1网络构建 3 2读取标签对应的名字 4 展示数据 4 1数据转换 4 2画图 5 模型训练 1 导入各种库 上代码 import os impor
  • ESP32 Https server 错误Header fields are too long for server to interpret

    这个错误的根源是浏览器发送的请求头文件过于长 esp32 header fields are too long issue 给出了解决方案 修改sdkconfig文件中的CONFIG HTTPD MAX REQ HDR LEN 将其设置为更
  • DS证据理论

    1 基本概念 假设空间 识别框架 对于全域X X A B 那么假设空间为 空 A B AB Mass函数和BPA mass函数给假设空间每一个假设都分配了概率 我们称为基本概率分配 BPA Basic Probability Assignm
  • [设计模式] 浅谈SOLID设计原则

    目录 单一职责原则 开闭原则 里氏替换原则 接口隔离原则 依赖倒转原则 SOLID是一个缩写词 代表以下五种设计原则 单一职责原则 Single Responsibility Principle SRP 开闭原则 Open Closed P
  • VC++6.0的使用技巧

    1 建立工程 一定要创建window32位控制台应用 Win32 console Application 2 创建新文件 文件 新建 文件 源文件或头文件 3 如果不想要的文件 File View gt XXX files gt Sourc
  • 量子力学与自由意志

    第一个观点 是有造物主存在的 人不是偶然出险的 第二个观点 人是否具备自由意志 人可以违背生物定律做出自己的选择 量子力学的微观实验 因果链可以倒置 唯物主义与唯心主义到底谁是对的 熵增定律 普朗克 爱因斯坦 波尔 杨老 世界是非连续的 粒
  • [520]pandas(ix & iloc &loc)区别

    loc 通过行标签索引行数据 iloc 通过行号索引行数据 ix 通过行标签或者行号索引行数据 基于loc和iloc 的混合 举例说明 1 分别使用loc iloc ix 索引第一行的数据 coding utf 8 import panda
  • Python中heapq模块浅析

    Python提供了heapq模块 有利于我们更好的对堆的相关操作进行简化 下面总结我所用到的相关方法 文章目录 0 回顾堆的概念 1 heappush heap item 建立大 小根堆 2 heapify heap 建立大 小根堆 3 h
  • 一款运行于windows上的linux命令神器-Cmder(用过后爱不释手)

    一 前言 很多工程师都习惯了使用linux下一些命令 再去用Windows的 cmd 简直难以忍受 要在windows上运行linux命令 目前比较流行的方式由 GunWin32 Cygwin WSL Bash on Windows Git
  • 手写生产者消费者,要求指定容量,有个put方法和一个get方法,和当前库存量size

    废话不多说 直接看代码 tomcat addAdditionalTomcatConnectors httpConnector 1 核心代码 2 生产者 生产者 class ShopProducer implements Runnable p
  • journalctl 查看历史日志

    查看历史日志 使用 journalctl 命令来查看 systemd 日志时 可以使用 since 和 until 标志来查看特定时间范围内的历史日志 以下是一些示例命令 它们将显示不同时间范围内的历史日志 显示过去一小时内的日志 jour
  • Python 核心笔记(一)

    Python 是一种支持面向对象的解释性高级语言 Simple yet Powerful 是人们对它的 一致评价 最初是在苹果计算机上被编译成功的 但现在他已经可以运行于世界上主流的 操作平台之上了 跨平台性极强 它包含多种 Program
  • 小白易懂的遗传算法(Python代码实现)

    无约束的遗传算法 最简单的 最开始真正理解遗传算法 是通过这个博主的讲解 安利给小白们看一看 遗传算法的Python实现 通俗易懂 我觉得博主写的让人特别容易理解 关键是代码也不报错 然后我就照着他的代码抄了一遍 认真地理解了一下每一个模块
  • 【Springboot】整合wxjava实现 微信小程序:授权登录

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