一、注册一个公众号
微信公众平台官网:https://mp.weixin.qq.com/
微信公众号注册地址:https://mp.weixin.qq.com/cgi-bin/registermidpage?action=index&lang=zh_CN
个人只能注册订阅号、注册成功后使用微信登录
二、实现接入认证接口
仔细微信阅读接入指南文档:官网开发文档
三、接口调用
调用方法及参数说明
开发者提交服务器地址信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带参数如下表所示
开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:
1)将token、timestamp、nonce三个参数进行字典序排序
2)将三个参数字符串拼接成一个字符串进行sha1加密
3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
4)java代码实现参考以下service层checkAccess方法
四、实现代码
controller层
@RestController
@RequestMapping(value = "/api/wx")
public class WechatController {
@Resource
private WechatService wechatService;
/**
* 微信接入认证接口
* @author Liyh
* @date 2024/10/23 14:18
* @param signature
* @param timestamp
* @param nonce
* @param echostr
* @return String
*/
@GetMapping("")
public String checkAccess(@RequestParam("signature") String signature,
@RequestParam("timestamp") String timestamp,
@RequestParam("nonce") String nonce,
@RequestParam("echostr") String echostr) {
return wechatService.checkAccess(signature, timestamp, nonce, echostr);
}
}
service层
public String checkAccess(String signature, String timestamp, String nonce, String echostr) {
log.info("接入微信公众号验证:===>【{}】【{}】【{}】【{}】",signature, timestamp, nonce, echostr);
// 1. 将token、timestamp、nonce三个参数进行字典序排序
String token = "aB3c******7kL8mN";
String[] arr = {timestamp, nonce, token};
Arrays.sort(arr);
// 2. 将三个参数字符串拼接成一个字符串进行sha1加密
StringBuilder sb = new StringBuilder();
for (String temp : arr) {
sb.append(temp);
}
// 2.1这里利用了hutool的加密工具类
String sha1 = Sha1Util.sha1(sb.toString());
// 3. 加密后的字符串与signature对比,如果相同则该请求来源于微信,原样返回echostr
if (sha1.equals(signature)){
return echostr;
}
// 接入失败
return null;
}
util 工具类
public class Sha1Util {
public static String sha1(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
byte[] hash = digest.digest(input.getBytes("UTF-8"));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException | java.io.UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
五、测试接入验证
1、可以使用测试公众号测试(可以调用非80、443端口地址)
显示配置成功表示接口可以调用
2、使用自己注册的公众号测试(服务器地址端口必须是80、443)
可以在服务器安装nginx进行80端口映射
显示提交成功表示接口配置成功