package org.baozi.web.wechat;
import lombok.extern.slf4j.Slf4j;
import org.baozi.config.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
/**
* 测试号管理-接口配置信息-url, 用来测试是否能够连通改程序与微信公众平台
*/
@Controller
@Slf4j
public class WechatConnectController {
/**
* 微信:timestamp、nonce、测试号管理中-接口配置信息-token,组成signature
* 并将signature、timestamp、nonce和一个随机字符串echostr发送到服务器方
* 服务器:timestamp、nonce、代码中的token,组成signature
* 比较两个signature,比较成功就将echostr返回
*
* @param request
* @param response
*/
@GetMapping("/wechat")
public void doGet(HttpServletRequest request, HttpServletResponse response) throws NoSuchAlgorithmException, IOException {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
log.debug("signature:{}, timestamp:{}, nonce:{}, echostr:{}", signature, timestamp, nonce, echostr);
// 组合signature:
// 1)将token、timestamp、nonce三个参数进行字典序排序
String[] arr = new String[]{Constants.TOKEN, timestamp, nonce};
Arrays.sort(arr);
// 2)将三个参数字符串拼接成一个字符串进行sha1加密
StringBuilder content = new StringBuilder();
for (String s : arr) {
content.append(s);
}
byte[] digest = MessageDigest.getInstance("SHA-1").digest(content.toString().getBytes());
String tempSignature = byteToStr(digest);
log.debug("新signature:{}", tempSignature);
// 3)开发者获得加密后的字符串可与signature对比,对比成功输出echostr
try (PrintWriter out = response.getWriter()) {
if (tempSignature.equalsIgnoreCase(signature)) {
out.write(echostr);
}
}
}
/**
* 将 字节数组 转换为十六进制字符串,转成的是大写的
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
StringBuilder sb = new StringBuilder();
for (byte b : byteArray) {
sb.append(byteToHexStr(b));
}
return sb.toString();
}
/**
* 将 字节 转换为十六进制字符串
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
return new String(tempArr);
}
}
网友评论