鉴于前期做过短暂的小程序开发,之后做微信公号开发的时候觉得不是很难的,困难点在于前期对接成功;后期的业务逻辑代码就靠你自己发挥了
- 这里罗列的是不同模板消息需要的类
- 对接步骤的代码实现
/**
* 消息工具类
*
*/
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";
/**
* 事件类型:VIEW(自定义菜单链接事件)
*/
public static final String EVENT_TYPE_VIEW = "VIEW";
/**
* 事件类型:SCAN(用户扫描二维码,已关注的时候)
*/
public static final String EVENT_TYPE_SCAN = "SCAN";
// appid
public static final String APPID = "wx0418a42bb1c6b328";
// appsecret
public static final String APPSECRET = "f939d7f9da7f45fab12a7c6ab260dfcb";
// 获取openid请求地址
public static final String URL_OPENID =
"https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
// 获取jsapi_ticket
public static final String JSAPI_TICKET =
"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
// 获取access_token
public static final String ACCESS_TOKEN =
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
// 新增永久素材
public static final String MATERIAL_TOKEN =
"https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN";
/**
* 解析微信发来的请求(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 = (Element)document.getRootElement();
// 得到根元素的所有子节点
List<Element> elementList = root.elements();
// 遍历所有子节点
for (Element el : elementList) {
if (el.elements().size() == 0) {
map.put(el.getName(), el.getText());
} else {
List<Element> rl = el.elements();
for (Element e : rl) {
map.put(e.getName(), e.getText());
}
}
}
// 释放资源
inputstream.close();
inputstream = null;
return map;
}
/**
* 文本消息对象转换成xml
*
* @param newMessage 文本消息对象
* @return xml
*/
public static String textMessageToXml(com.rionsoft.WechatMsg.res.TextMessage newMessage) {
xstream.alias("xml", newMessage.getClass());
return xstream.toXML(newMessage);
}
/**
* 音乐消息对象转换成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 2015-11-10
*/
private static XStream xstream = new XStream(new XppDriver() {
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);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
});
/**
* 获取OPENID
*
* @param code
* @return
*/
public static String getOpenId(String code) {
String openid = null;
String openid_url = MessageUtil.URL_OPENID;
String requestUrl = openid_url.replace("APPID", MessageUtil.APPID).replace("SECRET", MessageUtil.APPSECRET)
.replace("CODE", code);
// 发起GET请求获取凭证
String result = ProxyUtil.httpsRequest(requestUrl, "POST", null);
JSONObject object = JSONObject.parseObject(result);
openid = object.getString("openid");
return openid;
}
/**
*
* 获取jsapi_ticket expires_in
*/
public static Map<String, Object> getJsapiTicket() {
Map<String, Object> paramMap = new HashMap<String, Object>();
String ticket = null;
String accessToken = null;
String expiresIn = null;
String accessTokenUtl =
MessageUtil.ACCESS_TOKEN.replace("APPID", MessageUtil.APPID).replace("APPSECRET", MessageUtil.APPSECRET);
String accessTokenResult = ProxyUtil.httpsRequest(accessTokenUtl, "GET", null);
JSONObject accessTokenObject = JSONObject.parseObject(accessTokenResult);
accessToken = accessTokenObject.getString("access_token");
expiresIn = accessTokenObject.getString("expires_in");
String jsTicketUrl = MessageUtil.JSAPI_TICKET.replace("ACCESS_TOKEN", accessToken);
// 发起GET请求获取凭证
String jsTicketResult = ProxyUtil.httpsRequest(jsTicketUrl, "GET", null);
JSONObject jsTicketObject = JSONObject.parseObject(jsTicketResult);
ticket = jsTicketObject.getString("ticket");
paramMap.put("ticket", ticket);
paramMap.put("expiresIn", expiresIn);
return paramMap;
}
/**
* 新增的永久素材
*
* @author yangjun
* @Date 2015-12-29
*/
public static String postFile(String url, String filePath, String title, String introduction) {
File file = new File(filePath);
if (!file.exists())
return null;
String result = null;
try {
URL url1 = new URL(url);
HttpURLConnection conn = (HttpURLConnection)url1.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
String boundary = "-----------------------------" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream output = conn.getOutputStream();
output.write(("--" + boundary + "\r\n").getBytes());
output.write(
String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName())
.getBytes());
output.write("Content-Type: video/mp4 \r\n\r\n".getBytes());
byte[] data = new byte[1024];
int len = 0;
FileInputStream input = new FileInputStream(file);
while ((len = input.read(data)) > -1) {
output.write(data, 0, len);
}
output.write(("--" + boundary + "\r\n").getBytes());
output.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());
output.write(String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}", title, introduction).getBytes());
output.write(("\r\n--" + boundary + "--\r\n\r\n").getBytes());
output.flush();
output.close();
input.close();
InputStream resp = conn.getInputStream();
StringBuffer sb = new StringBuffer();
while ((len = resp.read(data)) > -1)
sb.append(new String(data, 0, len, "utf-8"));
resp.close();
result = sb.toString();
} catch (Exception e) {
}
return result;
}
public static void main(String[] args) throws IOException {
String filePath = "F:/photo/transferPhoto/1.JPG";
String sendUrl = "";
String accessTokenUtl =
MessageUtil.ACCESS_TOKEN.replace("APPID", MessageUtil.APPID).replace("APPSECRET", MessageUtil.APPSECRET);
String accessTokenResult = ProxyUtil.httpsRequest(accessTokenUtl, "GET", null);
JSONObject accessTokenObject = JSONObject.parseObject(accessTokenResult);
String accessToken = accessTokenObject.getString("access_token");
sendUrl = MessageUtil.MATERIAL_TOKEN.replace("ACCESS_TOKEN", accessToken);
String imageUrl = null;
imageUrl = MessageUtil.postFile(sendUrl, filePath, "", "");
System.out.println(imageUrl);
}
}
- 对接实现
if (MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgType)) {
String Event = requestMap.get("Event");
if (MessageUtil.EVENT_TYPE_SUBSCRIBE.equals(Event)) {
// NewsMessage newsMessage = new NewsMessage();
// newsMessage.setToUserName(fromUserName);
// newsMessage.setFromUserName(toUserName);
// newsMessage.setCreateTime(new Date().getTime());
// newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
//
// List<Article> articleList = new ArrayList<Article>();
// // 单图文消息
// Article article = new Article();
// article.setTitle(MessageUtil.RESP_JIGONG_WELCOME_TITLE);
// article.setDescription(MessageUtil.RESP_JIGONG_WELCOME_DESCRIPTION);
// article.setPicUrl("http://gymspic1.oss-cn-shanghai.aliyuncs.com/wechat/wx_res_img.jpg");
// article.setUrl(
// "http://mp.weixin.qq.com/s?__biz=MzIyMjEyNTQ1NQ==&mid=100001048&idx=1&sn=ffe08d446979a208a9708f785dee3338&chksm=683309f85f4480ee743ba58071d573b4d125a16ecf4faad2d56237b63f304e62f0d03b980995#rd");
// articleList.add(article);
// // 设置图文消息个数
// newsMessage.setArticleCount(articleList.size());
// // 设置图文消息包含的图文集合
// newsMessage.setArticles(articleList);
// // 将图文消息对象转换成xml字符串
// respMessage = MessageUtil.newsMessageToXml(newsMessage);
// 创建图文消息(回复用)
TextMessage newsMessage = new TextMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setContent(MessageUtil.RESP_JIGONG_WELCOME_TITLE);
newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
respMessage = MessageUtil.textMessageToXml(newsMessage);
System.out.println(respMessage.toString());
log.info("msgType:" + msgType + ",Event:" + requestMap.get("Event") + ",event:"
+ requestMap.get("event"));
response.getWriter().write(respMessage.toString());// 关注回复 向用户发送消息
}
}
over