开发环境接入
准备外网映射工具
按照微信公众平台的开发者文档要求,验证消息的确来自微信服务器时需要用到URL
可参考ngrok工具:
进行下载配置(我的ngrok程序放在了F盘根目录下了):
每次用的时候都需要启动cmd命令端
f:
cd ngrok
ngrok -config=ngrok.cfg -subdomain xxx 8080
运行结果就是:
Tunnel Status online
Version 1.7/1.7
Forwarding http://xxx.tunnel.2bdata.com -> 127.0.0.1:8080
http://xxx.tunnel.2bdata.com/
Forwarding https://xxx.tunnel.2bdata.com -> 127.0.0.1:8080
Web Interface 127.0.0.1:4040
# Conn 0
Avg Conn Time 0.00ms
验证消息的确来自微信服务器
根据微信开发者文档要求
signature:微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
timestamp:时间戳
nonce: 随机数
echostr:随机字符串
开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,
请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:
1)将token、timestamp、nonce三个参数进行字典序排序
2)将三个参数字符串拼接成一个字符串进行sha1加密
3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
部分参考代码:
/**
* 校验工具类
*/
public class checkUtil {
private static String token = "uxawsenyweixin";
//检验方法
public static boolean checkSignature(String signature, String timestamp, String nonce) throws AesException {
String[] array = new String[]{token, timestamp, nonce};
//排序
Arrays.sort(array);
//拼接字符串
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; i++) {
sb.append(array[i]);
}
String str = sb.toString();
//SHA1加密
String sha1Str = getSHA1(str);
return sha1Str.equals(signature);
}
//加密方法getSHA1实现
public static String getSHA1(String str) throws AesException {
try {
// SHA1签名生成
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.ComputeSignatureError);
}
}
}
文本转XML
/**
* 文本对象转成xml
*
* @param textMessage
* @return
*/
public static String textMessageToXml(TextMessage textMessage) {
XStream xStream = new XStream();
xStream.alias("xml", textMessage.getClass());
return xStream.toXML(textMessage);
}
xml转文本(map)
/**
* xml转map
*
* @param request
* @return
* @throws IOException
* @throws DocumentException
*/
public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
Map<String, String> map = new HashMap<>();
SAXReader reader = new SAXReader();
//读取xml中的数据
InputStream input = request.getInputStream();
Document document = reader.read(input);
//获取根元素
Element root = document.getRootElement();
List<Element> list = root.elements();
//遍历list并存进map
for (Element e : list) {
map.put(e.getName(), e.getText());
}
input.close();
return map;
}
完整参考代码见:
https://git.coding.net/uxaw/weixin-v0.1.git
BAE
uxawsen.duapp.com
http://weixin1230.duapp.com/weixin_war/weixinServlet