后台代码
控制器
package com.example.demo.controller;
import com.example.demo.util.Sha1Util;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
@RestController
public class WechatController {
/**
* @return 微信请求接收
*/
@GetMapping(value = "/weixin", produces = "text/plain;charset=UTF-8")
public ResponseEntity weixin(@RequestParam(name = "signature") String signature,
@RequestParam(name = "timestamp") String timestamp,
@RequestParam(name = "nonce") String nonce,
@RequestParam(name = "echostr") String echostr) {
String auths[] = {token(自己填的 token), timestamp, nonce};
Arrays.sort(auths);
if (signature.equals(Sha1Util.getSha1(auths[0] + auths[1] + auths[2]))) {
if (null != echostr) {
return ResponseEntity.ok(this.auth(echostr));
}
}
return ResponseEntity.ok().build();
}
/**
* @param echostr
* @return 认证
*/
private String auth(String echostr) {
return echostr;
}
@GetMapping(value = "/test")
public ResponseEntity test() {
return ResponseEntity.ok("测试成功!");
}
}
Sha1 加密
package com.example.demo.util;
import java.security.MessageDigest;
public class Sha1Util {
public static String getSha1(String str){
if (null == str || 0 == str.length()){
return null;
}
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) {
e.printStackTrace();
return null;
}
}
}
微信后台配置
后台的 token 就是控制器中自己配置的 token
url 就填 http://你的链接/weixin
提交就验证成功了