[JavaWeb] 接入微信公众号(一)

微信公众号

相信大家对微信公众号都不陌生,本文就从开发者角度,简单说说目前微信公众号的状况。

分为三个类型:订阅号、服务号、企业号,一旦选定不可以修改。

微信公众号类型介绍

微信公众平台测试账号

我们直接申请测试账号,减少很多麻烦,很多权限也可以直接使用,不需要认证。

申请链接:微信公众平台接口测试帐号申请页

微信公众号交互模型

如下图,用户给公众号发送消息后,通过“微信后台”转发给“我们开发的服务”,“我们开发的后台”根据请求进行响应,返回给“微信后台”,微信后台再转发给我们的用户。
微信公众号交互模型2

接入微信公众号

接入微信时,微信服务器将发送 GET 请求到填写的服务器地址 URL 上,GET 请求携带四个参数:

参数 描述
signature 微信加密签名,signature 结合了开发者填写的 token 参数和请求中的 timestamp 参数、nonce 参数。
timestamp 时间戳
nonce 随机数
echostr 随机字符串

开发者通过检验 signature 对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回 echostr 参数内容,则接入生效,成为开发者成功,否则接入失败。

验证服务器地址的有效性

此代码仅适用于明文传输模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 接口代码 ,采用 SpringMVC 框架
@RequestMapping(value = "/weixin", method = RequestMethod.GET)
@ResponseBody
public void renzheng(HttpServletRequest request, HttpServletResponse response) throws IOException {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");

PrintWriter out = response.getWriter();
// 判断该请求是否来源于微信
if (WeChatCheckUtil.checkSignature(signature, timestamp, nonce)) {
out.print(echostr);
}
}

具体的校验方法

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    private static final String token = "aaaaaaaa";
private static final String EncodingAESKey = "sh5xZjYG1oKWc0douiZVzgaAP3n6ZH111CkZ5haaaa";

public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[]{token, timestamp, nonce};

// 1. 将token、timestamp、nonce三个参数进行字典序排序
Arrays.sort(arr);

// 2. 将三个参数字符串拼接成一个字符串
StringBuffer content = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}

//sha1 加密
String temp = getSha1(content.toString());

// 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
return temp.equals(signature);
}

// 具体的 SHA1 加密方法
public static String getSha1(String str) {
if (null == str || 0 == str.length()) {
return null;
}
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));

byte[] md = mdTemp.digest();
int j = md.length;
char[] buf = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
// e.printStackTrace();
return null;
}
}

填写服务器配置

官方接口配置图
接口配置

目前微信接口配置时仅支持以 http:// 或 https:// 开头,分别支持 80 端口和 443 端口。

我们大多数人开发环境都没有公网 80 端口,本次采用解决的方法是 ngrok 局域网穿透。

采用 ngrok 局域网穿透

ngrok 的官网 是 https://ngrok.com/,服务器在国外。个人比较推荐国内的 http://ngrok.cc/,自己申请一个账号,按照教程自己配置就行了。如果还是遇到困难可以给我留言或者发邮件。

有经济实力的可以赞助一下作者。

配置接口信息

假设已经配置 ngrok 了,并启动。在微信公众平台接口测试帐号里面填入”接口配置信息”,URL 和 Token。

没有意外就会提示配置成功。

消息的接收和响应

当普通微信用户向公众账号发消息时,微信服务器将 POST 消息的 XML 数据包到开发者填写的 URL 上。

文本消息

微信中推送的一条普通的文本格式如下:

1
2
3
4
5
6
7
8
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1348831860</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[this is a test]]></Content>
<MsgId>1234567890123456</MsgId>
</xml>

Mavem 引入 xml 解析相关依赖

1
2
3
4
5
6
7
8
9
10
11
12
<!--XML 解析-->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- 对象类型转成 XML-->
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.7</version>
</dependency>

消息工具类代码

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class MessageUtil {
// 消息类型
public static final String MESSAGE_TEXT = "text";
public static final String MESSAGE_IMAGE = "image";
public static final String MESSAGE_VOICE = "voice";
public static final String MESSAGE_VIDEO = "video";
public static final String MESSAGE_LINK = "link";
public static final String MESSAGE_LOCATION = "location";
// 事件推送 event
public static final String MESSAGE_EVENT = "event";
// 关注
public static final String MESSAGE_SUBSCRIBE = "subscribe";
// 取消关注
public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";
//菜单点击
public static final String MESSAGE_CLICK = "CLICK";
// 浏览
public static final String MESSAGE_VIEW = "VIEW";


/**
* 将 xml 转换成 Map 集合
*/

public static Map<String, String> xmlToMap(HttpServletRequest request){
Map<String, String> map = new LinkedHashMap<String, String>();
SAXReader reader = new SAXReader();

try {
ServletInputStream inputStream = request.getInputStream();
Document document = reader.read(inputStream);
Element rootElement = document.getRootElement();
List<Element> elements = rootElement.elements();
for (Element e: elements) {
map.put(e.getName(), e.getText());
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
return map;
}

/**
* 对象类型转换成 xml
*/

public static String textMessageToXml(TextMessage textMessage){
XStream xStream = new XStream();
xStream.alias("xml", textMessage.getClass());
return xStream.toXML(textMessage);
}
}

封装了消息的基本类型,提供了对象转成 xml 方法,以及 xml 转成 Map 集合。

响应服务器的代码

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
29
30
31
32
33
    @RequestMapping(value = "/weixin", method = RequestMethod.POST)
public void xiaoxi(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> map = MessageUtil.xmlToMap(request);
String fromUserName = map.get("FromUserName");
String toUserName = map.get("ToUserName");
String msgType = map.get("MsgType");
String content = map.get("Content");
// request.setCharacterEncoding("utf-8");
PrintWriter responseWriter = null;
try {
responseWriter = response.getWriter();
String message = null;
if (MessageUtil.MESSAGE_TEXT.equals(msgType)) {
TextMessage textMessage = new TextMessage();
textMessage.setFromUserName(toUserName);
textMessage.setToUserName(fromUserName);
textMessage.setMsgType("text");
textMessage.setCreateTime(new Date().getTime());
textMessage.setContent("您发送的消息为:" + content);
message = MessageUtil.textMessageToXml(textMessage);
System.out.println("消息:");
System.out.println(message);
}else if (MessageUtil.MESSAGE_EVENT.equals(msgType)){
// TODO 关注后等各种操作
System.out.println("关注后的操作。");
}
responseWriter.print(message);
} catch (IOException e) {
e.printStackTrace();
} finally {
responseWriter.close();
}
}

这样就简单的实现了,发送什么回复什么了。

参考资料