【微信小程序】SpringBoot集成微信小程序(多小程序集成)

news2024/9/27 7:16:50

SpringBoot集成微信小程序

  • 前言
  • 一、前置工作
    • 1、获取appId和appSecret核心参数
  • 二、SpringBoot集成微信小程序
    • 1、引入pom依赖
    • 2、yml配置
    • 3、java代码文件
      • 3.1、Properties 配置类
      • 3.2 Configuration 服务类
    • 4、使用示例
      • 4.1、获取登录后的session信息:openId
      • 4.2、获取当前用户手机号
    • 5、更多接口使用请参考

前言

本文内容参考于“binarywang”,感谢大佬的开源

源码参考:https://github.com/Wechat-Group/WxJava

demo参考:https://github.com/binarywang/weixin-java-miniapp-demo

一、前置工作

1、获取appId和appSecret核心参数

在这里插入图片描述

二、SpringBoot集成微信小程序

1、引入pom依赖

        <!-- 小程序依赖 -->
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-miniapp</artifactId>
            <version>4.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-common</artifactId>
            <version>4.3.0</version>
        </dependency>
        <!--<dependency>-->
        <!--<groupId>commons-fileupload</groupId>-->
        <!--<artifactId>commons-fileupload</artifactId>-->
        <!--</dependency>-->
        <!--emoji处理-->
        <dependency>
            <groupId>com.vdurmont</groupId>
            <artifactId>emoji-java</artifactId>
            <version>5.1.1</version>
        </dependency>

2、yml配置


wx:
  miniapp:
    configs:
      - appid: wxa3760c4bd118deb3
        secret: e426f8e0b6c692c8e8410708ae114e9c
        token:  #微信小程序消息服务器配置的token
        aesKey:  #微信小程序消息服务器配置的EncodingAESKey
        msgDataFormat: JSON

3、java代码文件

3.1、Properties 配置类



import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.List;

/**
 * @author tm
 * date 2023/5/15
 * @version 1.0
 */
@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;

    }

}



3.2 Configuration 服务类

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 com.google.common.collect.Maps;
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.jeecg.modules.fag.properties.WxMaProperties;
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 javax.annotation.PostConstruct;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tm
 * date 2023/5/15
 * @version 1.0
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)
public class WxMaConfiguration {
    private final WxMaProperties properties;

    private static final Map<String, WxMaMessageRouter> routers = Maps.newHashMap();
    private static Map<String, WxMaService> maServices;

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

    @Bean
    public WxMaService defaultWxMaService() {
        return WxMaConfiguration.getMaService();
    }

    public static WxMaService getMaService() {
        String appId = null;
        for (String appIdKey : maServices.keySet()) {
            appId = appIdKey;
        }

        return getMaService(appId);
    }

    public static WxMaService getMaService(String appid) {
        WxMaService wxService = maServices.get(appid);
        if (wxService == null) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
        }

        return wxService;
    }

    public static WxMaMessageRouter getRouter(String appid) {
        return routers.get(appid);
    }

    @PostConstruct
    public void init() {
        List<WxMaProperties.Config> configs = this.properties.getConfigs();
        if (configs == null) {
            throw new WxRuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!");
        }

        maServices = 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());

                    WxMaService service = new WxMaServiceImpl();
                    service.setWxMaConfig(config);
                    routers.put(a.getAppid(), this.newRouter(service));
                    return service;
                }).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a));
    }

    private WxMaMessageRouter newRouter(WxMaService service) {
        final WxMaMessageRouter router = new WxMaMessageRouter(service);
        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;
    };

}

4、使用示例

4.1、获取登录后的session信息:openId


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;

import org.jeecg.modules.fag.configuration.WxMaConfiguration;
import org.springframework.stereotype.Service;

/**
 * Author:     tm
 * Version:    1.0
 */
@Slf4j
@Service
public class TestServiceImpl {

    public Result login(String code) {

        final WxMaService wxService = WxMaConfiguration.getMaService();
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            if (session == null) {
                return Result.error("获取小程序用户失败");
            }
            log.info(session.getSessionKey());
            log.info(session.getOpenid());
            
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(e.getLocalizedMessage());
        }
    }


}

4.2、获取当前用户手机号


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.fag.configuration.WxMaConfiguration;
import org.springframework.stereotype.Service;
import javax.validation.constraints.NotEmpty;

/**
 * Author:     tm
 * Version:    1.0
 */
@Slf4j
@Service
public class TestServiceImpl {


    public Result userPhone(@NotEmpty(message = "code不能为空") String code) {
        final WxMaService wxService = WxMaConfiguration.getMaService();
        try {
            WxMaPhoneNumberInfo newPhoneNoInfo = wxService.getUserService().getNewPhoneNoInfo(code);
            if (newPhoneNoInfo == null) {
                return Result.error("获取手机号失败");
            }
            log.info("请求结果:{}", newPhoneNoInfo);
            String phoneNumber = newPhoneNoInfo.getPhoneNumber();

            return Result.ok("获取手机号成功", phoneNumber);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(e.getLocalizedMessage());
        }
    }


}

5、更多接口使用请参考

cn.binarywang.wx.miniapp.api.WxMaService
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2088838.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

提升你的校招简历:推荐高质量C++项目示例!

Linux C/C开发&#xff08;后端/音视频/游戏/嵌入式/高性能网络/存储/基础架构/安全&#xff09;、QT开发、学习资料、教学视频和学习路线图&#xff0c;↓↓↓↓↓↓见下面文章底部点击学习资料领取↓↓↓↓↓↓ TinyTetris TinyTetris 是一个用不到 1024 字节的 C 语言代码编…

SWAP模型入门到精通:模拟土壤水分动态、溶质运输、土壤温度以及作物生长等过程

目录 专题一 SWAP模型介绍及数据要求 专题二 数据制备与模型运行 专题三 基于R模型敏感性分析与贝叶斯优化 专题四 基于Fortran源代码分析 专题五 气候数据降尺度与变化影响分析 专题六 AI大语言模型在建模中的应用 更多应用 SWAP模型是由荷兰瓦赫宁根大学开发的先进农作…

泽众P-One如何测试https接口性能问题

P-One是泽众软件自主研发的一套一站式性能测试平台&#xff0c;集管理、设计、压测、监控以及分析于一体的全方位性能测试解决方案&#xff0c;有效提升了性能测试的技术能力和效率&#xff0c;降低了测试门槛和成本&#xff0c;同时提升了软件产品质量。本文将详细介绍如何使用…

Nuxt 项目实战 - 16:利用CDN+OSS给网站全面提速

背景 我面试过一些前端同学&#xff0c;同时也看到网上很多前端同学说可以利用CDN加速&#xff0c;提高网站的访问速度&#xff0c;具体如何搞&#xff1f;具体如何配置&#xff1f;估计很多前端都是不知道的&#xff0c;一方面权限所限&#xff0c;另一方面可能只是知道可以利…

Substance 3D Stager for Mac/Win:高效三维场景设计利器

Substance 3D Stager是Adobe推出的一款专为Mac和Windows用户设计的三维场景设计和渲染软件&#xff0c;它以其高效、直观的特点&#xff0c;在数字艺术、游戏开发、影视特效等领域赢得了广泛的认可。 核心功能 直观的操作界面&#xff1a;Substance 3D Stager提供了优秀的视觉…

智慧交通算法一体机助力城市交通智能管理,让违规行为无处遁形

背景分析&#xff1a; 随着社会的进步和科技的不断发展&#xff0c;互联网技术和AI视觉分析技术日益成熟&#xff0c;为传统交通监控领域带来了新的发展机遇。AI视觉分析技术的引入&#xff0c;不仅提升了交通监控的智能化和自动化水平&#xff0c;还显著减轻了交管部门的工作…

数据分析报告练习作业

该数据集为日本1960年到2022年间的基建领域的投资数据&#xff0c;包含以下特征&#xff1a; 年份 价值 总计 建筑总计 住宅建筑 政府住宅建筑 私人住宅建筑 非住宅建筑 政府非住宅建筑 私人非住宅建筑 私人非住宅建筑&#xff08;矿业和工业&#xff09; 私人非住宅建筑&…

使用HTTP代理注意的点

“在网络世界中&#xff0c;HTTP代理扮演着桥梁的角色&#xff0c;帮助用户匿名访问网站、加速网页加载、绕过地区限制等。然而&#xff0c;不当或不安全地使用HTTP代理也可能带来一系列问题。以下是在使用HTTP代理时需要注意的几个关键点。” 一、选择可靠的代理服务商 首先&…

PHP指尖上的旅行管家手边酒店民宿预订系统小程序源码

指尖上的旅行管家——手边酒店民宿预订系统&#x1f31f;&#x1f6eb; &#x1f680; 开篇&#xff1a;旅行新伴侣&#xff0c;轻松启程 每次计划旅行&#xff0c;是不是都曾为找酒店、订民宿而头疼不已&#xff1f;&#x1f914; 繁琐的搜索、对比、预订流程&#xff0c;让美…

旅行追踪和行程规划工具AdventureLog

什么是 AdventureLog &#xff1f; AdventureLog 是一种记录您的旅行并与世界分享的简单方法。您可以在日志中添加照片、笔记等。跟踪您访问过的国家、探索去过的地区和地方。您还可以查看您的旅行统计数据和里程碑。AdventureLog 旨在成为您终极的旅行伴侣&#xff0c;帮助您记…

chapter09-OOP高级部分——(抽象类)——day12

目录 398-抽象类引出 399-抽象类细节1 400-抽象类细节 401-抽象类的课堂练习 398-抽象类引出 399-抽象类细节1 400-抽象类细节 401-抽象类的课堂练习 一、 1、错&#xff0c;dinal不能被继承 2、错&#xff0c;不能有static&#xff0c;没办法被重写 3、错&#xff0c;…

跟着我发现味蕾新宝藏

你是不是常常为找不到正宗又美味的传统美食而烦恼呢&#xff1f;是不是渴望品尝那些带着浓郁地方特色、满满都是回忆味道的美食呢&#xff1f;那你可一定不能错过食家巷。 先说那食家巷的大烤馍&#xff0c;外表金黄&#xff0c;散发着诱人的光泽。拿在手里沉甸甸的&…

Python用 Uvicorn 打造高性能 FastAPI 应用程序使用详解

概要 随着 Python 在 Web 开发领域越来越受欢迎,开发人员对于构建快速、可靠和高性能的 Web 应用程序的需求也日益增加。在这个背景下,Uvicorn 这个高性能 ASGI 服务器应运而生,它为构建现代化的 Python Web 应用程序提供了强大的支持。 本文将详细介绍 Uvicorn 的使用教程…

零知识证明-椭圆曲线(五)

这章主要讲述椭圆曲线 N 子群的阶n &#xff0c;明文嵌入等 补充上章的知识点 1&#xff1a;椭圆曲线的阶 一个群中的元素数量称为这个群的阶&#xff08;order&#xff09; 当 p 小时 &#xff0c;0到p-1的所有整数x代入方程&#xff0c;然后对于每个x都找到所有满足方程的解&…

Python爬虫学习路线教程:从零基础到入门

如果你也正在入门Python爬虫&#xff0c;那么你需要的话可以&#xff0c;点击这里&#x1f449;Python重磅福利&#xff1a;入门&进阶全套学习资料、电子书、软件包、项目源码等等免费分享&#xff01; 前言 在数字化时代&#xff0c;信息如潮水般汹涌而来&#xff0c;如…

基于火锅餐饮大数据的精准推荐系统【协同过滤、前后台信息管理、万能推荐系统】

文章目录 有需要本项目的代码或文档以及全部资源&#xff0c;或者部署调试可以私信博主项目介绍项目展示项目过程大屏设计管理员界面用户界面数据库展示用户信息评论功能商家回复每文一语 有需要本项目的代码或文档以及全部资源&#xff0c;或者部署调试可以私信博主 项目介绍…

【手机取证】智能手机位置数据提取方法

文章关键词&#xff1a;手机取证、电子数据取证、云取证 一、前言 随着智能手机的普及&#xff0c;人们的生活方式和行为模式发生了巨大变化。智能手机不仅是通信工具&#xff0c;还是集成了多种传感器和定位技术的强大设备。这些设备每天都会产生大量的位置信息&#xff0c;…

优质企业上网行为管理软件大盘点

员工在上班时间摸鱼&#xff0c;看似是一个小问题&#xff0c;但却会给企业带来诸多不良影响。首先&#xff0c;摸鱼会降低员工的工作效率&#xff0c;导致工作任务无法按时完成&#xff0c;影响项目进度。其次&#xff0c;摸鱼行为会破坏企业的工作氛围&#xff0c;影响其他员…

Dxf文件中多段线弧线的计算

要计算弧形的参数&#xff08;包括起始角度、跨度角度以及包围弧形的矩形&#xff09;&#xff0c;我们首先需要理解一些基础知识&#xff1a; 弧的半径和中心&#xff1a;弧是圆的一部分&#xff0c;因此我们首先要计算整个圆的半径和圆心。起始角度和跨度角度&#xff1a;弧…

Vue3.0项目实战(二)——大事件管理系统登录注册功能实现

目录 1. 登录注册页面 [element-plus 表单 & 表单校验] 1.1 注册登录 静态结构 & 基本切换 2. 注册功能 2.1 实现注册校验 2.2 注册前的预校验 2.3 封装 api 实现注册功能 3. 登录功能 3.1 实现登录校验 3.2 登录前的预校验 & 登录成功 1. 登录注册页面 […