微信公众号对接的官方文档都是PHP的,为止我找了好多资料,整理出如下内容,记录一下
pom.xml 如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wechat</groupId>
<artifactId>wecaht-core</artifactId>
<version>1.0-SNAPSHOT</version>
<name>package</name>
<description>Demo project for WeCaht</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--mybatis-plus 增强包-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.7</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.0.7</version>
</dependency>
<!--mybatis-plus 增强包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- http-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.6</version>
</dependency>
</dependencies>
<!-- build plugins -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<!-- spring热部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.7.RELEASE</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
WeChatContant.java 是全局常量
package com.wechat.core.common;
/**
* 微信常量
* @author hgb
* @date 2019/1/26
* Email xhy18650@sina.com
*/
public class WeChatContant {
//APPID
public static final String appID = "xxx";
//appsecret
public static final String appsecret = "xxx";
// Token 验证服务器
public static final String TOKEN = "xhy1_prod";
public static final String RESP_MESSAGE_TYPE_TEXT = "text";
public static final Object REQ_MESSAGE_TYPE_TEXT = "text";
public static final Object REQ_MESSAGE_TYPE_IMAGE = "image";
public static final Object REQ_MESSAGE_TYPE_VOICE = "voice";
public static final Object REQ_MESSAGE_TYPE_VIDEO = "video";
public static final Object REQ_MESSAGE_TYPE_LOCATION = "location";
public static final Object REQ_MESSAGE_TYPE_LINK = "link";
public static final Object REQ_MESSAGE_TYPE_EVENT = "event";
public static final Object EVENT_TYPE_SUBSCRIBE = "SUBSCRIBE";
public static final Object EVENT_TYPE_UNSUBSCRIBE = "UNSUBSCRIBE";
public static final Object EVENT_TYPE_SCAN = "SCAN";
public static final Object EVENT_TYPE_LOCATION = "LOCATION";
public static final Object EVENT_TYPE_CLICK = "CLICK";
public static final String FromUserName = "FromUserName";
public static final String ToUserName = "ToUserName";
public static final String MsgType = "MsgType";
public static final String Content = "Content";
public static final String Event = "Event";
public static final Object EVENT_KEY = "EventKey";
}
微信请求控制器
package com.wechat.core.controller;
import com.wechat.core.service.WeChatService;
import com.wechat.core.util.WeChatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* 微信处理类
* @author hgb
* @date 2019/1/26
* Email xhy18650@sina.com
*/
@RestController
public class WeChatController {
@Autowired
WeChatService weChatService;
/**
* 处理微信服务器发来的get请求,进行签名的验证
*
* signature 微信端发来的签名
* timestamp 微信端发来的时间戳
* nonce 微信端发来的随机字符串
* echostr 微信端发来的验证字符串
*/
@GetMapping(value = "prod/wechat/handler")
public String validate(@RequestParam(value = "signature") String signature,
@RequestParam(value = "timestamp") String timestamp,
@RequestParam(value = "nonce") String nonce,
@RequestParam(value = "echostr") String echostr) {
return WeChatUtil.checkSignature(signature, timestamp, nonce) ? echostr : null;
}
/**
* 此处是处理微信服务器的消息转发的
* @param request
* @return
*/
@PostMapping(value = "prod/wechat/handler")
public String processMsg(HttpServletRequest request) {
// 调用核心服务类接收处理请求
return weChatService.processRequest(request);
}
}
微信请求服务类
package com.wechat.core.service;
import javax.servlet.http.HttpServletRequest;
/**
* 微信处理服务类
*/
public interface WeChatService {
/**
* 处理微信消息
* @param request
*/
String processRequest(HttpServletRequest request);
}
实现类
package com.wechat.core.service.impl;
import com.wechat.core.common.WeChatContant;
import com.wechat.core.model.ArticleItem;
import com.wechat.core.service.UserInfoService;
import com.wechat.core.service.WeChatService;
import com.wechat.core.util.WeChatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author hgb
* @date 2019/1/26
* Email xhy18650@sina.com
*/
@Service
public class WeChatServiceImpl implements WeChatService {
private Logger logger = LoggerFactory.getLogger(WeChatServiceImpl.class);
@Autowired
private UserInfoService userInfoService;
@Override
public String processRequest(HttpServletRequest request) {
// xml格式的消息数据
String respXml = null;
// 默认返回的文本消息内容
String respContent;
try {
// 调用parseXml方法解析请求消息
Map<String, String> requestMap = WeChatUtil.parseXml(request);
// 消息类型
String msgType = (String) requestMap.get(WeChatContant.MsgType);
String mes = null;
// 文本消息
if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_TEXT)) {
mes = requestMap.get(WeChatContant.Content).toString();
if (mes != null && mes.length() < 2) {
List<ArticleItem> items = new ArrayList<>();
ArticleItem item = null;
item = new ArticleItem();
item.setTitle("小游戏");
item.setDescription("小游戏");
item.setPicUrl("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3257434623,3478200329&fm=26&gp=0.jpg");
item.setUrl("https://mp.weixin.qq.com/s/4P2e67VidADWR63V8Jm61w");
items.add(item);
item = new ArticleItem();
item.setTitle("百度");
item.setDescription("百度一下");
item.setPicUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1505100912368&di=69c2ba796aa2afd9a4608e213bf695fb&imgtype=0&src=http%3A%2F%2Ftx.haiqq.com%2Fuploads%2Fallimg%2F170510%2F0634355517-9.jpg");
item.setUrl("http://www.baidu.com");
items.add(item);
respXml = WeChatUtil.sendArticleMsg(requestMap, items);
}
}
// 图片消息
else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_IMAGE)) {
respContent = "您发送的是图片消息!";
respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
}
// 语音消息
else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_VOICE)) {
respContent = "您发送的是语音消息!";
respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
}
// 视频消息
else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_VIDEO)) {
respContent = "您发送的是视频消息!";
respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
}
// 地理位置消息
else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_LOCATION)) {
respContent = "您发送的是地理位置消息!";
respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
}
// 链接消息
else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_LINK)) {
respContent = "您发送的是链接消息!";
respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
}
// 事件推送
else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_EVENT)) {
// 事件类型
String eventType = (String) requestMap.get(WeChatContant.Event);
// 关注
if (eventType.equals(WeChatContant.EVENT_TYPE_SUBSCRIBE)) {
respContent = "谢谢您的关注!";
respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
}
// 取消关注
else if (eventType.equals(WeChatContant.EVENT_TYPE_UNSUBSCRIBE)) {
// TODO 取消订阅后用户不会再收到公众账号发送的消息,因此不需要回复
}
// 扫描带参数二维码
else if (eventType.equals(WeChatContant.EVENT_TYPE_SCAN)) {
// TODO 处理扫描带参数二维码事件
}
// 上报地理位置
else if (eventType.equals(WeChatContant.EVENT_TYPE_LOCATION)) {
// TODO 处理上报地理位置事件
}
// 自定义菜单
else if (eventType.equals(WeChatContant.EVENT_TYPE_CLICK)) {
// TODO 处理菜单点击事件
String eventKey = requestMap.get(WeChatContant.EVENT_KEY);
if("V1001_TODAY_MUSIC".equals(eventKey)){
//每日一签{向用户推送用户个人信息}
Map<String, Object> userInfo = userInfoService.getUserInfo(requestMap.get(WeChatContant.FromUserName));
logger.debug(userInfo.toString());
String nickname = userInfo.get("nickname").toString();
String city = userInfo.get("city").toString();
String province = userInfo.get("province").toString();
String country = userInfo.get("country").toString();
String headimgurl = userInfo.get("headimgurl").toString();
List<ArticleItem> items = new ArrayList<>();
ArticleItem item = new ArticleItem();
item.setTitle(nickname+"签到");
item.setDescription("昵称:" + nickname + " 地址:" + country + " " + province + " " + city);
item.setPicUrl(headimgurl);
item.setUrl("http://www.baidu.com");
items.add(item);
respXml = WeChatUtil.sendArticleMsg(requestMap, items);
}
else if("V1001_OUT".equals(eventKey)){
//关于我们
respXml = WeChatUtil.sendTextMsg(requestMap, "关于我们");
}
else if("V1001_MSG".equals(eventKey)){
//留言
respXml = WeChatUtil.sendTextMsg(requestMap, "留言");
}
}
}
mes = mes == null ? "" : mes;
if (respXml == null){
respXml = WeChatUtil.sendTextMsg(requestMap, mes);
}
logger.debug(respXml);
return respXml;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
如需项目源码,请访问 https://gitee.com/xhy18650/wechat-core.git
欢迎fork me