1. 程式人生 > >微信公眾號接收訊息密文解密及明文加密後自動回覆

微信公眾號接收訊息密文解密及明文加密後自動回覆

1.使用token驗證後的地址接收訊息

/**
	 * 將微信公眾號接收資訊(引數微信會攜帶過來)
	 * @params timestamp 時間戳
	 * @params nonce 隨機串
	 * @params  msg_signature 訊息簽名
	 * @params  requestBody 訊息體
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/msg")
	public String msg( @RequestBody String requestBody,
					   @RequestParam(name = "timestamp",required = false) String timestamp,
					   @RequestParam(name = "nonce", required = false) String nonce,
					   @RequestParam(name = "msg_signature", required = false) String msg_signature
	) {
		System.out.print(requestBody+"\n");
		System.out.print(timestamp+"\n");
		System.out.print(nonce+"\n");
		System.out.print(msg_signature+"\n");
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("requestBody", requestBody);
		jsonObject.put("token", token);
		jsonObject.put("nonce",nonce);
		jsonObject.put("timestamp", timestamp);
		jsonObject.put("msg_signature", msg_signature);
		jsonObject.put("appId",appid);
		jsonObject.put("encodingAesKey", encodingAESKey);
		String sendUrl = "http://localhost:8080/wechat/myboot/msgDecrypt";
		String result=HttpConnection.doPost(sendUrl,jsonObject.toJSONString());
		System.out.print("明文:"+result);
		String toUserName = result.substring(result.indexOf("<xml><ToUserName><![CDATA[") + "<xml><ToUserName><![CDATA[".length(), result.indexOf("]]></ToUserName>"));
		String msgType = result.substring(result.indexOf("<MsgType><![CDATA[") +"<MsgType><![CDATA[".length(), result.indexOf("]]></MsgType>"));
		String fromUserName = result.substring(result.indexOf("<FromUserName><![CDATA[") + "<FromUserName><![CDATA[".length(), result.indexOf("]]></FromUserName>"));
		String resultStr="";
		String replay = "";
        //自己包裝返回xml資訊
        replay=WeChatXMLUtils.textXML(fromUserName,toUserName,new Date().getTime()+"","您好!手機號繫結成功。");
        //加密後返回加密的xml
        resultStr=send( replay, token, nonce, timestamp, appid, encodingAESKey);
		return resultStr;
	}
public static String send(String replay,String token,String nonce,String timestamp,String appid,String encodingAESKey){
		System.out.print(replay+"\n");
		String encryptUrl = "http://localhost:8080/wechat/myboot/msgEncrypt";
		JSONObject jsonObject1 = new JSONObject();
		jsonObject1.put("requestBody", replay);
		jsonObject1.put("token", token);
		jsonObject1.put("nonce",nonce);
		jsonObject1.put("timestamp", timestamp);
		jsonObject1.put("appId",appid);
		jsonObject1.put("encodingAesKey", encodingAESKey);
		String miwenResult=HttpConnection.doPost(encryptUrl,jsonObject1.toJSONString());
		System.out.print(miwenResult);
		return miwenResult;
	}
public class WeChatXMLUtils {

    public static String textXML(String toUser,String fromUser,String time,String content){
        String format ="<xml><ToUserName><![CDATA[%1$s]]></ToUserName><FromUserName><![CDATA[%2$s]]></FromUserName><CreateTime>%3$s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%4$s]]></Content></xml>";

        return String.format(format, toUser, fromUser, time, content);
    }
}

 

 

2.地址:http://localhost:8080/wechat/myboot/msgDecrypt 為另一個專門微信專案的解密介面,token為驗證token時寫的token

 /**
     * 解密
     * @param requestBody   傳送的請求本體
     * @return              訊息體解密後的字串
     * @throws Exception
     */
    @PostMapping(produces = "text/plain;charset=utf-8",value = "/msgDecrypt")
    public static String msgDecrypt(@RequestBody String requestBody) throws Exception{
        JSONObject  obj = JSONObject.parseObject(requestBody);
        String token=obj.get("token").toString();
        String replyMsg=obj.get("requestBody").toString();
        String timestamp=obj.get("timestamp").toString();
        String nonce=obj.get("nonce").toString();
        String appId=obj.get("appId").toString();
        String msgSignature=obj.get("msg_signature").toString();
        String encodingAesKey=obj.get("encodingAesKey").toString();
        WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
        String str=pc.decryptMsg(msgSignature, timestamp, nonce, replyMsg);
        return str;
    }

    /**
     * 加密
     * @param requestBody   加密的請求體
     * @return
     * @throws Exception
     */
    @PostMapping(produces = "text/plain;charset=utf-8",value = "/msgEncrypt")
    public static String msgEncrypt(
            @RequestBody String requestBody
    ) throws Exception{
        JSONObject  obj = JSONObject.parseObject(requestBody);
        String token=obj.get("token").toString();
        String replyMsg=obj.get("requestBody").toString();
        String timestamp=obj.get("timestamp").toString();
        String nonce=obj.get("nonce").toString();
        String appId=obj.get("appId").toString();
        String encodingAesKey=obj.get("encodingAesKey").toString();
        //建立初始化微信加解密物件
        WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
        //生成加密字串
        String miwen = pc.encryptMsg(replyMsg, timestamp, nonce);
        System.out.println("加密後: " + miwen);
        return miwen;
    }

3.解密方法為微信官方的方法

官方地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1434696670