使用weixin-java-miniapp配置进行单个小程序的配置详解

在进行小程序后端接口开发方面,使用weixin-java-tools中的weixin-java-miniapp模块,往往可以事半功倍。

引入weixin-java-tools

在https://mvnrepository.com/中搜索weixin-java-miniapp,进入微信小程序 Java SDK这个项目中。

选择相应正式版本来进行使用。

maven中在依赖中添加如下配置项:

<dependency>
 <groupId>com.github.binarywang</groupId>
 <artifactId>weixin-java-miniapp</artifactId>
 <version>3.3.0</version>
</dependency>

gradle中添加如下配置项:

compile("com.github.binarywang:weixin-java-miniapp:3.3.0")

注意:以上我用的版本是3.3.0,实际中根据你要使用的版本来用。

配置文件

配置文件中主要配置四项参数,分别是:

  • appId
  • secret
  • token
  • aesKey

配置初始化:

weixin-java-miniapp可以使用注解来进行配置,具体步骤如下:

在config包中创建WxMaConfiguration类。

使用@Configuration注解来进行小程序相关的参数配置,可参考以下代码。

该代码示例中是单个小程序配置示例,如果需要配置多个小程序的参数,请参考官方案例点击进入。

package com.diboot.miniapp.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import dibo.framework.config.BaseConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WxMaConfiguration {

 // 此处获取配置的方式可以改成你自己的方式,也可以注解等方式获取配置等。
 private static final String appId = BaseConfig.getProperty("wechat.appId");
 private static final String secret = BaseConfig.getProperty("wechat.secret");
 private static final String token = BaseConfig.getProperty("wechat.token");
 private static final String aesKey = BaseConfig.getProperty("wechat.aesKey");

 private static WxMaService wxMaService = null;

 @Bean
 public Object services(){
  WxMaInMemoryConfig config = new WxMaInMemoryConfig();
  config.setAppid(appId);
  config.setSecret(secret);
  config.setToken(token);
  config.setAesKey(aesKey);

  wxMaService = new WxMaServiceImpl();
  wxMaService.setWxMaConfig(config);

  return Boolean.TRUE;
 }

 public static WxMaService getWxMaService(){
  return wxMaService;
 }
}

开始使用

在需要使用小程序相关接口的地方,只需要通过该配置类中的静态方法getWxMaService()来获取到wxMaService即可开始使用,如:

 // 获取小程序服务实例
WxMaService wxMaService = WxMaConfiguration.getWxMaService();
// 获取小程序二维码生成实例
WxMaQrcodeService wxMaQrcodeService = wxMaService.getQrcodeService();
// 便可以开始使用wxMaQrcodeService来进行二维码相关的处理了
....

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。