java開發微信公眾號,公眾號與java後臺獲取連線,自動回覆,關注獲取使用者資訊,取消關注刪除使用者資訊
@RequestMapping(method = { RequestMethod.GET })
public void gget(HttpServletRequest request, HttpServletResponse response) throws IOException {
// // 將請求、響應的編碼均設定為UTF-8(防止中文亂碼)
// request.setCharacterEncoding("UTF-8");
// //微信伺服器POST訊息時用的是UTF-8編碼,在接收時也要用同樣的編碼,否則中文會亂碼;
// response.setCharacterEncoding("UTF-8");
// //在響應訊息(回覆訊息給使用者)時,也將編碼方式設定為UTF-8,原理同上;boolean isGet =
// request.getMethod().toLowerCase().equals("get");
PrintWriter print = response.getWriter();
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 &&CheckoutUtil.checkSignature
try {
print = response.getWriter();
print.write(echostr);
print.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@RequestMapping(method = { RequestMethod.POST })
public void ppost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 當你用微信給平臺傳送資訊時就會到這裡
// 回覆音樂和圖文訊息,我都寫死了,自己可以根據自己的需要加相應的處理
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
String wxMsgXml = IOUtils.toString(request.getInputStream(), "utf-8");
RequestTextMessage textMsg = new RequestTextMessage();
String event = null;
StringBuffer replyMsg = new StringBuffer();
String returnXml = null;
//UserPro p = new UserPro();
try {
textMsg = ReplyMessage.getRequestTextMessage(wxMsgXml);
event = textMsg.getEvent();
String openID = textMsg.getFromUserName().toString();
if (textMsg.getEvent() != null) {
// 獲取使用者基本資訊
if (textMsg != null && event.equals("subscribe")) {
//Info info = p.userProcessing(openID);
// 儲存微信使用者基本資訊
//chatService.savaUserInfo(info);
// 儲存微信使用者openid到使用者管理
sysUserService.saveOpenid(openID);
List<Enter> chatList = new ArrayList<Enter>();
chatList = chatService.queryChat();
replyMsg.append("歡迎使用微信平臺!");
// 查詢資料庫,關注回覆歡迎語
for (int i = 0; i < chatList.size(); i++) {
replyMsg.append(
"\r\n" + chatList.get(i).getKeyWord() + "、" + chatList.get(i).getEnterContent() + "");
returnXml = ReplyMessage.getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName(),
textMsg.getToUserName());
}
} else {//取消關注刪除使用者資訊
//chatService.deleteUserInfo(textMsg.getFromUserName());
sysUserService.deleteUserByOpenId(openID);
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (textMsg.getContent() != null) {
//StringBuffer replyMsg = new StringBuffer();
String receive = textMsg.getContent().trim();
//String returnXml = null;
if (receive.equals("1")) {
// 回覆音樂資訊
returnXml = ReplyMessage.getReplyMusicMessage(textMsg.getFromUserName(), textMsg.getToUserName());
} else if (receive.equals("3")) {
// 回覆圖文
returnXml = ReplyMessage.getReplyTuwenMessager(textMsg.getFromUserName(), textMsg.getToUserName());
} else if (receive.equals("2")) {
// 回覆時間
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
replyMsg.append("當前時間\r\n" + df.format(new Date()));
returnXml = ReplyMessage.getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName(),
textMsg.getToUserName());
} else {
// 關鍵字查詢
Item item = (Item) chatService.queryImgText(receive);
if (item == null) {
replyMsg.append("沒有此關鍵字有關的內容,請重新輸入");
returnXml = ReplyMessage.getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName(),
textMsg.getToUserName());
} else {
returnXml = ReplyMessage.getReplyTuwenMessage(textMsg.getFromUserName(), textMsg.getToUserName(),
item);
}
}
//pw.println(returnXml);
}
pw.println(returnXml);
}
CheckoutUtil 工具類驗證token:
package io.renren.modules.fol.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
*
* @author hp
*token驗證
*/
public class CheckoutUtil {
// 與介面配置資訊中的Token要一致
private static String token = "sxxnhService";
/**
* 驗證簽名
*
* @param signature
* @param timestamp
* @param nonce
* @return
*/
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[] { token, timestamp, nonce };
// 將token、timestamp、nonce三個引數進行字典序排序
// Arrays.sort(arr);
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;
}
public static void sort(String a[]) {
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[j].compareTo(a[i]) < 0) {
String temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
}
ReplyMessage :獲取推送訊息
package io.renren.modules.fol.util;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import io.renren.modules.fol.message.Articles;
import io.renren.modules.fol.message.Item;
import io.renren.modules.fol.message.Music;
import io.renren.modules.fol.message.ReplyMusicMessage;
import io.renren.modules.fol.message.ReplyTextMessage;
import io.renren.modules.fol.message.ReplyTuwenMessage;
import io.renren.modules.fol.message.RequestTextMessage;
import io.renren.modules.fol.service.ChatService;
public class ReplyMessage {
@Autowired
private static ChatService chatService;
// 獲取推送文字訊息
public static RequestTextMessage getRequestTextMessage(String xml) {
XStream xstream = new XStream(new DomDriver());
xstream.alias("xml", RequestTextMessage.class);
xstream.aliasField("ToUserName", RequestTextMessage.class, "toUserName");
xstream.aliasField("FromUserName", RequestTextMessage.class, "fromUserName");
xstream.aliasField("CreateTime", RequestTextMessage.class, "createTime");
xstream.aliasField("MsgType", RequestTextMessage.class, "messageType");
xstream.aliasField("Content", RequestTextMessage.class, "content");
xstream.aliasField("MsgId", RequestTextMessage.class, "msgId");
xstream.aliasField("Event", RequestTextMessage.class, "event");
xstream.aliasField("EventKey", RequestTextMessage.class, "eventKey");
RequestTextMessage requestTextMessage = (RequestTextMessage) xstream.fromXML(xml);
return requestTextMessage;
}
// 回覆文字訊息
public static String getReplyTextMessage(String content, String fromUserName, String toUserName) {
ReplyTextMessage we = new ReplyTextMessage();
we.setMessageType("text");
we.setFuncFlag("0");
we.setCreateTime(new Long(new Date().getTime()).toString());
we.setContent(content);
we.setToUserName(fromUserName);
we.setFromUserName(toUserName);
XStream xstream = new XStream(new DomDriver());
xstream.alias("xml", ReplyTextMessage.class);
xstream.aliasField("ToUserName", ReplyTextMessage.class, "toUserName");
xstream.aliasField("FromUserName", ReplyTextMessage.class, "fromUserName");
xstream.aliasField("CreateTime", ReplyTextMessage.class, "createTime");
xstream.aliasField("MsgType", ReplyTextMessage.class, "messageType");
xstream.aliasField("Content", ReplyTextMessage.class, "content");
xstream.aliasField("FuncFlag", ReplyTextMessage.class, "funcFlag");
String xml = xstream.toXML(we);
return xml;
}
// 回覆音樂訊息
public static String getReplyMusicMessage(String fromUserName, String toUserName) {
ReplyMusicMessage we = new ReplyMusicMessage();
Music music = new Music();
we.setMessageType("music");
we.setCreateTime(new Long(new Date().getTime()).toString());
we.setToUserName(fromUserName);
we.setFromUserName(toUserName);
we.setFuncFlag("0");
music.setTitle("大壯");
music.setDescription("我們不一樣");
String url = "http://sc1.111ttt.cn/2017/1/11/11/304112002493.mp3";
String url2 = "http://sc1.111ttt.cn/2017/1/11/11/304112002493.mp3";
music.setMusicUrl(url);
music.setHqMusicUrl(url2);
we.setMusic(music);
XStream xstream = new XStream(new DomDriver());
xstream.alias("xml", ReplyMusicMessage.class);
xstream.aliasField("ToUserName", ReplyMusicMessage.class, "toUserName");
xstream.aliasField("FromUserName", ReplyMusicMessage.class, "fromUserName");
xstream.aliasField("CreateTime", ReplyMusicMessage.class, "createTime");
xstream.aliasField("MsgType", ReplyMusicMessage.class, "messageType");
xstream.aliasField("FuncFlag", ReplyMusicMessage.class, "funcFlag");
xstream.aliasField("Music", ReplyMusicMessage.class, "Music");
xstream.aliasField("Title", Music.class, "title");
xstream.aliasField("Description", Music.class, "description");
xstream.aliasField("MusicUrl", Music.class, "musicUrl");
xstream.aliasField("HQMusicUrl", Music.class, "hqMusicUrl");
String xml = xstream.toXML(we);
return xml;
}
// 回覆圖文訊息
public static String getReplyTuwenMessager(String fromUserName, String toUserName) {
ReplyTuwenMessage we = new ReplyTuwenMessage();
Articles articles = new Articles();
Item item = new Item();
we.setMessageType("news");
we.setCreateTime(new Long(new Date().getTime()).toString());
we.setToUserName(fromUserName);
we.setFromUserName(toUserName);
we.setFuncFlag("0");
we.setArticleCount(1);
item.setTitle("周杰倫");
item.setDescription("周杰倫(Jay Chou),1979年1月18日出生於臺灣省新北市,中國臺灣流行樂男歌手、音樂人、演員、導演、編劇、監製、商人。");
item.setPicUrl("http://cimg2.163.com/catchimg/20090930/8458904_45.jpg");
item.setUrl("https://baike.baidu.com/item/%E5%91%A8%E6%9D%B0%E4%BC%A6");
articles.setItem(item);
we.setArticles(articles);
XStream xstream = new XStream(new DomDriver());
xstream.alias("xml", ReplyTuwenMessage.class);
xstream.aliasField("ToUserName", ReplyTuwenMessage.class, "toUserName");
xstream.aliasField("FromUserName", ReplyTuwenMessage.class, "fromUserName");
xstream.aliasField("CreateTime", ReplyTuwenMessage.class, "createTime");
xstream.aliasField("MsgType", ReplyTuwenMessage.class, "messageType");
xstream.aliasField("Articles", ReplyTuwenMessage.class, "Articles");
xstream.aliasField("ArticleCount", ReplyTuwenMessage.class, "articleCount");
xstream.aliasField("FuncFlag", ReplyTuwenMessage.class, "funcFlag");
xstream.aliasField("item", Articles.class, "item");
xstream.aliasField("Title", Item.class, "title");
xstream.aliasField("Description", Item.class, "description");
xstream.aliasField("PicUrl", Item.class, "picUrl");
xstream.aliasField("Url", Item.class, "url");
String xml = xstream.toXML(we);
return xml;
}
// 回覆圖文訊息2
public static String getReplyTuwenMessage(String fromUserName, String toUserName,Item it) {
ReplyTuwenMessage we = new ReplyTuwenMessage();
Articles articles = new Articles();
Item item = new Item();
we.setMessageType("news");
we.setCreateTime(new Long(new Date().getTime()).toString());
we.setToUserName(fromUserName);
we.setFromUserName(toUserName);
we.setFuncFlag("0");
we.setArticleCount(1);
item.setTitle(it.getTitle());
item.setDescription(it.getDescription());
item.setPicUrl(it.getPicUrl());
item.setUrl(it.getUrl());
articles.setItem(item);
we.setArticles(articles);
XStream xstream = new XStream(new DomDriver());
xstream.alias("xml", ReplyTuwenMessage.class);
xstream.aliasField("ToUserName", ReplyTuwenMessage.class, "toUserName");
xstream.aliasField("FromUserName", ReplyTuwenMessage.class, "fromUserName");
xstream.aliasField("CreateTime", ReplyTuwenMessage.class, "createTime");
xstream.aliasField("MsgType", ReplyTuwenMessage.class, "messageType");
xstream.aliasField("Articles", ReplyTuwenMessage.class, "Articles");
xstream.aliasField("ArticleCount", ReplyTuwenMessage.class, "articleCount");
xstream.aliasField("FuncFlag", ReplyTuwenMessage.class, "funcFlag");
xstream.aliasField("item", Articles.class, "item");
xstream.aliasField("Title", Item.class, "title");
xstream.aliasField("Description", Item.class, "description");
xstream.aliasField("PicUrl", Item.class, "picUrl");
xstream.aliasField("Url", Item.class, "url");
String xml = xstream.toXML(we);
return xml;
}
}
UserPro :獲取使用者基本資訊
package io.renren.modules.fol.util;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.http.client.ClientProtocolException;
import com.alibaba.fastjson.JSONObject;
import io.renren.modules.fol.entity.Info;
/**
*
* @author hp
*使用者基本資訊
*/
public class UserPro {
public Info userProcessing(String openid) throws ClientProtocolException, IOException{
Info info = new Info();
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ WXAuthUtil.APPID + "&secret=" + WXAuthUtil.APPSECRET;
System.out.println(url);
JSONObject refreshInfo = WXAuthUtil.doGetJson(url);
String url2 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="
+ refreshInfo.getString("access_token") + "&openid=" +openid
+ "&lang=zh_CN";
System.out.println(url2);
JSONObject refreshInfo2 = WXAuthUtil.doGetJson(url2);
if (refreshInfo2.getString("sex").equals("1")) {
info.setSex("男");
} else if (refreshInfo2.getString("sex").equals("2")) {
info.setSex("女");
;
} else {
info.setSex("未知");
}
Long time = Long.parseLong(refreshInfo2.getString("subscribe_time"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String subtime = sdf.format(new Date(time * 1000L));
info.setCreattime(subtime);
if (refreshInfo2.getString("subscribe_scene").equals("ADD_SCENE_SEARCH")) {
info.setMode("公眾號搜尋");
} else if (refreshInfo2.getString("subscribe_scene").equals("ADD_SCENE_QR_CODE")) {
info.setMode("掃描二維碼");
}
info.setOpenid(refreshInfo2.getString("openid"));
info.setConuntry(refreshInfo2.getString("country"));
info.setProvince(refreshInfo2.getString("province"));
info.setUrban(refreshInfo2.getString("city"));
info.setImg(refreshInfo2.getString("headimgurl"));
info.setLang(refreshInfo2.getString("language"));
info.setIname(refreshInfo2.getString("nickname"));
return info;
}
}
WXAuthUtil :訪問網址獲取資訊,輸入自己的APPID和APPSECRET
package io.renren.modules.fol.util;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class WXAuthUtil {
public static final String APPID="wx06496765cdeb9090";//wx06496765cdeb9090
public static final String APPSECRET ="0fed2c47cb8a0b62ebbe69487a376089";//0fed2c47cb8a0b62ebbe69487a376089
public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
JSONObject jsonObject =null;
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet =new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity =response.getEntity();
if(entity!=null)
{
//轉化為json物件
String result =EntityUtils.toString(entity, "UTF-8");
jsonObject =JSON.parseObject(result);
}
return jsonObject;
}
}
RequestTextMessage://文字型別
package io.renren.modules.fol.message;
public class RequestTextMessage {
private String toUserName;
private String fromUserName;
private String createTime;
private String messageType;
private String content;
private String event;
private String eventKey;
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
private String msgId;
//getters,setters
public String getToUserName() {
return toUserName;
}
public void setToUserName(String toUserName) {
this.toUserName = toUserName;
}
public String getFromUserName() {
return fromUserName;
}
public void setFromUserName(String fromUserName) {
this.fromUserName = fromUserName;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getMessageType() {
return messageType;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getMsgId() {
return msgId;
}
public void setMsgId(String msgId) {
this.msgId = msgId;
}
public String getEventKey() {
return eventKey;
}
public void setEventKey(String eventKey) {
this.eventKey = eventKey;
}
}
ReplyTuwenMessage :圖文型別
package io.renren.modules.fol.message;
//ͼ����Ϣ
public class ReplyTuwenMessage {
private String toUserName;
private String fromUserName;
private String createTime;
private String messageType;
private int articleCount;
private Articles Articles;
private String funcFlag;
public String getToUserName() {
return toUserName;
}
public void setToUserName(String toUserName) {
this.toUserName = toUserName;
}
public String getFromUserName() {
return fromUserName;
}
public void setFromUserName(String fromUserName) {
this.fromUserName = fromUserName;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getMessageType() {
return messageType;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
public int getArticleCount() {
return articleCount;
}
public void setArticleCount(int articleCount) {
this.articleCount = articleCount;
}
public Articles getArticles() {
return Articles;
}
public void setArticles(Articles articles) {
Articles = articles;
}
public String getFuncFlag() {
return funcFlag;
}
public void setFuncFlag(String funcFlag) {
this.funcFlag = funcFlag;
}
}
ReplyTextMessage :文字型別
package io.renren.modules.fol.message;
//�ı���Ϣ
public class ReplyTextMessage {
private String toUserName;
private String fromUserName;
private String createTime;
private String messageType;
private String content;
private String funcFlag;
private String event;
private String eventKey;
public String getToUserName() {
return toUserName;
}
public void setToUserName(String toUserName) {
this.toUserName = toUserName;
}
public String getFromUserName() {
return fromUserName;
}
public void setFromUserName(String fromUserName) {
this.fromUserName = fromUserName;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getMessageType() {
return messageType;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFuncFlag() {
return funcFlag;
}
public void setFuncFlag(String funcFlag) {
this.funcFlag = funcFlag;
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public String getEventKey() {
return eventKey;
}
public void setEventKey(String eventKey) {
this.eventKey = eventKey;
}
}
ReplyMusicMessage :音樂型別
package io.renren.modules.fol.message;
//������Ϣ
public class ReplyMusicMessage {
private String toUserName;
private String fromUserName;
private String createTime;
private String messageType;
private Music Music;
private String funcFlag;
public String getToUserName() {
return toUserName;
}
public void setToUserName(String toUserName) {
this.toUserName = toUserName;
}
public String getFromUserName() {
return fromUserName;
}
public void setFromUserName(String fromUserName) {
this.fromUserName = fromUserName;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getMessageType() {
return messageType;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
public Music getMusic() {
return Music;
}
public void setMusic(Music music) {
Music = music;
}
public String getFuncFlag() {
return funcFlag;
}
public void setFuncFlag(String funcFlag) {
this.funcFlag = funcFlag;
}
}
Music :
package io.renren.modules.fol.message;
//����
public class Music {
private String title;
private String description;
private String musicUrl;
private String hqMusicUrl;
//getters,setters
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMusicUrl() {
return musicUrl;
}
public void setMusicUrl(String musicUrl) {
this.musicUrl = musicUrl;
}
public String getHqMusicUrl() {
return hqMusicUrl;
}
public void setHqMusicUrl(String hqMusicUrl) {
this.hqMusicUrl = hqMusicUrl;
}
}
Item :
package io.renren.modules.fol.message;
//ͼ��
public class Item {
private String title;
private String description;
private String picUrl;
private String url;
//getters,setters
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Articles :
package io.renren.modules.fol.message;
//����
public class Articles {
private Item item;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}