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

相关推荐
皮皮林5512 小时前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
weixin_456904272 小时前
Spring Boot 用户管理系统
java·spring boot·后端
趁你还年轻_2 小时前
异步编程CompletionService
java
DKPT2 小时前
Java内存区域与内存溢出
java·开发语言·jvm·笔记·学习
sibylyue2 小时前
Guava中常用的工具类
java·guava
奔跑吧邓邓子2 小时前
【Java实战㉞】从0到1:Spring Boot Web开发与接口设计实战
java·spring boot·实战·web开发·接口设计
专注API从业者2 小时前
Python/Java 代码示例:手把手教程调用 1688 API 获取商品详情实时数据
java·linux·数据库·python
奔跑吧邓邓子3 小时前
【Java实战㉝】Spring Boot实战:从入门到自动配置的进阶之路
java·spring boot·实战·自动配置
ONLYOFFICE3 小时前
【技术教程】如何将ONLYOFFICE文档集成到使用Spring Boot框架编写的Java Web应用程序中
java·spring boot·编辑器
叫我阿柒啊3 小时前
Java全栈开发工程师的实战面试经历:从基础到微服务
java·微服务·typescript·vue·springboot·前端开发·后端开发