0


SpringBoot集成微信小程序 (一)【搭建】

一、背景

小程序是一种全新的连接用户与服务的方式,它可以在微信内被便捷地获取和传播,同时具有出色的使用体验。

微信小程序官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/

二、技术栈

  • SpringBoot 2.0
  • MyBatis-Plus
  • MySQL
  • Redis
  • Sa-Token
  • weixin-java-miniapp

三、实现

3.1 引入依赖

<?xml version="1.0" encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.17</version><relativePath/></parent><groupId>com.qiangesoft</groupId><artifactId>wechat-miniapp</artifactId><version>1.0.0</version><name>wechat-miniapp</name><packaging>jar</packaging><description>微信小程序</description><properties><java.version>1.8</java.version><maven.compiler.source>${java.version}</maven.compiler.source><maven.compiler.target>${java.version}</maven.compiler.target></properties><dependencies><!-- web模块 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 参数校验模块 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency><!-- redis --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- 自动配置 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId></dependency><!-- lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!-- sa-token --><dependency><groupId>cn.dev33</groupId><artifactId>sa-token-spring-boot-starter</artifactId><version>1.37.0</version></dependency><!-- mysql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency><!-- mybatis-plus --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3</version></dependency><!-- knife4j依赖 --><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-openapi2-spring-boot-starter</artifactId><version>4.4.0</version></dependency><!-- fastjson --><dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2</artifactId><version>2.0.34</version></dependency><!-- hutool工具包 --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-core</artifactId><version>5.8.27</version></dependency><!-- 开源weixin-java-miniapp --><dependency><groupId>com.github.binarywang</groupId><artifactId>weixin-java-miniapp</artifactId><version>4.5.0</version></dependency></dependencies><build><finalName>wxminiapp</finalName><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><mainClass>com.qiangesoft.miniapp.WxMaApplication</mainClass></configuration><executions><execution><goals><goal>repackage</goal></goals></execution></executions></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.10.1</version><configuration><source>${maven.compiler.source}</source><target>${maven.compiler.target}</target></configuration></plugin></plugins></build></project>

3.2 yml配置

server:port:8087spring:# 数据库配置datasource:driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/wechat_ma?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8username: root
    password: root
  # redis配置redis:host: localhost
    port:6379username:password:timeout:2000lettuce:pool:max-active:8max-idle:8max-wait:0min-idle:0# mybatis-plus配置mybatis-plus:# MyBaits别名包扫描路径type-aliases-package: com.qiangesoft.miniapp.entity
  # Mapper所对应的XML文件位置 默认【classpath*:/mapper/**/*.xml】mapper-locations: classpath*:/mapper/*Mapper.xmlconfiguration:# 日志打印log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    # 是否开启自动驼峰命名规则map-underscore-to-camel-case:trueglobal-config:db-config:# 全局默认主键类型id-type: auto
      # 逻辑删除配置logic-delete-field: deleted
      logic-delete-value:1logic-not-delete-value:0# Sa-Token配置sa-token:# token名称(同时也是 cookie 名称)token-name: satoken
  # token有效期(单位:秒)默认30天timeout:2592000# token最低活跃频率(单位:秒)active-timeout:-1# 是否允许同一账号多地同时登录is-concurrent:true# 在多人登录同一账号时,是否共用一个 tokenis-share:true# token 风格(默认可取值:uuid、simple-uuid、random-32、random-64、random-128、tik)token-style: uuid
  # 是否输出操作日志is-log:true# 微信小程序配置wx:miniapp:appid: xxx
    secret: xxx
    token:aesKey:msg-data-format: JSON
    config-storage:type: redis
      key-prefix: wa
      http-client-type: httpclient
      http-proxy-host:http-proxy-username:http-proxy-password:retry-sleep-millis:max-retry-times:# 接口文档配置knife4j:enable:trueopenapi:title: 微信小程序
    description: 微信小程序
    email: [email protected]
    concat: xxx
    url: https://www.baidu.com/
    version: v1.0
    license: Apache 2.0
    license-url: https://stackoverflow.com/
    terms-of-service-url: https://stackoverflow.com/
    group:default:group-name: 默认
        api-rule: package
        api-rule-resources:- com.qiangesoft.miniapp.controller

3.3 配置属性类

packagecom.qiangesoft.miniapp.properties;importcom.qiangesoft.miniapp.enums.HttpClientType;importcom.qiangesoft.miniapp.enums.StorageType;importlombok.Data;importorg.springframework.boot.context.properties.ConfigurationProperties;/**
 * 属性配置类
 *
 * @author qiangesoft
 * @since 2024-07-16
 */@Data@ConfigurationProperties(prefix =WxMaProperties.PREFIX)publicclassWxMaProperties{publicstaticfinalStringPREFIX="wx.miniapp";/**
     * 微信小程序的appid.
     */privateString appid;/**
     * 微信小程序的Secret.
     */privateString secret;/**
     * 微信小程序消息服务器配置的token.
     */privateString token;/**
     * 微信小程序消息服务器配置的EncodingAESKey.
     */privateString aesKey;/**
     * 消息格式,XML或者JSON.
     */privateString msgDataFormat;/**
     * 存储策略
     */privatefinalConfigStorage configStorage =newConfigStorage();/**
     * 存储配置类
     */@DatapublicstaticclassConfigStorage{/**
         * 存储类型.
         */privateStorageType type =StorageType.Memory;/**
         * 指定key前缀.
         */privateString keyPrefix ="wa";/**
         * http客户端类型.
         */privateHttpClientType httpClientType =HttpClientType.HttpClient;/**
         * http代理主机.
         */privateString httpProxyHost;/**
         * http代理端口.
         */privateInteger httpProxyPort;/**
         * http代理用户名.
         */privateString httpProxyUsername;/**
         * http代理密码.
         */privateString httpProxyPassword;/**
         * http 请求重试间隔
         * <pre>
         *   {@link cn.binarywang.wx.miniapp.api.impl.BaseWxMaServiceImpl#setRetrySleepMillis(int)}
         * </pre>
         */privateInteger retrySleepMillis =1000;/**
         * http 请求最大重试次数
         * <pre>
         *   {@link cn.binarywang.wx.miniapp.api.impl.BaseWxMaServiceImpl#setMaxRetryTimes(int)}
         * </pre>
         */privateInteger maxRetryTimes =5;}}

3.4 微信相关存储方式配置类

packagecom.qiangesoft.miniapp.config.ma.store;importcn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;importcn.hutool.core.util.StrUtil;importcom.qiangesoft.miniapp.properties.WxMaProperties;/**
 * 微信配置抽象
 *
 * @author qiangesoft
 * @since 2024-07-16
 */publicabstractclassAbstractWxMaStorageConfiguration{/**
     * 配置
     *
     * @param config
     * @param properties
     * @return
     */protectedWxMaDefaultConfigImplconfig(WxMaDefaultConfigImpl config,WxMaProperties properties){// 基本配置
        config.setAppid(StrUtil.trimToNull(properties.getAppid()));
        config.setSecret(StrUtil.trimToNull(properties.getSecret()));
        config.setToken(StrUtil.trimToNull(properties.getToken()));
        config.setAesKey(StrUtil.trimToNull(properties.getAesKey()));
        config.setMsgDataFormat(StrUtil.trimToNull(properties.getMsgDataFormat()));// 代理配置WxMaProperties.ConfigStorage configStorageProperties = properties.getConfigStorage();
        config.setHttpProxyHost(configStorageProperties.getHttpProxyHost());
        config.setHttpProxyUsername(configStorageProperties.getHttpProxyUsername());
        config.setHttpProxyPassword(configStorageProperties.getHttpProxyPassword());if(configStorageProperties.getHttpProxyPort()!=null){
            config.setHttpProxyPort(configStorageProperties.getHttpProxyPort());}int maxRetryTimes = configStorageProperties.getMaxRetryTimes();if(configStorageProperties.getMaxRetryTimes()<0){
            maxRetryTimes =0;}int retrySleepMillis = configStorageProperties.getRetrySleepMillis();if(retrySleepMillis <0){
            retrySleepMillis =1000;}
        config.setRetrySleepMillis(retrySleepMillis);
        config.setMaxRetryTimes(maxRetryTimes);return config;}}
packagecom.qiangesoft.miniapp.config.ma.store;importcn.binarywang.wx.miniapp.config.WxMaConfig;importcn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;importcom.qiangesoft.miniapp.properties.WxMaProperties;importlombok.RequiredArgsConstructor;importorg.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;importorg.springframework.boot.autoconfigure.condition.ConditionalOnProperty;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;/**
 * 内存缓存配置
 *
 * @author qiangesoft
 * @since 2024-07-16
 */@Configuration@ConditionalOnProperty(prefix =WxMaProperties.PREFIX+".config-storage", name ="type", matchIfMissing =true, havingValue ="memory")@RequiredArgsConstructorpublicclassMemoryWxMaStorageConfigurationextendsAbstractWxMaStorageConfiguration{privatefinalWxMaProperties wxMaProperties;@Bean@ConditionalOnMissingBean(WxMaConfig.class)publicWxMaConfigwxMaConfig(){WxMaDefaultConfigImpl config =newWxMaDefaultConfigImpl();returnthis.config(config, wxMaProperties);}}
packagecom.qiangesoft.miniapp.config.ma.store;importcn.binarywang.wx.miniapp.config.WxMaConfig;importcn.binarywang.wx.miniapp.config.impl.WxMaRedisBetterConfigImpl;importcom.qiangesoft.miniapp.properties.WxMaProperties;importlombok.RequiredArgsConstructor;importme.chanjar.weixin.common.redis.RedisTemplateWxRedisOps;importme.chanjar.weixin.common.redis.WxRedisOps;importorg.springframework.boot.autoconfigure.condition.ConditionalOnClass;importorg.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;importorg.springframework.boot.autoconfigure.condition.ConditionalOnProperty;importorg.springframework.context.ApplicationContext;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.data.redis.core.StringRedisTemplate;/**
 * redis缓存配置
 *
 * @author qiangesoft
 * @since 2024-07-16
 */@Configuration@ConditionalOnProperty(prefix =WxMaProperties.PREFIX+".config-storage", name ="type", havingValue ="redis")@ConditionalOnClass(StringRedisTemplate.class)@RequiredArgsConstructorpublicclassRedisWxMaStorageConfigurationextendsAbstractWxMaStorageConfiguration{privatefinalWxMaProperties properties;privatefinalApplicationContext applicationContext;@Bean@ConditionalOnMissingBean(WxMaConfig.class)publicWxMaConfigwxMaConfig(){WxMaRedisBetterConfigImpl config =getWxMaInRedisTemplateConfigStorage();returnthis.config(config, properties);}privateWxMaRedisBetterConfigImplgetWxMaInRedisTemplateConfigStorage(){StringRedisTemplate redisTemplate = applicationContext.getBean(StringRedisTemplate.class);WxRedisOps redisOps =newRedisTemplateWxRedisOps(redisTemplate);returnnewWxMaRedisBetterConfigImpl(redisOps, properties.getConfigStorage().getKeyPrefix());}}
packagecom.qiangesoft.miniapp.config.ma;importcom.qiangesoft.miniapp.config.ma.store.MemoryWxMaStorageConfiguration;importcom.qiangesoft.miniapp.config.ma.store.RedisWxMaStorageConfiguration;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Import;/**
 * 微信小程序存储策略自动配置
 *
 * @author qiangesoft
 * @since 2024-07-16
 */@Configuration@Import({MemoryWxMaStorageConfiguration.class,RedisWxMaStorageConfiguration.class})publicclassWxMaStorageAutoConfiguration{}

3.5 平台服务配置类

packagecom.qiangesoft.miniapp.config.ma;importcn.binarywang.wx.miniapp.api.WxMaService;importcn.binarywang.wx.miniapp.api.impl.WxMaServiceHttpClientImpl;importcn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;importcn.binarywang.wx.miniapp.api.impl.WxMaServiceJoddHttpImpl;importcn.binarywang.wx.miniapp.api.impl.WxMaServiceOkHttpImpl;importcn.binarywang.wx.miniapp.config.WxMaConfig;importcom.qiangesoft.miniapp.enums.HttpClientType;importcom.qiangesoft.miniapp.properties.WxMaProperties;importlombok.AllArgsConstructor;importorg.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;/**
 * 微信小程序平台相关服务自动注册
 *
 * @author qiangesoft
 * @since 2024-07-16
 */@Configuration@AllArgsConstructorpublicclassWxMaServiceAutoConfiguration{privatefinalWxMaProperties wxMaProperties;@Bean@ConditionalOnMissingBean(WxMaService.class)publicWxMaServicewxMaService(WxMaConfig wxMaConfig){HttpClientType httpClientType = wxMaProperties.getConfigStorage().getHttpClientType();WxMaService wxMaService;switch(httpClientType){caseOkHttp:
                wxMaService =newWxMaServiceOkHttpImpl();break;caseJoddHttp:
                wxMaService =newWxMaServiceJoddHttpImpl();break;caseHttpClient:
                wxMaService =newWxMaServiceHttpClientImpl();break;default:
                wxMaService =newWxMaServiceImpl();break;}
        wxMaService.setWxMaConfig(wxMaConfig);return wxMaService;}}
packagecom.qiangesoft.miniapp.config.ma;importcom.qiangesoft.miniapp.properties.WxMaProperties;importorg.springframework.boot.context.properties.EnableConfigurationProperties;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Import;/**
 * 自动配置
 *
 * @author qiangesoft
 * @since 2024-07-16
 */@Configuration@EnableConfigurationProperties(WxMaProperties.class)@Import({WxMaStorageAutoConfiguration.class,WxMaServiceAutoConfiguration.class})publicclassWxMaAutoConfiguration{}

3.6 其他配置

packagecom.qiangesoft.miniapp.config;importcn.dev33.satoken.stp.StpUtil;importcom.baomidou.mybatisplus.core.handlers.MetaObjectHandler;importorg.apache.ibatis.reflection.MetaObject;importorg.springframework.stereotype.Component;importjava.time.LocalDateTime;/**
 * 自定义sql字段填充器,自动填充创建修改相关字段
 *
 * @author qiangesoft
 * @date 2024-04-11
 */@ComponentpublicclassCustomMetaObjectHandlerimplementsMetaObjectHandler{@OverridepublicvoidinsertFill(MetaObject metaObject){setFieldValByName("createUser",StpUtil.getLoginIdAsLong(), metaObject);setFieldValByName("createTime",LocalDateTime.now(), metaObject);}@OverridepublicvoidupdateFill(MetaObject metaObject){setFieldValByName("updateUser",StpUtil.getLoginIdAsLong(), metaObject);setFieldValByName("updateTime",LocalDateTime.now(), metaObject);}}
packagecom.qiangesoft.miniapp.config;importcom.baomidou.mybatisplus.annotation.DbType;importcom.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;importcom.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;/**
 * mybatis-plus配置
 *
 * @author qiangesoft
 * @date 2024-04-11
 */@ConfigurationpublicclassMybatisPlusConfig{/**
     * 分页插件
     */@BeanpublicMybatisPlusInterceptormybatisPlusInterceptor(){MybatisPlusInterceptor interceptor =newMybatisPlusInterceptor();
        interceptor.addInnerInterceptor(newPaginationInnerInterceptor(DbType.MYSQL));return interceptor;}}

3.7 常量

packagecom.qiangesoft.miniapp.enums;/**
 * httpclient类型
 *
 * @author qiangesoft
 * @since 2024-07-16
 */publicenumHttpClientType{/**
     * HttpClient.
     */HttpClient,/**
     * OkHttp.
     */OkHttp,/**
     * JoddHttp.
     */JoddHttp,}
packagecom.qiangesoft.miniapp.enums;/**
 * storage类型
 *
 * @author qiangesoft
 * @since 2024-07-16
 */publicenumStorageType{/**
     * 内存.
     */Memory,/**
     * redis.
     */Redis}

3.8 启动类

packagecom.qiangesoft.miniapp;importorg.mybatis.spring.annotation.MapperScan;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;/**
 * 启动类
 *
 * @author qiangesoft
 * @since 2024-07-16
 */@MapperScan("com.qiangesoft.miniapp.mapper")@SpringBootApplicationpublicclassWxMaApplication{publicstaticvoidmain(String[] args){SpringApplication.run(WxMaApplication.class, args);}}

四、至此本节结束


本文转载自: https://blog.csdn.net/weixin_39311781/article/details/141251557
版权归原作者 PG_强哥 所有, 如有侵权,请联系我们删除。

“SpringBoot集成微信小程序 (一)【搭建】”的评论:

还没有评论