1. 程式人生 > >Java後臺與微信公眾號互動

Java後臺與微信公眾號互動

理論就不說了,直接上程式碼
下面是一個比對微信伺服器傳送過來的請求的工具類,前提是得匯入一個jar包,commons-codec-1.9.jar,我用的是1.9的版本,直接去網上下載即可。
下載連結:http://central.maven.org/maven2/commons-codec/commons-codec/1.9/commons-codec-1.9.jar

package org.weixin.utils;

import java.util.Arrays;

import org.apache.commons.codec.digest.DigestUtils;

public class CheckUtil {

	// 一定要和微信公總平臺設定的token 值一致
	private static final String token = "xxxxx";

	public static boolean checkSignature(String signature, String timestamp,
			String nonce) {

		String[] arr = new String[] { token, timestamp, nonce };

		// 排序
		Arrays.sort(arr);
		// 生成字串
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}

		// sha1加密
		String temp = getSHA1String(content.toString());

		// 與微信傳遞過來的簽名進行比較
		return temp.equals(signature);
	}

	private static String getSHA1String(String data) {
		// 使用commons codec生成sha1字串
		return DigestUtils.sha1Hex(data);
	}

}

然後就是直接呼叫該工具類。

public class WeChatServlet extends HttpServlet {

	/**
	 * 接收微信伺服器傳送的4個引數並返回echostr
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("進入...");
		// 接收微信伺服器以Get請求傳送的4個引數
		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 (CheckUtil.checkSignature(signature, timestamp, nonce)) {
			System.out.println("比對成功!");
			out.print(echostr); // 校驗通過,原樣返回echostr引數內容
		}
	}

	/**
	 * 接收並處理微信客戶端傳送的請求
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			// 在這裡處理微信公眾號發來的各種請求,如關注事件、回覆資訊、點選事件等
			System.out.println("接收到微信服務端傳送的請求。");
	}
}