接入概述
接入微信公众平台开发,开发者需要按照如下步骤完成:
1、填写服务器配置
2、验证服务器地址的有效性
3、依据接口文档实现业务逻
第一步:填写服务器配置
登录微信公众平台官网后,在公众平台官网的开发-基本设置页面,勾选协议成为开发者,点击“修改配置”按钮,填写服务器地址(URL)、Token和EncodingAESKey,其中URL是开发者用来接收微信消息和事件的接口URL。Token可由开发者可以任意填写,用作生成签名(该Token会和接口URL中包含的Token进行比对,从而验证安全性)。EncodingAESKey由开发者手动填写或随机生成,将用作消息体加解密密钥。
同时,开发者可选择消息加解密方式:明文模式、兼容模式和安全模式。模式的选择与服务器配置在提交后都会立即生效,请开发者谨慎填写及选择。加解密方式的默认状态为明文模式,选择兼容模式和安全模式需要提前配置好相关加解密代码
第二步:验证消息的确来自微信服务器
开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带参数如下表所示:
参数 | 描述 |
---|---|
signature | 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。 |
timestamp | 时间戳 |
nonce | 随机数 |
echostr | 随机字符串 |
开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:
1)将token、timestamp、nonce三个参数进行字典序排序
2)将三个参数字符串拼接成一个字符串进行sha1加密
3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
第三步:JAVA实现接入服务器
官方文档列举了python实现方式,这边采用基于springboot的java实现。
- 新建API Controller
WeChatValidationController
@RequestMapping(value = "/wechat/validate", method = RequestMethod.GET)
public void validateWeChat(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Get parameters from the request
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
// Validate request
if (checkSignature(signature, timestamp, nonce)) {
// If validation is successful, return the echostr
response.getWriter().write(echostr);
} else {
// If validation fails, return an empty response or an error code
response.getWriter().write("Validation failed");
}
}
private boolean checkSignature(String signature, String timestamp, String nonce) {
try {
// Combine token, timestamp, and nonce
String[] arr = new String[]{TOKEN, timestamp, nonce};
// Sort lexicographically
Arrays.sort(arr);
// Concatenate strings
StringBuilder content = new StringBuilder();
for (String s : arr) {
content.append(s);
}
// Hash the result using SHA-1
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digest = md.digest(content.toString().getBytes());
// Convert byte array to hex string
StringBuilder hexString = new StringBuilder();
for (byte b : digest) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() < 2) {
hexString.append(0);
}
hexString.append(hex);
}
// Compare the calculated signature with the one provided by WeChat
return hexString.toString().equals(signature);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
结果验证
- 启动xyx-wx-sa服务
- 提交配置注册成功