直接上代码
constant.java为基础常量类
import com.douples.common.util.CommonUtil;
import com.douples.framework.util.PageData;
import java.text.SimpleDateFormat;
/**
* 常量
*
* @author lucky
* @date 2019-02-12
*/
public class Constant {
public static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMddHHmmsss");
public static final String SUCCESS = "10000";//请求处理成功
public static final String FAIL = "10001";//请求处理失败
//微信部分的常量
PageData pd = new PageData();
//服务器域名
public static final String DOMAIN = "http://88hyze.natappfree.cc";
//public static final String DOMAIN = CommonUtil.getConfig("common","WEIXIN_DOMAIN");
//微信配置的常量
//微信的消息类型
public static final String TEXT_MESSAGE = "text";
public static final String NEWS_MESSAGE = "news";
//用户回复的特定消息
public static final String WX_KEY_WORD = CommonUtil.getConfig("common","WEIXIN_WX_KEY_WORD");
//public static final String WX_KEY_WORD = "ceshi";
public static final String TOKEN="weChat";
public static final String APP_ID = "111122222333333";
public static final String APP_SECRET = "6666uy7jkop778889";
//获取公众号的全局唯一接口调用凭据的接口
public static final String GLOBAL_ACCESS_TOKEN="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
//创建自定义菜单的接口
public static final String MENU = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
//微信授权模块
//1.微信网页授权接口
public static final String AUTH = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
//2.通过code换取网页授权access_token
public static final String GET_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
//3,刷新access_token(跟全局的不一样),如果有需要的话
public static final String REFRESH_TOKEN = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
//4.拉取用户信息(需scope为 snsapi_userinfo)
public static final String GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
//微信jdk jsApi的token
public static final String JS_API_TICKET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
//微信消息模块
//数据库存储的模板id
public static final String Template_Id = CommonUtil.getConfig("common","WEIXIN_Template_Id");
//public static final String Template_Id ="--hiFOOuQC207RPmYYUEmk592GM4_ihtaEM1-Vj1Lj8";
//获取模板消息--get方式,测试号获取不到
public static final String GET_TEMPLATE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=ACCESS_TOKEN";
//发送模板消息---post方式发送有
public static final String SEND_TEMPLATE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
//微信登录模块
public static final String WX_LOGIN_SESSION = "wxSessionUser";
}
WXEntry.java接口调用类
import com.alibaba.fastjson.JSONObject;
import com.douples.common.annotation.IgnoreAuth;
import com.douples.common.constant.Constant;
import com.douples.common.util.weChat.OAuthUtil;
import com.douples.common.util.weChat.ResponseProcessUtil;
import com.douples.common.util.weChat.SignUtil;
import com.douples.framework.core.impl.BaseController;
import com.douples.framework.util.PageData;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
@Controller
@RequestMapping(value = "weChat/wxEntry")
public class WXEntry extends BaseController {
/**
* 接收微信端消息的入口
* @param request
* @param response
*/
@RequestMapping(value = "/main", method = { RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public void getToken(HttpServletRequest request,
HttpServletResponse response) throws Exception {
boolean isGet = request.getMethod().toLowerCase().equals("get");
boolean isPost = request.getMethod().toLowerCase().equals("post");
PrintWriter print;
if (isGet) {//接收get方法信息
// 微信加密签名
String signature = request.getParameter("signature");
// 时间戳
String timestamp = request.getParameter("timestamp");
// 随机数
String nonce = request.getParameter("nonce");
// 随机字符串
String echostr = request.getParameter("echostr");
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (signature != null
&& SignUtil.checkSignature(signature, timestamp, nonce)) {
try {
print = response.getWriter();
print.write(echostr);
print.close();
} catch (IOException e) {
e.printStackTrace();
}
}
isGet = false;
}
if(isPost) {//接收post信息
//将请求、相应类型都设置为utf-8防止出现乱码
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
PageData imgMsg =null;
//PageData imgMsg = wxFacade.findImgMsg();
System.out.println("res测试1----------------");
String res = ResponseProcessUtil.processRequest(request,imgMsg);
System.out.println("res测试1----------------"+res);
PrintWriter writer = response.getWriter();
writer.print(res);
writer.close();
writer = null;
isPost = false;
}
}
/**
* 网页授权入口,以snsapi_userinfo为scope发起的网页授权,能够获取能获取的所有信息
* @param request
* @param response
* @throws IOException
*/
@IgnoreAuth
@RequestMapping(value = "/webAuthorize", method = { RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public void webAuthorize(HttpServletRequest request,HttpServletResponse response) throws IOException {
PageData pageData = getPageData();
String redicUrl =Constant.DOMAIN+"/weChat/wxEntry/webJumpPage?requestURI="+pageData.get("requestURI").toString();
String appId = Constant.APP_ID;
String scope = "snsapi_userinfo";
String state = "1";//非必需
//redicUURLE
redicUrl = URLEncoder.encode(redicUrl,"UTF-8");
System.out.println("这个是auth---1"+Constant.AUTH);
String url = Constant.AUTH.replace("APPID", appId)
.replace("REDIRECT_URI", redicUrl)
.replace("SCOPE", scope)
.replace("STATE", state);
response.sendRedirect(url);
}
/**
* 通过获取到code来查询登录的用户信息
*/
@IgnoreAuth
@RequestMapping(value = "/webJumpPage", method = { RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public void webAuthorizes(HttpServletRequest request,HttpServletResponse response,String code) throws IOException {
PageData pageData = getPageData();
JSONObject authAccessToken = OAuthUtil.getAuthAccessToken(code);
String openid = (String) authAccessToken.get("openid");
String unionid = (String) authAccessToken.get("unionid");
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
session.setAttribute("openId", openid);
//session.setAttribute("unionId", unionid);
session.setAttribute("unionId", "123456");
response.getWriter().print("<script>top.location='"+Constant.DOMAIN+pageData.get("requestURI").toString()+ "';</script>");
}
}
ResponseProcessUtil.java 类
import com.douples.framework.util.PageData;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ResponseProcessUtil {
//获取返回的微信消息
public static String processRequest(HttpServletRequest request, PageData pd){
//返回的消息
String respMessage = null;
try {
//将xml解析成map
Map map = ResponseProcessUtil.parseXml(request);
// 发送方帐号(open_id)
String fromUserName = map.get("FromUserName").toString();
// 公众帐号
String toUserName = map.get("ToUserName").toString();
// 消息类型
String msgType = map.get("MsgType").toString();
//消息内容
String content = map.get("Content").toString();
System.out.println("content值---------"+content);
if(content!=null){
//特定回复
}
} catch (Exception e) {
e.printStackTrace();
}
return respMessage;
}
/**
* 拓展xstream 将每个节点都加上cdata块
*/
private static XStream xStream = new XStream(new XppDriver(){
@Override
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out){
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
public void startNode(String name, Class clazz){
super.startNode(name,clazz);
}
public void writeText(QuickWriter writer, String text){
if (cdata){
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
}
}
};
}
});
//解析微信发送过来的xml信息
public static Map parseXml(HttpServletRequest request) throws Exception{
Map res = new HashMap();
InputStream inputStream = request.getInputStream();
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
Element root = document.getRootElement();
List<Element> elements = root.elements();
for (Element e:elements) {
res.put(e.getName(),e.getText());
}
inputStream.close();
inputStream = null;
return res;
}
}
SignUtil.java类
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import com.douples.common.constant.Constant;
public class SignUtil {
//与接口配置的token保持一致
private static String token = Constant.TOKEN;
/**
* 验证签名
* @param signature
* @param timestamp
* @param nonce
*
*/
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[] { token, timestamp, nonce };
// 将token、timestamp、nonce三个参数进行字典序排序
Arrays.sort(arr);
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
// 将三个参数字符串拼接成一个字符串进行sha1加密
byte[] digest = md.digest(content.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
content = null;
// 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}
/**
* 将字节数组转换为十六进制字符串
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = 0; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* 将字节转换为十六进制字符串
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
}
OAuthUtil为基础实现类
import java.net.ConnectException;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
import com.douples.common.constant.Constant;
/**
* 授权登陆
* @author lucky
*
*/
public class OAuthUtil {
private static Logger logger = Logger.getLogger(OAuthUtil.class);
/**
* 获取网页授权的accessToken
* @param code
* @return
* @throws ConnectException
*/
public static JSONObject getAuthAccessToken(String code) throws ConnectException {
//获取token的url
System.out.println("这个是GET_TOKEN---1"+Constant.GET_TOKEN);
String url = Constant.GET_TOKEN.replace("APPID", Constant.APP_ID)
.replace("SECRET", Constant.APP_SECRET)
.replace("CODE", code);
JSONObject res = HttpUtil.httpsConnect(url, "GET", null);
return res;
}
/**
* 获取微信用户信息详情
* @param
* @return
* @throws ConnectException
*/
public static JSONObject getWxUserInfo(String token, String openid) throws ConnectException {
//获取信息的url
System.out.println("这个是GET_USER_INFO---1"+Constant.GET_USER_INFO);
String userInfoUrl = Constant.GET_USER_INFO.replace("ACCESS_TOKEN", token)
.replace("OPENID", openid);
JSONObject info = HttpUtil.httpsConnect(userInfoUrl, "GET", null);
return info;
}
}
WeChatLoginAuthInterceptor.java为微信接口拦截器类,所有路径访问都需要经过此拦截器进行拦截
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class WeChatLoginAuthInterceptor extends HandlerInterceptorAdapter{
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
HttpSession sesssion = request.getSession();
String requestURI = request.getRequestURI();
if(sesssion.getAttribute("unionId") == null){
response.getWriter().print("<script>top.location='/weChat/wxEntry/webAuthorize?requestURI="+requestURI+ "';</script>");
return false;
}
return true;
}
}
在 applicationContext-mvc.xml配置拦截器
<mvc:interceptor>
<mvc:mapping path="/weChat/**/**"/>
<mvc:exclude-mapping path="/weChat/wxEntry/**"/>
<bean class="com.douples.framework.interceptor.WeChatLoginAuthInterceptor">
</bean>
</mvc:interceptor>