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

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

  1. 在pom.xml文件中引入依赖
		
			com.github.binarywang
			wx-java-miniapp-spring-boot-starter
			4.7.0
		

		
			org.springframework.boot
			spring-boot-starter-data-redis
		
  1. 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
  1. 加载配置及实例化服务类
@Data
@Configuration
@ConfigurationProperties(prefix = "wx.miniapp")
public class WxMaProperties {
    private Map 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 wxMaConfigs() {
        Map 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;
    }
}
  1. 根据微信小程序标识及页面路径,生成小程序码
@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

你可能感兴趣的:(小程序,java,微信小程序)