1.去微信开放平台申请微信公众号账号测试
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Requesting_an_API_Test_Account.html
申请
这里需要填写url和token
url我这里写了个接口,微信支持80端口,所以我这里也是80端口
这里的url需要外网访问,我用Natapp内网映射的域名(教程:https://blog.csdn.net/YXWik/article/details/114526089)
配置好之后就是接口了,我在网上找的一个demo,测试可以使用,给大家贴出来
Controller
/**
* @author: YXY
* @date: 2021/3/8 11:52
* @Version 1.0
*/
@RestController
@RequestMapping("/wx")
public class WxSignatureCheckController {
@Autowired
private WxSignatureCheckService wxSignatureCheckService;
@RequestMapping("/wxSignatureCheck")
public String wxSignatureCheck(
@RequestParam(value = "signature") String signature,
@RequestParam(value = "timestamp") String timestamp,
@RequestParam(value = "nonce") String nonce,
@RequestParam(value = "echostr") String echostr
){
return wxSignatureCheckService.wxSignatureCheck(signature, timestamp, nonce, echostr);
}
}
Service
/**
* @author: YXY
* @date: 2021/3/8 11:53
* @Version 1.0
*/
public interface WxSignatureCheckService {
String wxSignatureCheck(String signature, String timestamp, String nonce, String echostr);
}
ServiceImpl
/**
* @author: YXY
* @date: 2021/3/8 11:53
* @Version 1.0
*/
@Service
public class WxSignatureCheckServiceImpl implements WxSignatureCheckService {
//token
private final String token = "wxtoken";
public String wxSignatureCheck(String signature, String timestamp, String nonce, String echostr) {
ArrayList<String> array = new ArrayList<String>();
array.add(signature);
array.add(timestamp);
array.add(nonce);
//排序
String sortString = sort(token, timestamp, nonce);
//加密
String mytoken = Decript.SHA1(sortString);
//校验签名
if (mytoken != null && mytoken != "" && mytoken.equals(signature)) {
System.out.println("签名校验通过。");
return echostr; //如果检验成功输出echostr,微信服务器接收到此输出,才会确认检验完成。
} else {
System.out.println("签名校验失败。");
return null;
}
}
/**
* 排序方法
* @param token
* @param timestamp
* @param nonce
* @return
*/
public static String sort(String token, String timestamp, String nonce) {
String[] strArray = { token, timestamp, nonce };
Arrays.sort(strArray);
StringBuilder sbuilder = new StringBuilder();
for (String str : strArray) {
sbuilder.append(str);
}
return sbuilder.toString();
}
}
加密
/**
* @author: YXY
* @date: 2021/3/8 11:54
* @Version 1.0
* 加密的方法
*/
public class Decript {
public static String SHA1(String decript) {
try {
MessageDigest digest = MessageDigest
.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
// 字节数组转换为 十六进制 数
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}
上面代码放到项目中,运行起来,端口给80
然后回到接口配置点击提交
这里要保证serviceImpl中的token 和公众号接口配置的token一致
这样就配置好了