基於微信公眾平臺的第三方介面接入Java接發訊息
阿新 • • 發佈:2019-01-11
玩過微信公眾號的都清楚,微信公眾號的專案欄是可以在裡面生成的,今天就來說一下使用Java接入微信平臺提供的第三方介面。
開啟微信公眾平臺,開啟開發者模式,裡面有一個介入指南,下面有三款:1.填寫伺服器配置。2.驗證伺服器地址的有效性。3依據介面文件實現業務邏輯。
1.填寫伺服器配置:截圖如下(我的已經驗證過了)
其中URL為http://rocky1996.tunnel.echomod.cn/weixin02/weixin.do,前面是用ngrok做的內網穿透的一個外鏈,後面是自己寫的一個介面,
令牌Token,是我隨機寫的,是我們實驗室的名稱,他的作用就是認證的時候生成一個簽名
EncodingAESKey,隨機生成的一個字串,用作訊息加密,相當於一個金鑰
2.驗證伺服器地址的有效性(驗證的時候有四個引數,分別是signature,timestamp,nonce,echostr)
signature:微信加密簽名,signature結合了開發者填寫的token引數和請求中的timestamp引數,nonce引數
timestamp:時間戳
nonce:隨機數
echostr:隨機字串
微信伺服器會發一個get請求到你填寫的伺服器上面,傳遞這四個引數。
3.據介面文件實現業務邏輯。
這是普通訊息需要的幾個引數,後面還有圖片訊息,語音訊息等,都有官方的API文件。需要之一的是傳遞過來的訊息是以xml的形式,所以需要解析
一下是所有的程式碼:
package com.acat.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.acat.po.TextMessage; import com.acat.util.CheckUtil; import com.acat.util.MessageUtil; import com.acat.util.getNowTime; public class WeixinServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String signature = request.getParameter("signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); String echostr = request.getParameter("echostr"); PrintWriter out = response.getWriter(); if(CheckUtil.checkSignature(signature, timestamp, nonce)){ out.println(echostr); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { Map<String, String> map = MessageUtil.xmlToMap(request); String fromUserName = map.get("FromUserName"); String toUserName = map.get("ToUserName"); String msgType = map.get("MsgType"); String content = map.get("Content"); String message = null; if("text".equals(msgType)){ TextMessage text = new TextMessage(); text.setFromUserName(toUserName); text.setToUserName(toUserName); text.setMsgType("text"); text.setCreateTime(getNowTime.getTime()); text.setContent("您傳送的訊息是:"+content); message = MessageUtil.textMessageToXml(text); System.out.println(message); } out.print(message); } catch (Exception e) { e.printStackTrace(); }finally { out.close(); } } }
package com.acat.util;
import java.security.MessageDigest;
import java.util.Arrays;
public class CheckUtil {
private static final String token = "acat";
public static boolean checkSignature(String signature,String timestamp,String nonce){
String[] arr = new String[]{token,timestamp,nonce};
//排序
Arrays.sort(arr);
//生成字串
StringBuffer content = new StringBuffer();
for(int i=0;i<arr.length;i++){
content.append(arr[i]);
}
//sha1加密
String temp = getSha1(content.toString());
return temp.equals(signature);
}
public static String getSha1(String str){
if(str==null || str.length()==0){
return null;
}
char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
try{
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j*2];
int k = 0;
for(int i=0;i<j;i++){
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
}catch(Exception e){
return null;
}
}
}
package com.acat.util; import java.text.SimpleDateFormat; import java.util.Date; public class getNowTime { public static String getTime() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String value = sdf.format(new Date()); return value; } }
package com.acat.po;
public class TextMessage {
private String ToUserName;
private String FromUserName;
private String CreateTime;
private String MsgType;
private String Content;
private String MsgId;
public String getToUserName() {
return ToUserName;
}
public String getFromUserName() {
return FromUserName;
}
public String getMsgType() {
return MsgType;
}
public String getContent() {
return Content;
}
public String getMsgId() {
return MsgId;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public String getCreateTime() {
return CreateTime;
}
public void setCreateTime(String createTime) {
CreateTime = createTime;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
public void setContent(String content) {
Content = content;
}
public void setMsgId(String msgId) {
MsgId = msgId;
}
}
package com.acat.util;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.acat.po.TextMessage;
import com.thoughtworks.xstream.XStream;
public class MessageUtil {
/**
* xml轉成集合
* @param request
* @return
* @throws Exception
*/
public static Map<String, String> xmlToMap(HttpServletRequest request) throws Exception {
Map<String, String> map = new HashMap<String, String>();
SAXReader reader = new SAXReader();
InputStream ins = request.getInputStream();
Document doc = reader.read(ins);
Element root = doc.getRootElement();
List<Element> list = root.elements();
for(Element e:list){
map.put(e.getName(), e.getText());
}
ins.close();
return map;
}
/**
* 將文字訊息轉為xml
* @return
*/
public static String textMessageToXml(TextMessage textMessage){
XStream stream = new XStream();
stream.alias("xml", textMessage.getClass());
return stream.toXML(textMessage);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>weixin02</display-name>
<servlet>
<servlet-name>WeixinServlet</servlet-name>
<servlet-class>com.acat.servlet.WeixinServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WeixinServlet</servlet-name>
<url-pattern>/weixin.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
示例如下: