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

相关推荐
小猪咪piggy13 分钟前
【JavaEE】(1) 计算机如何工作
java
smileNicky18 分钟前
SpringBoot系列之OpenAI API 创建智能博客评论助手
java·spring boot·后端
弥鸿28 分钟前
MinIO的安装和使用
java·spring boot·java-ee·springcloud·javaee
丿BAIKAL巛1 小时前
如何使用Java生成pdf报告
java·pdf
hy.z_7772 小时前
【数据结构】 栈和队列
java·数据结构
栗子~~3 小时前
idea 安装飞算-javaAI 插件使用
java·ide·intellij-idea
蓉妹妹3 小时前
React+Taro 微信小程序做一个页面,背景图需贴手机屏幕最上边覆盖展示
react.js·微信小程序·taro
zy happy3 小时前
黑马点评前端Nginx启动失败问题解决记录
java·运维·前端·spring boot·nginx·spring
lxyker4 小时前
MongoDB大数据量的优化——mongoTemplate.stream()方法使用
java·数据库·mongodb·性能优化·数据库调优