JAVA微信公眾號輸入選擇回覆文字或者圖文,列輸入1回覆一圖文或者文字
先寫一個servlet介面,傳入選擇1,2....
package com.wx.service;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.bochiot.amain.HttpGyRentUserService;
import com.bochiot.amain.StringConst;
import com.bochiot.znys.config.ENUM_BOZHI_RESULT;
import com.project.util.L;
import com.wx.message.resp.Article;
import com.wx.util.MessageUtil;
import com.wx.util.WeixinMessageUtil;
import net.sf.json.JSONObject;
/**
* 處理微信的操作
*
*
* @author Administrator
*
*/
public class WeixinService {
public static String TAG = "WeixinService";
/**
* 處理微信發來的請求
*
* @param request
* @return
* @throws Exception
*/
public static String processRequest(HttpServletRequest request) throws Exception {
L.i(TAG, "processRequest "); // 預設返回的文字訊息內容
// xml請求解析
Map<String, String> requestMap = MessageUtil.parseXml(request);
// 傳送方帳號(open_id)
String fromUserName = requestMap.get("FromUserName");
// 公眾帳號
String toUserName = requestMap.get("ToUserName");
// 訊息型別
String msgType = requestMap.get("MsgType");
try {
L.i(TAG, "FromUserName: " + fromUserName + " toUserName: " + toUserName + " msgType: " + msgType);
// 文字訊息
if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
String content = requestMap.get("Content").trim();
if(Integer.valueOf(content)==1) {
// return doTextMessage(fromUserName, toUserName, content);
return WeixinMessageUtil.createTextMessage(fromUserName, toUserName,
StringConst.WEIXIN_TEXT_BLACKLIST_DEFALUT);
}else if(Integer.valueOf(content)==2) {
return WeixinMessageUtil.createTextMessage(fromUserName, toUserName,
StringConst.WEIXIN_NEWS_QUERY_ORDER_TITLE);
}else if(Integer.valueOf(content)==3) {
Article article=WeixinMessageUtil.createArticle("鉑智科技有限公司","鉑智宣傳視訊","http://nhbtek.com/bzser/assets/images/logo.png","http://nhbtek.com/bzser/assets/images/videobochiot.mp4");
List<Article> list=WeixinMessageUtil.createArticleList(article);
return WeixinMessageUtil.createNewsMessage(fromUserName, toUserName, list);
}
}
// 圖片訊息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
return WeixinMessageUtil.createTextMessage(fromUserName, toUserName,
StringConst.WEIXIN_TEXT_IMAGE_DEFALUT);
}
// 地理位置訊息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
return WeixinMessageUtil.createTextMessage(fromUserName, toUserName,
StringConst.WEIXIN_TEXT_LOCATION_DEFALUT);
}
// 連結訊息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
return WeixinMessageUtil.createTextMessage(fromUserName, toUserName,
StringConst.WEIXIN_TEXT_LINK_DEFALUT);
}
// 音訊訊息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
return WeixinMessageUtil.createTextMessage(fromUserName, toUserName,
StringConst.WEIXIN_TEXT_VOICE_DEFALUT);
}
// 事件推送
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
// 事件型別
String eventType = requestMap.get("Event");
System.out.println(" eventType = "+ eventType);
for(String s:requestMap.keySet()){
System.out.println( s + ":" + requestMap.get(s));
}
System.out.println(" KeyStandard = "+ requestMap.get("KeyStandard"));
System.out.println(" KeyStr = "+ requestMap.get("KeyStr"));
System.out.println(" ExtInfo = "+ requestMap.get("ExtInfo"));
System.out.println(" EventKey = "+ requestMap.get("EventKey"));
// 訂閱 關注
if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
//新增 微信資訊
return WeixinMessageUtil.createTextMessage(fromUserName, toUserName,
StringConst.WEIXIN_TEXT_EVENT_SUBSCRIBE);
}
// 取消訂閱
else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
// TODO 取消訂閱後使用者再收不到公眾號傳送的訊息,因此不需要回復訊息
}
// 掃描 事件 我們的前臺業務申請和微信開門都是通過SCAN事件完成的
else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN2)) {
String eventKey = requestMap.get("EventKey");
System.out.println("掃描 EventKey"+ eventKey);
if(eventKey==null){
// eventKey = "123456790"; //測試 1001
}else{
return doScan(fromUserName, toUserName, eventKey);
}
} else if (eventType.equals(MessageUtil.EVENT_TYPE_Shake)) {
// 搖一搖
}
// 自定義選單點選事件
else if (eventType.equalsIgnoreCase(MessageUtil.EVENT_TYPE_CLICK)) {
String eventKey = requestMap.get("EventKey");
return doClick(fromUserName, toUserName, eventKey);
}
}
} catch (Exception e) {
return WeixinMessageUtil.createTextMessage(fromUserName, toUserName, StringConst.WEIXIN_TEXT_ERR_DEFALUT);
}
// 回覆文字
return WeixinMessageUtil.createTextMessage(fromUserName, toUserName, StringConst.WEIXIN_TEXT_DEFAULT);
}//..
//掃描事件
public static String doScan(String fromUserName, String toUserName, String eventKey) throws IOException {
L.i(TAG, "zc scan eventKey="+ eventKey);
//123456790
Integer iEventKey = 0;
try {
iEventKey = Integer.valueOf(eventKey);
} catch (Exception e) {
iEventKey = 10;
}
String response = "";
long startTime = System.currentTimeMillis();
//掃一掃開門
JSONObject jsonObject = HttpGyRentUserService.sendCmd_OPEN_SCAN( eventKey, fromUserName);
ENUM_BOZHI_RESULT respCode = ENUM_BOZHI_RESULT.getCODE(jsonObject.getInt("code"));
if (respCode == ENUM_BOZHI_RESULT.MSG_SUCCESS) {
JSONObject data = jsonObject.getJSONObject("data");
int room_number = 0;
try {
room_number = data.getInt("room_number");
} catch (Exception e) {
e.printStackTrace();
}
response = String.format(StringConst.WEIXIN_TEXT_OPENDOOR_SCAN_SUCCESSED, room_number);
} else {
response = String.format(StringConst.WEIXIN_TEXT_OPENDOOR_SCAN_FAILED, eventKey,
jsonObject.get("message") );
}
L.i(TAG, "saomiao opendoor use time : " + (System.currentTimeMillis() - startTime) + " ms");
/*
// 微信開門業務申請的scene_id是由32位的int組成,高16位是房間號,低16位是手機的CRC16值,由臨時二維碼生成的。
if (iEventKey > 100000) {
int iRoomNumber = 0;
iRoomNumber = iEventKey / 65536;
ENUM_BOZHI_RESULT respCode = bindRoom(iEventKey, fromUserName);
if (respCode == ENUM_BOZHI_RESULT.MSG_SUCCESS) {
response = String.format(StringConst.WEIXIN_TEXT_BINDROOM_SCAN_SUCCESSED, iRoomNumber);
} else {
response = String.format(StringConst.WEIXIN_TEXT_BINDROOM_SCAN_FAIL, iRoomNumber,
ENUM_BOZHI_RESULT.getStatusString(respCode, "", ""));
}
}//..
// 微信開門動作的scene_id是四位長度的數字,格式如下:XXXX,是永久二維碼生成的。
else if (iEventKey <= 100000) {
if (iEventKey == 3) {
// 關注
response = "歡迎回來~";
} else if (iEventKey == 1) {
// 餐券管理員登記
MainConst.couponManagerOpenID = fromUserName;
MainConst.couponManager_KFSendMSG_Num = 0;
response = StringConst.WEIXIN_TEXT_COUPON_MANAGER_SUCCESSED;
} else if (iEventKey == 2) {// 餐券掃一掃
response = useCoupon(fromUserName);
//開門
} else {
long startTime = System.currentTimeMillis();
// JSONObject jsonObject = HttpBC_ZNYS_Service.sendCmd_OPEN_SCAN( iEventKey, fromUserName);
JSONObject jsonObject = HttpBC_ZNYS_Service.sendCmd_OPEN_SCAN( eventKey, fromUserName);
int room_number = 0;
try {
room_number = jsonObject.getInt("room_number");
} catch (Exception e) {
// TODO: handle exception
}
ENUM_BOZHI_RESULT respCode = ENUM_BOZHI_RESULT.getCODE(jsonObject.getInt("code"));
;
if (respCode == ENUM_BOZHI_RESULT.MSG_SUCCESS
|| respCode == ENUM_BOZHI_RESULT.MSG_ERR_NETWORK_TIMEOUT) {
response = String.format(StringConst.WEIXIN_TEXT_OPENDOOR_SCAN_SUCCESSED, room_number);
} else {
response = String.format(StringConst.WEIXIN_TEXT_OPENDOOR_SCAN_FAILED, room_number,
ENUM_BOZHI_RESULT.getStatusString(respCode, "", ""));
}
L.i(TAG, "saomiao opendoor use time : " + (System.currentTimeMillis() - startTime) + " ms");
}
} else {
response = StringConst.WEIXIN_TEXT_EVENT_SCAN_DEFALUT;
}
*/
return WeixinMessageUtil.createTextMessage(fromUserName, toUserName, response);
}
public static String doClick(String fromUserName, String toUserName, String eventKey) throws IOException {
L.i(TAG, "doClick "+ eventKey);
// 處理使用者選單開門命令
String response = "";
if (eventKey.equals("35")) { //一鍵開門
System.out.println("點選了 一鍵開門 fromUserName=" + fromUserName);
// JSONObject jsonObject = HttpGyRentUserService.sendCmd_OPEN_ONE( fromUserName);
// ENUM_BOZHI_RESULT respCode = ENUM_BOZHI_RESULT.getCODE(jsonObject.getInt("code"));
//
// if (respCode == ENUM_BOZHI_RESULT.MSG_SUCCESS ) {
// int roomNo = jsonObject.getInt("data");
// System.out.println("一鍵開門成功 roomNo" + roomNo);
// response = String.format(StringConst.WEIXIN_TEXT_OPENDOOR_TEXT_SUCCESSED, roomNo) ;
//
// } else {
// String errorMsg = jsonObject.getString("message");
// response = String.format(StringConst.WEIXIN_TEXT_OPENDOOR_MENU_FAILED, errorMsg);
// }
} else if (eventKey.equals("22")) {
response = "謝謝你的支援,這是測試選單";
return response;
} else {
response = StringConst.WEIXIN_TEXT_EVENT_CLICK_DEFALUT;
}
return WeixinMessageUtil.createTextMessage(fromUserName, toUserName, response);
}
}//end
1.重點程式碼,傳入文字,我這邊用列舉的文字,和圖文自己定義
// 文字訊息
if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
String content = requestMap.get("Content").trim();
if(Integer.valueOf(content)==1) {
// return doTextMessage(fromUserName, toUserName, content);
return WeixinMessageUtil.createTextMessage(fromUserName, toUserName,
StringConst.WEIXIN_TEXT_BLACKLIST_DEFALUT);
}else if(Integer.valueOf(content)==2) {
return WeixinMessageUtil.createTextMessage(fromUserName, toUserName,
StringConst.WEIXIN_NEWS_QUERY_ORDER_TITLE);
}else if(Integer.valueOf(content)==3) {
Article article=WeixinMessageUtil.createArticle("鉑智科技有限公司","鉑智宣傳視訊","http://nhbtek.com/bzser/assets/images/logo.png","http://nhbtek.com/bzser/assets/images/videobochiot.mp4");
List<Article> list=WeixinMessageUtil.createArticleList(article);
return WeixinMessageUtil.createNewsMessage(fromUserName, toUserName, list);
呼叫的建立文字或者圖文的
package com.wx.util;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.wx.message.resp.Article;
import com.wx.message.resp.NewsMessage;
import com.wx.message.resp.TextMessage;
public class WeixinMessageUtil {
public static String createNewsMessage(String fromUserName, String toUserName, List<Article> articles) {
NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS );
newsMessage.setArticleCount(articles.size());
newsMessage.setArticles(articles);
return MessageUtil.newsMessageToXml(newsMessage);
}
public static List<Article> createArticleList(Article... articles) {
List<Article> articleList = new ArrayList<Article>();
for (Article article : articles) {
articleList.add(article);
}
return articleList;
}
public static Article createArticle(String title, String des, String picUrl, String url) {
Article article = new Article();
article.setTitle(title);
article.setDescription(des);
article.setPicUrl(picUrl);
article.setUrl(url);
return article;
}
public static Article createArticle1(String title, String des,String picUrl) {
Article article = new Article();
article.setTitle(title);
article.setDescription(des);
article.setPicUrl(picUrl);
return article;
}
public static String createTextMessage(String fromUserName,String toUserName,String respContent){
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(fromUserName);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(new Date().getTime());
textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
textMessage.setContent(respContent);
return MessageUtil.textMessageToXml(textMessage);
}
}
實體類
package com.wx.message.resp;
import java.util.List;
/**
* 文字訊息
*
* @author liufeng
* @date 2013-05-19
*/
public class NewsMessage extends BaseMessage {
// 圖文訊息個數,限制為10條以內
private int ArticleCount;
// 多條圖文訊息資訊,預設第一個item為大圖
private List<Article> Articles;
public int getArticleCount() {
return ArticleCount;
}
public void setArticleCount(int articleCount) {
ArticleCount = articleCount;
}
public List<Article> getArticles() {
return Articles;
}
public void setArticles(List<Article> articles) {
Articles = articles;
}
}
public class Article {
// 圖文訊息名稱
private String Title;
// 圖文訊息描述
private String Description;
// 圖片連結,支援JPG、PNG格式,較好的效果為大圖640*320,小圖80*80,限制圖片連結的域名需要與開發者填寫的基本資料中的Url一致
private String PicUrl;
// 點選圖文訊息跳轉連結
private String Url;
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return null == Description ? "" : Description;
}
public void setDescription(String description) {
Description = description;
}
public String getPicUrl() {
return null == PicUrl ? "" : PicUrl;
}
public void setPicUrl(String picUrl) {
PicUrl = picUrl;
}
public String getUrl() {
return null == Url ? "" : Url;
}
public void setUrl(String url) {
Url = url;
}
}
轉成xml
public class MessageUtil {
/**
* 返回訊息型別:文字
*/
public static final String RESP_MESSAGE_TYPE_TEXT = "text";
/**
* 返回訊息型別:音樂
*/
public static final String RESP_MESSAGE_TYPE_MUSIC = "music";
/**
* 返回訊息型別:圖文
*/
public static final String RESP_MESSAGE_TYPE_NEWS = "news";
/**
* 請求訊息型別:文字
*/
public static final String REQ_MESSAGE_TYPE_TEXT = "text";
/**
* 請求訊息型別:圖片
*/
public static final String REQ_MESSAGE_TYPE_IMAGE = "image";
/**
* 請求訊息型別:連結
*/
public static final String REQ_MESSAGE_TYPE_LINK = "link";
/**
* 請求訊息型別:地理位置
*/
public static final String REQ_MESSAGE_TYPE_LOCATION = "location";
/**
* 請求訊息型別:音訊
*/
public static final String REQ_MESSAGE_TYPE_VOICE = "voice";
/**
* 請求訊息型別:推送
*/
public static final String REQ_MESSAGE_TYPE_EVENT = "event";
/**
* 事件型別:subscribe(訂閱)
*/
public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";
/**
* 事件型別:unsubscribe(取消訂閱)
*/
public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";
/**
* 事件型別:CLICK(自定義選單點選事件)
*/
public static final String EVENT_TYPE_CLICK = "CLICK";
/**
* 事件型別:SCAN(掃一掃事件)
*/
public static final String EVENT_TYPE_SCAN = "SCAN";
public static final String EVENT_TYPE_SCAN2 = "scancode_push";
/**
* 事件型別:Shake(搖一搖事件)
*/
public static final String EVENT_TYPE_Shake = "ShakearoundUserShake";
/**
* 解析微信發來的請求(XML)
*
* @param request
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
// 將解析結果儲存在HashMap中
Map<String, String> map = new HashMap<String, String>();
// 從request中取得輸入流
InputStream inputStream = request.getInputStream();
// 讀取輸入流
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
// 得到xml根元素
Element root = document.getRootElement();
// 得到根元素的所有子節點
List<Element> elementList = root.elements();
// 遍歷所有子節點
for (Element e : elementList) {
map.put(e.getName(), e.getText());
}
// 釋放資源
inputStream.close();
inputStream = null;
return map;
}
/**
* 文字訊息物件轉換成xml
*
* @param textMessage 文字訊息物件
* @return xml
*/
public static String textMessageToXml(TextMessage textMessage) {
xstream.alias("xml", textMessage.getClass());
return xstream.toXML(textMessage);
}
/**
* 音樂訊息物件轉換成xml
*
* @param musicMessage 音樂訊息物件
* @return xml
*/
public static String musicMessageToXml(MusicMessage musicMessage) {
xstream.alias("xml", musicMessage.getClass());
return xstream.toXML(musicMessage);
}
/**
* 圖文訊息物件轉換成xml
*
* @param newsMessage 圖文訊息物件
* @return xml
*/
public static String newsMessageToXml(NewsMessage newsMessage) {
xstream.alias("xml", newsMessage.getClass());
xstream.alias("item", new Article().getClass());
return xstream.toXML(newsMessage);
}
/**
* 擴充套件xstream,使其支援CDATA塊
*
* @date 2013-05-19
*/
private static XStream xstream = new XStream(new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 對所有xml節點的轉換都增加CDATA標記
boolean cdata = true;
@SuppressWarnings("unchecked")
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
});
}
這樣就ok了
相關文章
- 微信公眾號之自動回覆文字 -- PHPPHP
- 微信公眾號-點選選單回覆圖片二維碼
- 微信公眾號自動回覆_JavaJava
- 圖靈教育微信公眾號關鍵詞回覆一覽表圖靈
- 微信公眾號自動回覆新增檔案
- 微信公眾號回覆小程式卡片如何實現?
- Python + Tornado 搭建自動回覆微信公眾號Python
- 【Flutter 專題】65 圖解基本 TextField 文字輸入框 (二)|8月更文挑戰Flutter圖解
- 微信公眾號--入門
- 微信公眾號快速開發(二)專案搭建與被動回覆
- Java IO之有緩衝的文字輸入Java
- 文字框輸入文字倒計詳解
- input只能輸入文字框
- wps文字教程:商標符號任我輸入符號
- Thinkphp 更新圖片,刪除原圖,更新文字或者圖片互不干涉,可以只更新圖片或者只更新文字。PHP
- 微信公眾號客服系統-接收對話方塊文字圖片影片訊息
- 【C#版本】微信公眾號模板訊息對接(二)(圖文詳解)C#
- 文字檔案輸入步驟
- Windows10系統怎麼新增輸入法【圖文】Windows
- 微信公眾號-入門的坑
- CAD中怎麼輸入文字?CAD製圖初學入門教程
- 微信公眾平臺開發(十) 訊息回覆總結
- JavaScript 文字框只能輸入數字JavaScript
- JavaScript 文字框輸入內容同步JavaScript
- jQuery文字框輸入內容同步jQuery
- javascript限制文字框輸入長度JavaScript
- JS 文字輸入框放大鏡效果JS
- 文字框只能輸入數字 javascriptJavaScript
- win10系統如何新增韓文輸入法【圖文】Win10
- 微信公眾平臺開發(四) 簡單回覆功能開發
- 海外微信公眾號不能設定被關注自動回覆訊息解決方案
- 微信公眾號java sdk技術選型Java
- Typinator 8 for Mac - 文字快捷輸入工具Mac
- 文字框限制輸入字數的JSJS
- 文字框只能輸入數字程式碼
- jQuery文字框內容輸入同步功能jQuery
- Apple Watch如何獲得文字輸入?APP
- 微信開發實戰(5)—粉絲關注開發者公眾號時,自動回覆訊息