@Override
  public WxMpXmlOutMessage handle(
      WxMpXmlMessage wxMessage,
      Map<String, Object> context,
      WxMpService wxMpService,
      WxSessionManager sessionManager)
      throws WxErrorException {

    if (wxMessage.getContent().equals("1")) {
      String url =
          wxMpService.oauth2buildAuthorizationUrl(
              Configue.getBaseUrl() + "/binf/oauth/login", WxConsts.OAUTH2_SCOPE_BASE, null);
      System.out.println("url:" + url);
      String aTag = "<a href=\"" + url + "\">认证链接</a>";
      return WxMpXmlOutMessage.TEXT()
          .content(aTag)
          .fromUser(wxMessage.getToUserName())
          .toUser(wxMessage.getFromUserName())
          .build();
    } else {
      return WxMpXmlOutMessage.TEXT()
          .content(Constant.DEF_SUBSCRIBE_TEXT)
          .fromUser(wxMessage.getToUserName())
          .toUser(wxMessage.getFromUserName())
          .build();
    }
  }
示例#2
0
  /** 此逻辑为了确定请求来自微信服务器 */
  @RequestMapping(value = "/api/wechat", method = RequestMethod.GET)
  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    logger.debug("验证是否来自微信请求");
    response.setContentType("text/html;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);

    String signature = request.getParameter("signature");
    String nonce = request.getParameter("nonce");
    String timestamp = request.getParameter("timestamp");

    if (!WeChatConnector.getMpService().checkSignature(timestamp, nonce, signature)) {
      // 消息签名不正确,说明不是公众平台发过来的消息
      response.getWriter().println("非法请求");
      return;
    }

    String echostr = request.getParameter("echostr");
    if (StringUtils.isNotBlank(echostr)) {
      // 说明是一个仅仅用来验证的请求,回显echostr
      response.getWriter().println(echostr);
      return;
    }

    String encryptType =
        StringUtils.isBlank(request.getParameter("encrypt_type"))
            ? "raw"
            : request.getParameter("encrypt_type");

    if ("raw".equals(encryptType)) {
      // 明文传输的消息
      WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
      WxMpXmlOutMessage outMessage = WeChatConnector.getMpMessageRouter().route(inMessage);
      if (outMessage != null) {
        response.getWriter().write(outMessage.toXml());
      }
      return;
    }

    if ("aes".equals(encryptType)) {
      // 是aes加密的消息
      String msgSignature = request.getParameter("msg_signature");
      WxMpXmlMessage inMessage =
          WxMpXmlMessage.fromEncryptedXml(
              request.getInputStream(),
              WeChatConnector.getMpConfigStorage(),
              timestamp,
              nonce,
              msgSignature);
      WxMpXmlOutMessage outMessage = WeChatConnector.getMpMessageRouter().route(inMessage);
      response.getWriter().write(outMessage.toEncryptedXml(WeChatConnector.getMpConfigStorage()));
      return;
    }

    response.getWriter().println("不可识别的加密类型");
    return;
  }