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

相关推荐
程序猿DD3 分钟前
人工智能如何改变 Anthropic 的工作方式
java·后端
C雨后彩虹5 分钟前
任务总执行时长
java·数据结构·算法·华为·面试
桦说编程10 分钟前
Guava Forwarding系列类详解——装饰器模式实战
java·后端·设计模式
柒.梧.23 分钟前
数据结构:二叉排序树构建与遍历的解析与代码实现
java·开发语言·数据结构
大道之简1 小时前
SpringAI基于内存存储向量
java
算法与双吉汉堡1 小时前
【短链接项目笔记】Day2 用户注册
java·redis·笔记·后端·spring
北漂IT民工_程序员_ZG2 小时前
SpringBean生命周期,动态代理
java·spring boot·spring
老华带你飞2 小时前
建筑材料管理|基于springboot 建筑材料管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习·spring
木心爱编程2 小时前
【Qt 5.14.2 新手实战】QTC++入门筑基——按钮与标签联动:QPushButton + QLabel 实现图片切换器
java·c++·qt
椰羊~王小美3 小时前
setScale没传roudingmode,为什么会报错
java