使用第三方代码库接入微信

​ 在前公司的时候公司里有个项目因为要做微信小程序,我腹中其中的后端开发。一般来说微信开发的后端开发主要都要做鉴权验证,我为了偷点懒就上github找了一下,就发现了本文要讲的这个jar包。

传送门

​ 使用的第一步,理所当然的是要导包,我用的是gradle,所以我在build.gradle文件里的依赖区内这样写:

1
2
3
4
5
6
7
//微信开发工具
//小程序
compile "com.github.binarywang:weixin-java-miniapp:${WX_TOOL_VERSION}"
//公众号
compile "com.github.binarywang:weixin-java-mp:${WX_TOOL_VERSION}"
//开放平台
compile "com.github.binarywang:weixin-java-open:${WX_TOOL_VERSION}"

PS1:maven引用请参照github说明。

PS2:我引入了三个包是因为这个项目并不仅仅只是小程序,还有其他微信相关的需求要实现,所以如果你只是要做小程序的后端项目的话,只引入小程序的包就足够了。

接下来的第二部步并不是直接写代码,而是要配置参数项,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#微信
wechat:
#小程序
miniapp:
#APPID
appid: appid
#secret
secret: secret
#token
token: token
#aesKey
aesKey: aesKey
#数据格式
msgDataFormat: JSON

写入从微信公众平台获取到的对应的数据后,再写一个配置类读取以上配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Data
@ConfigurationProperties(prefix = "wechat.miniapp")
public class WxPrgConfig {
/**
* 设置微信小程序的appid
*/
private String appid;

/**
* 设置微信小程序的Secret
*/
private String secret;

/**
* 设置微信小程序的token
*/
private String token;

/**
* 设置微信小程序的EncodingAESKey
*/
private String aesKey;

/**
* 消息格式,XML或者JSON
*/
private String msgDataFormat;
}

PS:我这里使用了Lombok,所以没有gettersetter

再然后把这里的配置写入到bean中,载入到spring中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Configuration
@ConditionalOnClass(WxMaService.class)
@EnableConfigurationProperties(WxPrgConfig.class)
public class WxConfig {

@Autowired
private WxPrgConfig properties;

@Bean
@ConditionalOnMissingBean
public WxMaConfig maConfig() {
WxMaInMemoryConfig config = new WxMaInMemoryConfig();
config.setAppid(this.properties.getAppid());
config.setSecret(this.properties.getSecret());
config.setToken(this.properties.getToken());
config.setAesKey(this.properties.getAesKey());
config.setMsgDataFormat(this.properties.getMsgDataFormat());

return config;
}

@Bean
@ConditionalOnMissingBean
public WxMaService wxMaService(WxMaConfig maConfig) {
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(maConfig);
return service;
}

PS:工具类的作者有写小程序的demo,那里的配置更全面。传送门

做完以上三个步骤就OK了,剩下的就是在你需要使用这个工具的地方注入WxMaService,再通过它就可以获取用户的微信信息了。

AlexC wechat
博客与公众号同步发文,欢迎关注
感谢你的支持