当我们需要使用SpringBoot来开发一个微信公众号的后台的时候,第一步就是将我们的SpringBoot服务和微信公众号进行服务器的绑定,那么他是怎么进行绑定的呢?
开始验证
我们打开微信公众号(假设你已经拥有了一个公众号)的后台,在左侧的最后有开发选项,这里我们需要申请成为一个开发者,然后在他的基本配置中,我们看到了服务器配置选项(在他的第二项开发者工具中有详细的文档,我们也可以直接看那个):
服务器配置
我们看到这里的总共分为四个选项,其中EncodingASEKey的值是随机生成的,而消息加解密的方式我们暂时先采用明文模式。所以我们需要填写的主要就是服务器Url和令牌Token两项。Url自然就是我们SpringBoot启动之后接口的地址,令牌token正是我们用来验证接口服务的关键。值得注意的是,这里的接口地址需要提供GET和POST两种请求方式,GET请求用于验证接口的配置,POST请求用于功能的使用,所以我们今天先来说GET请求。
微信验证的过程
使用接口的get方法,我们可以获得四个参数:
参数名 | 释义 |
---|---|
signature | 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。 |
timestamp | 时间戳 |
nonce | 随机数 |
echostr | 随机字符串 |
然后校验流程如下:
- 将获取到的timestamp和nonce以及我们的token(我们在上图中需要配置的token,为了简单,我们把它先写死在程序里)进行字典序排序
- 将排序好的参数字符串进行sha1加密
- 将排序好后的字符串和signature进行对比,如果一致,则说明该请求来自微信
- 返回echostr字段,则代表微信验证通过
工程的搭建
知道了校验的过程,我们就可以开始写了,首先肯定是要新建一个SpringBoot的工程,他的pom文件可以这样设置,这是用idea直接生成的一个Spring Boot工程,只是我给他加上了swagger:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yu5</groupId>
<artifactId>wechat</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>wechat</name>
<description>WeChat project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
因为这里http协议的地址必须使用80端口,所以我们来配置一下application.properties
:
server.port=80
server.servlet.context-path=/weChart
然后我们写Controller:
package com.yu5.wechat.controller;
import com.yu5.wechat.utils.CheckSignatureUtil;
import com.yu5.wechat.utils.MessageUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
@Controller
public class RestController {
@Autowired
private CheckSignatureUtil checkSignatureUtil;
@ApiOperation(value = "登陆验证", notes = "登陆验证")
@RequestMapping(value="/dealData", method = RequestMethod.GET)
public void dealData(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
System.out.println("-------------验证服务号登陆信息-------------");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
PrintWriter out = null;
try {
out = response.getWriter();
if(checkSignatureUtil.checkSignature( signature, timestamp, nonce)){
out.write(echostr);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
out.close();
System.out.println("-------------验证服务号登陆信息结束-------------");
}
}
}
然后是处理校验步骤的CheckSignatureUtil
,这里我们把token
的值写为yWeChart9992
,可根据喜好任意修改:
package com.yu5.wechat.utils;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.security.MessageDigest;
@Service
public class CheckSignatureUtil {
private static final String token = "yWeChart9992";
public Boolean checkSignature(String signature, String timestamp, String nonce){
String[] str = new String[]{token, timestamp, nonce};
// 对三个参数进行字典序排序
Arrays.sort(str);
StringBuffer sb = new StringBuffer();
for(int i=0;i<str.length;i++){
sb.append(str[i]);
}
// 进行sha1加密算法转换
return signature.equals(getSha1(sb.toString()));
}
/**
* 微信采用的sha1加密算法
* @param str
* @return
*/
private String getSha1(String str) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
return null;
}
}
}
这样我们一个基本SpringBoot就写好了,我们可以启动这个SpringBoot工程,然后利用NATAPP将它映射到外网:
NATAPP映射
然后我们就可以直接在微信的服务器配置界面进行配置了,这里
token
的值需和代码中的token
值一致,我们代码中写的是yWeChart9992
:服务器配置
配置完成后选择提交,如果出现提交成功,这说明服务器配置通过,接下来我们就可以开心的进行微信公众号的开发了。