Java生成微信小程序码及小程序短链接

使用wx-java-miniapp-spring-boot-starter 生成微信小程序码及小程序短链接

  1. 在pom.xml文件中引入依赖

    复制代码
     	<dependency>
     		<groupId>com.github.binarywang</groupId>
     		<artifactId>wx-java-miniapp-spring-boot-starter</artifactId>
     		<version>4.7.0</version>
     	</dependency>
    
     	<dependency>
     		<groupId>org.springframework.boot</groupId>
     		<artifactId>spring-boot-starter-data-redis</artifactId>
     	</dependency>
  2. application.yml中配置小程序参数

    spring:
    application:
    name: wx-poster
    data:
    redis:
    host: 192.168.1.111
    port: 6379
    password: 123456
    database: 0

    wx:
    miniapp:
    configs:
    scm:
    appid: wx1234567890abcdef
    secret: test-567890abcdef1234567890abcdef
    msgDataFormat: JSON
    mall:
    appid: wxe8db97a0603abcde
    secret: test-35f85ebb2135bdcd9e154de12345
    msgDataFormat: JSON

  3. 加载配置及实例化服务类

    @Data
    @Configuration
    @ConfigurationProperties(prefix = "wx.miniapp")
    public class WxMaProperties {
    private Map<String, Config> configs;

    复制代码
     @Data
     public static class Config {
         private String appid;
         private String secret;
         private String msgDataFormat;
     }

    }

    @Configuration
    public class WxMaConfiguration {
    @Autowired
    private WxMaProperties properties;
    @Autowired
    private StringRedisTemplate redisTemplate;

    复制代码
     @Bean
     public Map<String, WxMaConfig> wxMaConfigs() {
         Map<String, WxMaConfig> configMap = new HashMap<>();
         WxRedisOps wxRedisOps = new RedisTemplateWxRedisOps(redisTemplate);
    
         properties.getConfigs().forEach((key, config) -> {
             WxMaRedisBetterConfigImpl maConfig = new WxMaRedisBetterConfigImpl(wxRedisOps, "wechat");
             maConfig.setAppid(config.getAppid());
             maConfig.setSecret(config.getSecret());
             maConfig.setMsgDataFormat(config.getMsgDataFormat());
             configMap.put(key, maConfig);
         });
    
         return configMap;
     }
    
     @Bean
     public WxMaService wxMaService() {
         WxMaService service = new WxMaServiceImpl();
         service.setMultiConfigs(wxMaConfigs());
         return service;
     }

    }

  4. 根据微信小程序标识及页面路径,生成小程序码

    @Slf4j
    @Service
    public class WxMaManagerService {
    @Autowired
    private WxMaService wxMaService;

    复制代码
     /**
      * 生成小程序码
      */
     @SneakyThrows
     public byte[] createWxaCode(WechatGenerateQrCodeParam param) {
         WxMaService service = wxMaService.switchoverTo(param.getAppKey());
    
         try {
             return service.getQrcodeService().createWxaCodeUnlimitBytes(param.getScene(), param.getPage(), param.getCheckPath(), param.getEnvVersion(),
                     param.getWidth(), param.getAutoColor(), param.getLineColor(), param.getIsHyaline());
         } catch (Exception e) {
             if (isTokenInvalid(e)) {
                 // 如果token无效,刷新一次后重试
                 service.getWxMaConfig().expireAccessToken();
                 return service.getQrcodeService().createWxaCodeUnlimitBytes(param.getScene(), param.getPage(), param.getCheckPath(), param.getEnvVersion(),
                         param.getWidth(), param.getAutoColor(), param.getLineColor(), param.getIsHyaline());
             }
             throw new RuntimeException("生成小程序码失败", e);
         }
     }
    
     /**
      * 生成短链接
      */
     @SneakyThrows
     public String createShortLink(WechatGenerateShortLinkParam param) {
         WxMaService service = wxMaService.switchoverTo(param.getAppKey());
         // 短期有效
         GenerateShortLinkRequest shortLinkRequest = GenerateShortLinkRequest.builder().pageUrl(param.getPageUrl()).isPermanent(false).build();
    
         try {
             return service.getLinkService().generateShortLink(shortLinkRequest);
         } catch (Exception e) {
             if (isTokenInvalid(e)) {
                 // 如果token无效,刷新一次后重试
                 service.getWxMaConfig().expireAccessToken();
                 return service.getLinkService().generateShortLink(shortLinkRequest);
             }
             throw new RuntimeException("生成短链接失败", e);
         }
     }
    
     /**
      * 判断是否是token无效的错误
      */
     private boolean isTokenInvalid(Exception e) {
         String errorMsg = e.getMessage();
         return StringUtils.containsIgnoreCase(errorMsg, "access_token")
                 && (StringUtils.containsIgnoreCase(errorMsg, "invalid")
                 || StringUtils.containsIgnoreCase(errorMsg, "expired"));
     }

    }

完整代码地址 https://gitee.com/galen.zhang/wx-poster

相关推荐
小学仔16 分钟前
科大镜像科大镜像科大镜像
java
小旭952716 分钟前
Java 反射详解
java·开发语言·jvm·面试·intellij-idea
HalvmånEver19 分钟前
Linux:线程创建与终止上(线程五)
java·linux·jvm
m0_7482331726 分钟前
PHP版本演进:从7.x到8.x全解析
java·开发语言·php
qq_124987075327 分钟前
基于springboot的林业资源管理系统设计与实现(源码+论文+部署+安装)
java·vue.js·spring boot·后端·spring·毕业设计·计算机毕业设计
当战神遇到编程34 分钟前
图书管理系统
java·开发语言·单例模式
indexsunny35 分钟前
互联网大厂Java求职面试实战:Spring Boot微服务与Kafka消息队列应用解析
java·数据库·spring boot·微服务·面试·kafka·jpa
说私域43 分钟前
开源链动2+1模式商城小程序在深度分销数字化转型中的应用研究
人工智能·小程序·开源·流量运营·私域运营
shuair44 分钟前
springboot整合redisson单机模式
java·spring boot·后端
Remember_9931 小时前
Java 单例模式深度解析:设计原理、实现范式与企业级应用场景
java·开发语言·javascript·单例模式·ecmascript