在讲微信公众号开发之前,先来大概了解一下微信公众号。微信公众号大体上可以分为服务号和订阅号,订阅号和服务号的区别如下:
- 一 公众号配置服务器
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>mica-weixin</artifactId>
<version>2.0.1</version>
</dependency>
dream:mica-weixin已经为我们提供好了消息校验接口,只需要继承DreamMsgControllerAdapter就可以了。
weixin:
wx-configs:
- appId: xxxxxx
appSecret: xxxxxx
token: javatrip
encodingAesKey: xxxxxx
@SpringBootApplication2.1 关注消息
@EnableCaching
public class WeixinApplication {
public static void main(String[] args) {
SpringApplication.run(WeixinApplication.class, args);
}
}
@Override
protected void processInTextMsg(InTextMsg inTextMsg) {
String content = inTextMsg.getContent();
// 根据用户发送的content去查询db中的响应内容
if("文本消息"){
OutTextMsg otm = new OutTextMsg(inTextMsg);
otm.setContent("消息内容");
render(otm);
return;
}else if("图片消息"){
OutImageMsg oim = new OutImageMsg(inTextMsg);
// 这里需要调用微信提供的素材接口,将图片上传至素材库。
oim.setMediaId("图片素材id");
render(oim);
return;
}else if("图文消息"){
OutNewsMsg onm = new OutNewsMsg(inTextMsg);
onm.addNews("标题","简介","图片地址","图文链接");
render(onm);
return;
}else if("视频消息"){
OutVideoMsg ovm = new OutVideoMsg(inTextMsg);
ovm.setTitle("标题");
ovm.setDescription("简介");
ovm.setMediaId("视频素材id");
render(ovm);
return;
}else{
OutTextMsg otm = new OutTextMsg(inTextMsg);
otm.setContent("暂未查到关键词...");
}
}
@Override
protected void processInMenuEvent(InMenuEvent inMenuEvent) {
String eventKey = inMenuEvent.getEventKey();
// 根据用户发送的content去查询db中的响应内容
if("文本消息"){
OutTextMsg otm = new OutTextMsg(inMenuEvent);
otm.setContent("消息内容");
render(otm);
return;
}else if("图片消息"){
OutImageMsg oim = new OutImageMsg(inMenuEvent);
// 这里需要调用微信提供的素材接口,将图片上传至素材库。
oim.setMediaId("图片素材id");
render(oim);
return;
}else if("图文消息"){
OutNewsMsg onm = new OutNewsMsg(inMenuEvent);
onm.addNews("标题","简介","图片地址","图文链接");
render(onm);
return;
}else if("视频消息"){
OutVideoMsg ovm = new OutVideoMsg(inMenuEvent);
ovm.setTitle("标题");
ovm.setDescription("简介");
ovm.setMediaId("视频素材id");
render(ovm);
return;
}else{
OutTextMsg otm = new OutTextMsg(inMenuEvent);
otm.setContent("无效链接,请重试...");
}
}
调用接口的时候需要传递token,获取token需要在微信后台中配置业务服务器的白名单。如下:
mica-weixin提供了所有的接口封装,具体可参考它的官方文档,如果要获取微信菜单,可以这样写:四 其他事项dream:
weixin:
wx-configs:
- appId: xxxxxx
appSecret: xxxxxx
token: javatrip
encodingAesKey: xxxxxx
- appId: xxxxxx
appSecret: xxxxxx
token: javatrip
encodingAesKey: xxxxxx
spring:
redis:
host: localhost
port: 6379
ApiConfigKit.setThreadLocalAppId(appid);