微信公众号开发流程
1.填写服务器配置
2.验证服务器地址的有效性
3.依据接口文档实现业务逻辑
1.接口配置
URL为内网穿透映射的URL
Token则是你随意定即可
软件环境:idea+springboot
image.png
2.验证消息的确来自微信服务器
开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带参数如下表所示:
signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
timestamp 时间戳
nonce 随机数
echostr 随机字符串
开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:
1)将token、timestamp、nonce三个参数进行字典序排序 2)将三个参数字符串拼接成一个字符串进行sha1加密 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
对比方法如下:
public boolean check(String signature, String timestamp, String nonce, String token) {
//1)将token、timestamp、nonce三个参数进行字典序排序
String[] str = new String[]{token, timestamp, nonce};
Arrays.sort(str);
//2)将三个参数字符串拼接成一个字符串进行sha1加密
String str2 = str[0] + str[1] + str[2];
String sha1Str = addSha1(str2);
//3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
sha1Str.equals(signature);
return true;
}
2.contoller方法
@RestController
@RequestMapping("wx")
public class DemoWxController {
@Value("${demo.token}")
private String token;
@Resource
private DemoWxService demoWxService;
@GetMapping("test")
public void demoTest(HttpServletRequest request, HttpServletResponse response) {
//第二步:验证消息的确来自微信服务器
//开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带参数如下表所示:
//signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
//timestamp 时间戳
//nonce 随机数
//echostr 随机字符串
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
System.out.println(signature);
System.out.println(timestamp);
System.out.println(nonce);
System.out.println(echostr);
//开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:
try {
if (demoWxService.check(signature, timestamp, nonce, token)) {
System.out.println("微信接入成功");
PrintWriter writer = null;
writer = response.getWriter();
//原样返回echostr参数内容
writer.print(echostr);
writer.flush();
writer.close();
} else {
System.out.println("微信接入失败");
}
} catch (IOException e) {
e.printStackTrace();
}
}
3.启动项目
image.png
4.点击接口配置信息提交,这里微信会和服务器进行对接,匹配成功则提交成功,否则失败
image.png