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

前言

本文内容参考于“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
在这里插入图片描述

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 微信小程序是一款通过微信平台开发的应用,可以在微信内直接运行。SpringBoot是一个基于Spring框架的开发工具,可以简化Spring项目的配置和部署。 在开发微信小程序的过程中,可以使用SpringBoot来构建后端服务器,提供数据接口和业务逻辑的实现。SpringBoot可以快速地搭建一个基于Java的后端开发环境,简化了配置,提高了开发效率。 首先,我们可以使用SpringBoot来创建一个基础的项目结构。通过使用Maven或者Gradle构建工具,可以快速生成项目的骨架代码,并引入所需的SpringBoot依赖。 其次,我们可以在项目中引入微信小程序的SDK,例如微信小程序开发工具提供的Java SDK。通过SDK提供的API,我们可以进行用户登录验证、获取用户信息、发送模板消息等功能的实现。 然后,我们可以使用SpringBoot来处理前端请求并返回相应的数据。通过注解方式配置接口路由,并使用SpringBoot提供的@RestController注解来标识一个控制器,处理前端请求。可以在控制器中调用微信小程序SDK提供的接口,从而获取用户信息、发送消息等。 最后,我们可以使用SpringBoot的数据库操作支持来进行数据的增删改查。可以使用ORM框架,如MyBatis或者Hibernate,来简化数据库操作的实现。通过使用SpringBoot的数据源配置,可以快速地配置数据库连接。 综上所述,微信小程序SpringBoot项目是一种通过使用SpringBoot构建后端服务器,实现微信小程序的功能和业务逻辑的开发方式。通过SpringBoot的快速开发特性和丰富的生态系统,可以减少开发成本,提高开发效率。 ### 回答2: 微信小程序是一种基于微信平台开发的应用程序,而Spring Boot是一种基于Java语言的开发框架。在开发微信小程序的过程中,我们可以选择使用Spring Boot作为后端开发工具,来构建和管理我们的项目。 使用Spring Boot搭建微信小程序项目可以带来以下好处: 1. 快速搭建:Spring Boot提供了自动化配置和快速启动的特性,可以让我们快速建立一个基础的项目框架,省去了繁琐的配置过程。 2. 简单易用:Spring Boot提供了丰富的开箱即用功能和规范,可以轻松集成微信小程序的功能模块,如用户登录、数据交互等。 3. 强大的生态圈:Spring Boot拥有庞大的社区和丰富的第三方库支持,可以快速解决常见问题,提高开发效率。 4. 易于维护和扩展:Spring Boot的代码规范和模块化设计使得项目易于维护和扩展,可以快速响应需求变化。 在使用Spring Boot开发微信小程序项目时,我们可以通过使用Spring Boot的Web开发框架来处理小程序的请求和响应,使用Spring的数据访问框架来实现与数据库的交互,使用Spring Security来实现用户认证和授权等功能。 总之,将Spring Boot应用于微信小程序开发中,可以帮助我们构建高效、可扩展和易维护的项目,提升开发效率并满足用户需求。 ### 回答3: 微信小程序是一种基于微信平台的应用程序,可以在手机上进行快速的开发和分享。而Spring Boot是一种开发框架,它可以简化Java应用程序的开发过程,并提供快速的开源工具和库。 结合微信小程序Spring Boot可以实现一个强大的移动应用后端,提供数据接口和业务逻辑处理。在微信小程序中,前端部分负责展示界面和用户交互,而后端Spring Boot项目则负责数据的处理和提供接口。 首先,需要建立一个Spring Boot项目,设置好相关的开发环境。然后,通过引入一些必要的依赖,如Spring Boot的Web模块、数据库连接、安全验证等,来支持项目的开发。 接下来,可以编写后端的逻辑代码,处理微信小程序的请求,如登录、支付、获取数据等等。同时,可以使用Spring Boot提供的ORM框架,如MyBatis或Spring Data JPA,来操作数据库,存储和读取数据。 在整个开发过程中,可以使用一些辅助工具,如Spring Boot的开发工具包、微信小程序SDK等,来提高开发效率和便利性。 最后,需要对项目进行测试和部署。可以使用一些自动化测试工具,如JUnit或Postman,来验证接口的正确性。然后,可以将项目打包成可执行的jar文件,部署到服务器上,供微信小程序调用和访问。 综上所述,微信小程序Spring Boot项目可以通过前后端分离的方式,实现微信小程序的功能和服务,并提供高效的开发和管理。这种组合可以满足移动应用开发的需求,并提供稳定和可靠的后台支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值