微信公众平台java版本token验证
以下是token.jsp? 本人项目中使用的方法,仅供参考,方便自己后期使用
?
<%@page import="java.util.Date"%>
<%@page import="org.dom4j.Element"%>
<%@page import="org.dom4j.DocumentHelper"%>
<%@page import="org.dom4j.Document"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.io.Reader"%>
<%@page import="java.security.MessageDigest"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="java.util.Arrays"%>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@page import="java.util.*"%>
<%@page import="com.cjt.base.util.comm.SysOptionsValues"%>
<%@page import="com.sides.vms.web.violation.service.MessageResolveBiz"%>
<%@page import="com.sides.vms.web.violation.service.ViolationInfoBiz"%>
<%@page import="com.sides.vms.web.violation.bean.RequsetBean"%>
<%@page import="com.sides.vms.web.violation.action.ViolationAction"%>
<%@page import="com.sides.vms.web.violation.bean.Violation"%>
<%@page import="com.sides.vms.web.violation.MainConfig"%>
<%
?String path = request.getContextPath();
?
%>
<%
?//WeiXinHandler为内部类不能使用非final类型的对象
?final String TOKEN="weixin";
?final HttpServletRequest final_request=request;
?final HttpServletResponse final_response=response;
?final HttpSession final_session =session;
?final ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
?final MessageResolveBiz msgResolveBiz = (MessageResolveBiz)context.getBean("msgResolveBiz");
?final ViolationInfoBiz violationInfoBiz = (ViolationInfoBiz)context.getBean("violationInfoBiz");?
?final String localIp = MainConfig.LOCALIP;
%>
<%
class WeiXinHandler{
?public void valid(){
??
??String echostr=final_request.getParameter("echostr");
??if(null==echostr||echostr.isEmpty()){
???try{
????responseMsg();
???}catch(Exception ex){
????ex.printStackTrace();
???}
??}else{
???if(this.checkSignature()){
????this.print(echostr);
???}else{
????this.print("error");????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
???}
??}
?}
?//自动回复内容
?public void responseMsg()throws Exception{
??String postStr=null;
?
??postStr=this.readStreamParameter(final_request.getInputStream());
??System.out.println("22:"+postStr);
??//存入用户信息及消息及验证用户
??String result = msgResolveBiz.insertMseeage(msgResolveBiz.pageContent2Bean(postStr));
??if("invalidUser".equals(result)){
???//非法用户
???final_response.setHeader("REFRESH","5;URL=userManager/login.jsp");
??}
??if (null!=postStr&&!postStr.isEmpty()){
???
???Document document=null;
???try{
????document = DocumentHelper.parseText(postStr);
???}catch(Exception e){
????e.printStackTrace();
???}
???if(null==document){
????this.print("");
????return;
???}
???
???Element root=document.getRootElement();
??????????? String fromUsername = root.elementText("FromUserName");
??????????? String toUsername = root.elementText("ToUserName");
??????????? String keyword = root.elementTextTrim("Content"); //消息内容
??????????? String msgtype =root.elementTextTrim("MsgType"); //消息类型
??????????? String event =root.elementTextTrim("Event"); //事件推送? click 表示自定义菜单点击事件
??????????? String eventKey =root.elementTextTrim("EventKey"); //自定义菜单接口中KEY值对应
??????????? String location_x =root.elementTextTrim("Location_X"); //地理位置纬度
??????????? String location_y =root.elementTextTrim("Location_Y"); //地理位置经度
??????????? String scale = root.elementTextTrim("Scale");//地图缩放大小
??????????? String label = root.elementTextTrim("Label");//地理位置信息
??????????? String time = new Date().getTime()+"";
??????????? System.out.println("keyword:? "+keyword);
??????????? System.out.println("msgtype:? "+msgtype);
??????????? //文本消息
??????????? String textTpl = "<xml>"+
??????"<ToUserName><![CDATA[%1$s]]></ToUserName>"+
??????"<FromUserName><![CDATA[%2$s]]></FromUserName>"+
??????"<CreateTime>%3$s</CreateTime>"+
??????"<MsgType><![CDATA[%4$s]]></MsgType>"+
??????"<Content><![CDATA[%5$s]]></Content>"+
??????"<FuncFlag>0</FuncFlag>"+
??????"</xml>";????
???//图文消息?
???String textTpl2 = "<xml>"+
?????"<ToUserName><![CDATA["+fromUsername+"]]></ToUserName>"+
?????"<FromUserName><![CDATA["+toUsername+"]]></FromUserName>"+
?????"<CreateTime>"+new Date().getTime()+"</CreateTime>"+
?????"<MsgType><![CDATA[news]]></MsgType>"+
?????"<Content><![CDATA[]]></Content>"+
?????"<ArticleCount>2</ArticleCount>"+
?????"<Articles>"+
?????"<item>"+
?????"<Title><![CDATA[%1$s]]></Title>"+
?????"<Description><![CDATA[]]></Description>"+
?????"<PicUrl><![CDATA[%2$s]]></PicUrl>"+
?????"<Url><![CDATA[%3$s]]></Url>"+
?????"</item>"+
?????"<item>"+
?????"<Title><![CDATA[%4$s]]></Title>"+
?????"<Description><![CDATA[]]></Description>"+
?????"<PicUrl><![CDATA[]]></PicUrl>"+
?????"<Url><![CDATA[%5$s]]></Url>"+
?????"</item>"+
?????"</Articles>"+
?????"<FuncFlag>0</FuncFlag>"+
?????"</xml>";?
??}
?}
?
?//微信接口验证
?public boolean checkSignature(){
??String signature = final_request.getParameter("signature");
??????? String timestamp = final_request.getParameter("timestamp");
??????? String nonce = final_request.getParameter("nonce");
??????? String token=TOKEN;
??????? String[] tmpArr={token,timestamp,nonce};
??????? Arrays.sort(tmpArr);
??????? String tmpStr=this.ArrayToString(tmpArr);
??????? tmpStr=this.SHA1Encode(tmpStr);
??????? if(tmpStr.equalsIgnoreCase(signature)){
???return true;
??}else{
???return false;
??}
?}
?//向请求端发送返回数据
?public void print(String content){
??try{
???final_response.getWriter().print(content);
???final_response.getWriter().flush();
???final_response.getWriter().close();
??}catch(Exception e){
???
??}
?}
?//数组转字符串
?public String ArrayToString(String [] arr){
??StringBuffer bf = new StringBuffer();
??for(int i = 0; i < arr.length; i++){
?? bf.append(arr[i]);
??}
??return bf.toString();
?}
?//sha1加密
?public String SHA1Encode(String sourceString) {
??String resultString = null;
??try {
???? resultString = new String(sourceString);
???? MessageDigest md = MessageDigest.getInstance("SHA-1");
???? resultString = byte2hexString(md.digest(resultString.getBytes()));
??} catch (Exception ex) {
??}
??return resultString;
?}
?public final String byte2hexString(byte[] bytes) {
??StringBuffer buf = new StringBuffer(bytes.length * 2);
??for (int i = 0; i < bytes.length; i++) {
???if (((int) bytes[i] & 0xff) < 0x10) {
????? ?buf.append("0");
???? ?}
???buf.append(Long.toString((int) bytes[i] & 0xff, 16));
??}
??return buf.toString().toUpperCase();
?}
?//从输入流读取post参数
?public String readStreamParameter(ServletInputStream in){
??StringBuilder buffer = new StringBuilder();
??BufferedReader reader=null;
??try{
???reader = new BufferedReader(new InputStreamReader(in));
???String line=null;
???while((line = reader.readLine())!=null){
????buffer.append(line);
???????? }
??}catch(Exception e){
???e.printStackTrace();
??}finally{
???if(null!=reader){
????try {
?????reader.close();
????} catch (IOException e) {
?????e.printStackTrace();
????}
???}
??}
??return buffer.toString();
?}
}
%>
<%
?WeiXinHandler handler=new WeiXinHandler();
?handler.valid();
%>