微信公衆號配置消息接口

服務器代碼,內網穿透

package io.renren.modules.generator.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
public class Test extends HttpServlet
{
private static final long serialVersionUID = 1L;

public static final String TOKEN = "majie";


@GetMapping("/checkToken")
protected void doget(HttpServletRequest request, HttpServletResponse response) throws IOException
{

String signature = request.getParameter("signature");
// 時間戳
String timestamp = request.getParameter("timestamp");
// 隨機數
String nonce = request.getParameter("nonce");
// 隨機字符串
String echostr = request.getParameter("echostr");
System.out.println(signature + timestamp + nonce);

PrintWriter out = response.getWriter();
// 通過檢驗signature對請求進行校驗,若校驗成功則原樣返回echostr,表示接入成功,否則接入失敗
if (checkSignature(signature, timestamp, nonce).equals(signature)) {
out.write(echostr);
System.out.println("微信服務驗證成功!"+echostr);
}else {
out.print(echostr);
System.out.println("微信服務驗證失敗!"+echostr);
}
out.flush();
out.close();
}

public static String checkSignature(String signature ,String timestamp, String nonce)
{
String[] src = {TOKEN,timestamp,nonce};
List<String> list =Arrays.asList(src);
Collections.sort(list);

StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++)
{
sb.append(list.get(i));
}
return SHA1(sb.toString());

}

/**
*
* @param decript
* @return
*/
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 "";
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章