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

相关推荐
长谷深风1114 分钟前
Agent 跑了 30 分钟宕机,如何从断点继续?
java·大数据·人工智能·ai·大模型·memory·aiagent
慧都小妮子4 分钟前
DevExpress Java 文档处理 API 免费 CTP:PDF、PowerPoint、条码与跨平台部署
java·pdf·powerpoint·devexpress·文档处理·条码生成
泡海椒7 分钟前
告别反射低效:JQuick-Java ASM动态调用链性能优化实战
java·python·性能优化
土司大王17 分钟前
LeetCode 17 电话号码的字母组合:Java 回溯模板、多叉决策树与复杂度分析
java·leetcode·决策树
CoderYanger30 分钟前
前端基础——JavaScript(WebAPI)代码案例
java·开发语言·前端·javascript·css·前端框架·html5
Nuanyt40 分钟前
JUC常见核心知识梳理02 AQS ReentrantLock CAS 原子类 线程池
java
CodeStats44 分钟前
【Java数据类型】Java底层数据类型原理(上):基本类型、转换与封装核心
java·数据类型·string·封装·转换
陈皮波比茶1 小时前
SpringCloudAlibaba
java·spring cloud·微服务
重生之小比特1 小时前
【Java SE】程序逻辑控制
java·开发语言·python
find1star1 小时前
LeetCode 25:K 个一组翻转链表
java·数据结构·算法·leetcode·链表·职场和发展·动态规划