package com.dxg.wechatdemo.weixin.pm.controller;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dxg.wechatdemo.weixin.pm.config.WechatMpProperties;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author Binary Wang(https://github.com/binarywang)
*/
@Controller
@RequestMapping("/wechat/portal")
public class WechatController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private WxMpService wxService;
@Autowired
private WxMpMessageRouter router;
@Resource
WechatMpProperties wmProperties;
@GetMapping(produces = "text/plain;charset=utf-8")
public void 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, HttpServletResponse response) {
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)) {
try {
response.getWriter().write(echostr);
response.getWriter().flush();
response.getWriter().close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return echostr;
}
// return "非法请求";
}
@PostMapping(produces = "application/xml; charset=UTF-8")
public String post(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/xml;charset=UTF-8");
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String encType = request.getParameter("encrypt_type");
String msgSignature = request.getParameter("msg_signature");
StringBuilder xmlMsg = new StringBuilder();
// 处理接收消息
try {
ServletInputStream in = request.getInputStream();
// 将流转换为字符串
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1; ) {
xmlMsg.append(new String(b, 0, n, "UTF-8"));
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String requestBody = xmlMsg.toString();
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)) {
// 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 "";
}
out = outMessage.toEncryptedXml(this.wxService.getWxMpConfigStorage());
}
this.logger.debug("\n组装回复信息:{}", out);
try {
response.getWriter().write(out);
response.getWriter().flush();
response.getWriter().close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public void weixinRedirect(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("application/json;charset=UTF-8");
String path = request.getParameter("path");
if (path == null) {
path = "?";
} else {
path = "%3fpath%3d" + path + "&";
}
this.logger.info("\n path = {} \n", path);
String redirectUrl = new String("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wmProperties.getAppId() + "&redirect_uri=http%3a%2f%2f" + wmProperties.getHost() + "%2fwechat%2fportal%2fgetUserOpenId" + path + "response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect");
logger.info("redirectUrl:" + redirectUrl);
response.sendRedirect(redirectUrl);
}
/* @GetMapping(value = "/getUserOpenId")
public void getUserOpenId(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("application/json;charset=UTF-8");
//参数
String code = request.getParameter("code");
String path = request.getParameter("path");
if (path == null) {
path = "";
}
WxMpOAuth2AccessToken accessToken = this.wxService.oauth2getAccessToken(code);
this.logger.info("\n code = {} \n openId = {} \n path = {} \n",code,accessToken.getOpenId(),path);
FcConsumerLoginInfo consumerLoginInfo = this.wechatMpService.getConsumerLoginInfo(accessToken.getOpenId());
String tokenStr = URLEncoder.encode(consumerLoginInfo.getToken(),"UTF-8");
String redirectUrl = new String(path+"?openId="+accessToken.getOpenId()+"&token="+tokenStr);
logger.info("公众号重定向url是:"+redirectUrl);
response.sendRedirect(redirectUrl);
}*/
//
// @RequestMapping(value = "/getWeixinOpenId", method = RequestMethod.GET)
// public void getWeixinOpenIdRedirect(HttpServletRequest request, HttpServletResponse response) throws Exception {
// response.setContentType("application/json;charset=UTF-8");
// this.logger.info("接口 getWeixinOpenId url = [{}] , \n ",request.getRequestURL());
// String redirectUrl = new String("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx07472b5042a0e627&redirect_uri=http%3a%2f%2f"+WxConstant.WX_HOST+"%2fwechat%2fportal
没有合适的资源?快使用搜索试试~ 我知道了~
资源详情
资源评论
资源推荐
收起资源包目录





































































































共 162 条
- 1
- 2





















0老船长0
- 粉丝: 13
上传资源 快速赚钱
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助


最新资源
- (源码)基于OpenGL框架的CG机器人手臂模拟系统.zip
- 基于MATLAB的模糊自适应PID控制:程序调通,动态性能提升的10页报告 - 仿真
- 微电网两阶段鲁棒优化经济调度方法及其Python代码实现
- (源码)基于 Raspberry Pi 的 FM 广播系统.zip
- MATLAB仿真下基于串电阻策略的双馈风力发电机低电压穿越研究
- 基于深度强化学习(DQNDDPGTD3)的混合动力汽车能量管理策略研究与应用
- (源码)基于Python和PyTorch的图像分类深度学习系统.zip
- 复现兰志勇老师的新型三矢量模型:预测电流控制下的永磁同步电机控制原理 - 三角函数运算 权威版
- 基于MATLAB的信号处理GUI:AM、DSB、SSB及FM调制解调交互系统设计与实现 · MATLAB
- (源码)基于C语言的嵌入式LED显示与串行通信系统.zip
- 小型三相光伏并网发电系统:电导增量法与干扰观察法的控制策略研究
- (源码)基于C语言的Crazyflie无人机控制系统.zip
- 永磁同步电机绕组计算器:磁动势与绕组系数的技术解析及应用 说明
- 基于PLC S7-1200与MCGS组态的小区恒压供水系统仿真及优化
- (源码)基于Python的智能家庭助手系统.zip
- 基于OpenFAST与Simulink联合仿真模型的非线性风电机组独立变桨与统一变桨控制研究
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈



安全验证
文档复制为VIP权益,开通VIP直接复制

评论0