目錄
①註冊公衆號(或者使用測試號)
註冊地址: https://mp.weixin.qq.com/
測試號地址: https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
②接口配置
URL:服務器的地址
Token: 隨便寫等下要與服務器那邊一致
首先我們本地開發,沒有獨立IP 需要進行內網穿透下個軟件 windows_amd64.zip
然後去官網 http://www.ngrok.cc/user.html 註冊登錄 購買
隧道名稱隨便
前置域名你喜歡啥填啥
本地端口按我的來
點擊隧道管理
複製你的贈送域名(填寫到微信測試號URL中 。。加上要訪問的地址哦 如下圖)
③創建一個項目
控制器
@RequestMapping(value="wx",method= RequestMethod.GET)
public void vx(HttpServletRequest request, HttpServletResponse response) {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
PrintWriter out = null;
try {
out = response.getWriter();
if(CheckUtil.checkSignature(signature, timestamp, nonce)){
out.write(echostr);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
out.close();
}
}
public class CheckUtil {
private static final String token = "czxcvsvasv";
public static boolean checkSignature(String signature,String timestamp,String nonce){
String[] str = new String[]{token,timestamp,nonce};
//排序
Arrays.sort(str);
//拼接字符串
StringBuffer buffer = new StringBuffer();
for(int i =0 ;i<str.length;i++){
buffer.append(str[i]);
}
//進行sha1加密
String temp = SHA1.encode(buffer.toString());
//與微信提供的signature進行匹對
return signature.equals(temp);
}
/**
* sha1加密算法
* @author Administrator
*
*/
public class SHA1 {
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* Takes the raw bytes from the digest and formats them correct.
*
* @param bytes the raw bytes from the digest.
* @return the formatted bytes.
*/
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
// 把密文轉換成十六進制的字符串形式
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
public static String encode(String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}