首先,整理一下获取授权的步骤。
一、配置微信服务器。
//省略import部分
@RequestMapping("/wechat")
@Controller
public class MobileWechatController {
private static String token = "wechat";
@RequestMapping(value = "/testWx")
public void get(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("========WechatController========= ");
Enumeration pNames = request.getParameterNames();
while (pNames.hasMoreElements()) {
String name = (String) pNames.nextElement();
String value = request.getParameter(name);
// out.print(name + "=" + value);
String log = "name =" + name + " value =" + value;
System.out.println(log + "aaaa");
}
String signature = request.getParameter("signature");/// 微信加密签名
String timestamp = request.getParameter("timestamp");/// 时间戳
String nonce = request.getParameter("nonce"); /// 随机数
String echostr = request.getParameter("echostr"); // 随机字符串
PrintWriter out = response.getWriter();
if (checkSignature(signature, timestamp, nonce)) {
System.out.println("--------接入成功--------");
out.print(echostr);
}
out.close();
out = null;
}
private static boolean checkSignature(String signature, String timestamp, String nonce) {
System.out.println("signature:" + signature + "timestamp:" + timestamp + "nonce:" + nonce);
String[] arr = new String[] { token, timestamp, nonce };
// 将token、timestamp、nonce三个参数进行字典序排序
Arrays.sort(arr);
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
// 将三个参数字符串拼接成一个字符串进行sha1加密