package com.ojins.app.controller;

import com.ojins.app.handler.BarcodeImageHandler;
import me.chanjar.weixin.mp.api.*;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutTextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Created by nwang on 23/01/16.
 */
@RestController
@RequestMapping("/")
public class WechatController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
    private WxMpService wxMpService = new WxMpServiceImpl();
    private WxMpMessageRouter wxMpMessageRouter;
    BarcodeImageHandler barcodeImageHandler = new BarcodeImageHandler();

    @PostConstruct
    public void init() throws Exception {
        config.setAppId("wxbe56750a77d32699"); // 设置微信公众号的appid
        config.setSecret("111a719fc630269177389e402f77b1e4"); // 设置微信公众号的app corpSecret
        config.setToken("ojinscom"); // 设置微信公众号的token
        config.setAesKey("aoGcSLZpgW12i46uP8AZ2w6z707nSYmg1YLUsxj2Ee2"); // 设置微信公众号的EncodingAESKey

        wxMpService.setWxMpConfigStorage(config);

        WxMpMessageHandler handler =
                (wxMpXmlMessage, map, wxMpService1, wxSessionManager) -> WxMpXmlOutMessage
                        .TEXT()
                        .content("测试加密消息")
                        .fromUser(wxMpXmlMessage.getToUserName())
                        .toUser(wxMpXmlMessage.getFromUserName())
                        .build();

        wxMpMessageRouter = new WxMpMessageRouter(wxMpService);
        wxMpMessageRouter
                .rule()
                .async(false)
                .msgType("image") // forward anykind of image to barcode handler
                .handler(barcodeImageHandler)
                .end();
        logger.info("initialized handler.");
    }

    @RequestMapping(method = RequestMethod.GET,
                    produces = "text/html;charset=utf-8")
    public ResponseEntity<String> getVerificationResponse(
            @RequestParam(defaultValue = "") String signature,
            @RequestParam(defaultValue = "") String nonce,
            @RequestParam(defaultValue = "") String timestamp,
            @RequestParam(defaultValue = "") String echostr) throws IOException {
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            // 消息签名不正确，说明不是公众平台发过来的消息
            logger.warn("消息签名不正确");
            return new ResponseEntity<>("非法请求", HttpStatus.OK);
        }

        if (StringUtils.isNotBlank(echostr)) {
            // 说明是一个仅仅用来验证的请求，回显echostr
            logger.info("一个仅仅用来验证的请求");
            return new ResponseEntity<>(echostr, HttpStatus.OK);
        }

        logger.warn("不可识别的加密类型");
        return new ResponseEntity<>("不可识别的加密类型", HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.POST,
                    produces = "text/html;charset=utf-8")
    public ResponseEntity<String> getResponse(@RequestParam(defaultValue = "") String signature,
                                              @RequestParam(defaultValue = "") String nonce,
                                              @RequestParam(defaultValue = "") String timestamp,
                                              @RequestParam(defaultValue = "") String echostr,
                                              @RequestParam(defaultValue = "raw") String encrypt_type,
                                              @RequestParam(defaultValue = "") String msg_signature,
                                              @RequestBody(required = false) String request) throws IOException {
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            // 消息签名不正确，说明不是公众平台发过来的消息
            logger.warn("消息签名不正确");
            return new ResponseEntity<>("非法请求", HttpStatus.OK);
        }

        if (StringUtils.isNotBlank(echostr)) {
            // 说明是一个仅仅用来验证的请求，回显echostr
            logger.info("一个仅仅用来验证的请求");
            return new ResponseEntity<>(echostr, HttpStatus.OK);
        }

        if ("raw".equals(encrypt_type)) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(
                    new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8)));
            WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
            if (outMessage == null) {
                return new ResponseEntity<>(HttpStatus.OK);
            }
            logger.info("明文传输的消息, content = {}",((WxMpXmlOutTextMessage) outMessage).getContent());
            return new ResponseEntity<>(outMessage.toXml(), HttpStatus.OK);
        }

        if ("aes".equals(encrypt_type)) {
            // 是aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage
                    .fromEncryptedXml(
                            new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8)),
                            config, timestamp, nonce, msg_signature);
            WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
            if (outMessage == null) {
                return new ResponseEntity<>(HttpStatus.OK);
            }
            logger.info("aes加密的消息, content = {}",((WxMpXmlOutTextMessage) outMessage).getContent());
            return new ResponseEntity<>(outMessage.toXml(), HttpStatus.OK);
        }

        logger.warn("不可识别的加密类型");
        return new ResponseEntity<>("不可识别的加密类型", HttpStatus.OK);
    }
}

@@ -107,16 +107,115 @@
 xin.
-mp.api.*
+common.util.StringUtils;%0Aimport me.chanjar.weixin.mp.api.*;%0Aimport me.chanjar.weixin.mp.bean.WxMpXmlMessage
 ;%0Aim
@@ -425,51 +425,8 @@
 us;%0A
-import org.springframework.http.MediaType;%0A
 impo
@@ -524,108 +524,8 @@
 *;%0A%0A
-import me.chanjar.weixin.common.util.StringUtils;%0Aimport me.chanjar.weixin.mp.bean.WxMpXmlMessage;%0A%0A
 impo
@@ -4759,32 +4759,86 @@
 sage == null) %7B%0A
+                logger.warn(%22out message is empty!%22);%0A
                 
@@ -5517,32 +5517,86 @@
 sage == null) %7B%0A
+                logger.warn(%22out message is empty!%22);%0A
                 

add log