1. 程式人生 > >909422229_微信公眾號接收訊息進行回覆

909422229_微信公眾號接收訊息進行回覆

一、基於上一篇文章已經說了如何配置伺服器,配置完成後給公眾號傳送訊息會返回接收的訊息內容,一個json串。

二、開啟上一篇提供的專案地址,開啟WechatController

程式碼如下:這個程式碼是我經過接收的訊息處理過的,使用的是加密後的訊息,經過解密後得到一個XML訊息串。

從這裡看的出來,在驗證tokent的時候的連結與接收訊息的連結是一致的,

驗證token是GET請求,會自動在GET方法中處理token,進行驗證。@GetMapping

處理訊息的時候是POST,會在POST方法中處理訊息。@PostMapping

package com.qh.wechat.controller;

import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
import com.qh.wechat.builder.TextBuilder;
import com.qh.wechat.service.QhChatService;
import com.qh.wechat.utils.JsonUtils;
import com.qh.wechat.utils.StringHelpers;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@RestController
@RequestMapping("/wechat/portal")
public class WechatController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private WxMpService wxService;

	@Autowired
	private WxMpMessageRouter router;

	@Autowired
	private QhChatService qhChatService;

	@GetMapping(produces = "text/plain;charset=utf-8")
	public String authGet(@RequestParam(name = "signature", required = false) String signature,
			@RequestParam(name = "timestamp", required = false) String timestamp,
			@RequestParam(name = "nonce", required = false) String nonce,
			@RequestParam(name = "echostr", required = false) String echostr) {

		this.logger.info("\n接收到來自微信伺服器的認證訊息:[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);

		if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
			throw new IllegalArgumentException("請求引數非法,請核實!");
		}

		if (this.wxService.checkSignature(timestamp, nonce, signature)) {
			return echostr;
		}

		return "非法請求";
	}

	@PostMapping(produces = "application/xml; charset=UTF-8")
	public String post(@RequestBody String requestBody, @RequestParam("signature") String signature,
			@RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce,
			@RequestParam(name = "encrypt_type", required = false) String encType,
			@RequestParam(name = "msg_signature", required = false) String msgSignature) {
//		this.logger.info(
//				"\n接收微信請求:[signature=[{}], encType=[{}], msgSignature=[{}],"
//						+ " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
//				signature, encType, msgSignature, timestamp, nonce, requestBody);

		if (!this.wxService.checkSignature(timestamp, nonce, signature)) {
			throw new IllegalArgumentException("非法請求,可能屬於偽造的請求!");
		}
		String out = null;
		if (encType == null) {
			// 明文傳輸的訊息
			WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
			WxMpXmlOutMessage outMessage = this.route(inMessage);
			if (outMessage == null) {
				return "";
			}

			out = outMessage.toXml();
		} else if ("aes".equals(encType)) {
			this.logger.info("--------------------aes加密的訊息");
			// aes加密的訊息
			WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody,
					this.wxService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);

//			this.logger.debug("\n訊息解密後內容為:\n{} ", inMessage.toString());
//			WxMpXmlOutMessage outMessage = this.route(inMessage);
//			if (outMessage == null) {
//				return "";
//			}
			JSONObject jsStr = JSONObject.parseObject(JsonUtils.toJson(inMessage));
			try {
				out = qhChatService.qhChat(jsStr);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
//			this.logger.info(out+"-----------呼叫介面返回資料");
			WxMpXmlOutMessage build = new TextBuilder().build(out, inMessage, this.wxService);
			out = build.toEncryptedXml(this.wxService.getWxMpConfigStorage());

			// 組裝XML返回給微信
//      out = outMessage
//          .toEncryptedXml(this.wxService.getWxMpConfigStorage());
		}

		this.logger.debug("\n組裝回覆信息:{}", out);
		return out;
	}

	private WxMpXmlOutMessage route(WxMpXmlMessage message) {
		try {
			return this.router.route(message);
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
		}

		return null;
	}

}

 

返回的訊息也是一個XML,需要微信的API轉成XML。呼叫該方法:

WxMpXmlOutMessage build = new TextBuilder().build(out, inMessage, this.wxService);
            out = build.toEncryptedXml(this.wxService.getWxMpConfigStorage());

將需要回復的訊息拼成一個微信可以識別的一個串,返回給微信。訊息內容就是out。可以在上面處理out,然後將out重新轉成XML。

最後效果:展示出來的是一個正常的訊息,而不是一個json串。下面是我呼叫圖靈介面進行訊息的回覆。

不懂可以留言聯絡。再會。