微信公衆號成爲開發者驗證

package net.binjoo.wechat;

import java.io.IOException;
import java.util.Arrays;

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

import net.binjoo.utils.SHA1;

@SuppressWarnings("serial")
public class WechatCallbackApi extends HttpServlet {
    // 自定義 token
    private String TOKEN = "這個地方由你本身定義";

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 微信加密簽名
        String signature = request.getParameter("signature");
        // 隨機字符串
        String echostr = request.getParameter("echostr");
        // 時間戳
        String timestamp = request.getParameter("timestamp");
        // 隨機數
        String nonce = request.getParameter("nonce");

        String[] str = { TOKEN, timestamp, nonce };
        Arrays.sort(str); // 字典序排序
        String bigStr = str[0] + str[1] + str[2];
        // SHA1加密
        String digest = new SHA1().getDigestOfString(bigStr.getBytes()).toLowerCase();

        // 確認請求來至微信
        if (digest.equals(signature)) {
            response.getWriter().print(echostr);
        }
    }
}
相關文章
相關標籤/搜索