1 package com.zone.weixin4j.socket;
2
3 import com.zone.weixin4j.exception.WeixinException;
4 import com.zone.weixin4j.response.WeixinResponse;
5 import com.zone.weixin4j.service.context.WeiXin4jContextAwareImpl;
6 import com.zone.weixin4j.type.EncryptType;
7 import com.zone.weixin4j.util.AesToken;
8 import com.zone.weixin4j.util.MessageUtil;
9 import com.zone.weixin4j.util.ServerToolkits;
10 import org.springframework.stereotype.Component;
11
12
13
14
15
16
17
18
19
20
21
22
23
24 @Component
25 public class WeixinResponseEncoder {
26
27 private final String XML_START = "<xml>";
28
29 private final String ELEMENT_TOUSERNAME = "<ToUserName><![CDATA[%s]]></ToUserName>";
30 private final String ELEMENT_FROMUSERNAME = "<FromUserName><![CDATA[%s]]></FromUserName>";
31 private final String ELEMENT_CREATETIME = "<CreateTime><![CDATA[%d]]></CreateTime>";
32 private final String ELEMENT_MSGTYPE = "<MsgType><![CDATA[%s]]></MsgType>";
33
34 private final String ELEMENT_MSGSIGNATURE = "<MsgSignature><![CDATA[%s]]></MsgSignature>";
35 private final String ELEMENT_ENCRYPT = "<Encrypt><![CDATA[%s]]></Encrypt>";
36 private final String ELEMENT_TIMESTAMP = "<TimeStamp><![CDATA[%s]]></TimeStamp>";
37 private final String ELEMENT_NONCE = "<Nonce><![CDATA[%s]]></Nonce>";
38 private final String XML_END = "</xml>";
39
40 public String encode(WeixinResponse response) throws WeixinException {
41 WeixinMessageTransfer messageTransfer = WeiXin4jContextAwareImpl.getWeixinMessageTransfer().get();
42 EncryptType encryptType = messageTransfer.getEncryptType();
43 StringBuilder content = new StringBuilder();
44 content.append(XML_START);
45 content.append(String.format(ELEMENT_TOUSERNAME,
46 messageTransfer.getFromUserName()));
47 content.append(String.format(ELEMENT_FROMUSERNAME,
48 messageTransfer.getToUserName()));
49 content.append(String.format(ELEMENT_CREATETIME,
50 System.currentTimeMillis() / 1000l));
51 content.append(String.format(ELEMENT_MSGTYPE, response.getMsgType()));
52 content.append(response.toContent());
53 content.append(XML_END);
54 if (encryptType == EncryptType.AES) {
55 AesToken aesToken = messageTransfer.getAesToken();
56 String nonce = ServerToolkits.generateRandomString(32);
57 String timestamp = Long
58 .toString(System.currentTimeMillis() / 1000l);
59 String encrtypt = MessageUtil.aesEncrypt(aesToken.getWeixinId(),
60 aesToken.getAesKey(), content.toString());
61 String msgSignature = MessageUtil.signature(aesToken.getToken(),
62 nonce, timestamp, encrtypt);
63 content.delete(0, content.length());
64 content.append(XML_START);
65 content.append(String.format(ELEMENT_NONCE, nonce));
66 content.append(String.format(ELEMENT_TIMESTAMP, timestamp));
67 content.append(String.format(ELEMENT_MSGSIGNATURE, msgSignature));
68 content.append(String.format(ELEMENT_ENCRYPT, encrtypt));
69 content.append(XML_END);
70 }
71 return content.toString();
72 }
73 }