随着科技的发展,人们利用公众账号平台进行自媒体活动,简单来说就是进行一对多的媒体性行为活动,如商家通过申请公众微信服务号通过二次开发展示商家微官网、微会员、微推送、微支付、微活动、微报名、微分享、微名片等,已经形成了一种主流的线上线下微信互动营销方式。
通过慕课网的学习,我对公众平台开发也熟悉许多,以下是个人分享(前提先注册公众号)
一.导入Jar包
可以去Maven配置下载
二.搭建好目录结构
三.具体实现
TestMessage代码:
package com.imooc.po;
public class TestMessage {
private String ToUserName; // 开发者微信号
private String FromUserName; // 发送方帐号(一个OpenID)
private Long CreateTime; // 消息创建时间 (整型)
private String MsgType;// text
private String Content; // 文本消息内容
private String MsgId;
public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public Long getCreateTime() {
return CreateTime;
}
public void setCreateTime(long l) {
CreateTime = l;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
public String getMsgId() {
return MsgId;
}
public void setMsgId(String msgId) {
MsgId = msgId;
}
@Override
public String toString() {
return "TestMessage [ToUserName=" + ToUserName + ", FromUserName=" + FromUserName + ", CreateTime=" + CreateTime
+ ", MsgType=" + MsgType + ", Content=" + Content + ", MsgId=" + MsgId + "]";
}
}
WeixinServlet代码:
package com.imooc.sevlet;
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 org.dom4j.DocumentException;
import com.imooc.po.TestMessage;
import com.imooc.util.CheckUtil;
import com.imooc.util.MessageUtil;
public class WeixinServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
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 req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
resp.setCharacterEncoding("utf-8");
req.setCharacterEncoding("utf-8");
PrintWriter out=resp.getWriter();
try {
Map<String, String> map=MessageUtil.xmlToMap(req);
String fromUserName=map.get("FromUserName");
String toUserName=map.get("ToUserName");
String msgType=map.get("MsgType");
String content=map.get("Content");
String message=null;
if(MessageUtil.MESSAGE_TEXT.equals(msgType)) {
if("1".equals(content)) {
message=MessageUtil.initText(toUserName, fromUserName, MessageUtil.firstSubMenu());
}else if("2".equals(content)){
message=MessageUtil.initText(toUserName, fromUserName, MessageUtil.secondSubMenu());
}else if("?".equals(content)||"?".equals(content)) {
message=MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
}
}else if(MessageUtil.MESSAGE_EVENT.equals(msgType)){
String eventType=map.get("Event");
if(MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)){
message=MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
}else {
message=MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
}
}
System.out.println("为什么不出来呢"+message);
out.print(message);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
out.close();
}
}
}
CheckUtil代码:
package com.imooc.util;
import java.security.MessageDigest;
import java.util.Arrays;
public class CheckUtil {
private static final String token = "imooc";
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]);
}
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;
}
}
}
MessageUtil代码:
package com.imooc.util;import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.imooc.po.TestMessage;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
/**
*
* @author user XML转map
*/
public class MessageUtil {
public static final String MESSAGE_TEXT = "text";
public static final String MESSAGE_IMAGE = "image";
public static final String MESSAGE_VOICE = "voice";
public static final String MESSAGE_VIDEO = "video";
public static final String MESSAGE_LINK = "link";
public static final String MESSAGE_LOCATION = "location";
public static final String MESSAGE_EVENT = "event";
public static final String MESSAGE_SUBSCRIBE = "subscribe";
public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";
public static final String MESSAGE_CLICK = "CLICK";
public static final String MESSAGE_VIEW= "VIEW";
public static Map<String, String> xmlToMap(HttpServletRequest req) throws IOException, DocumentException {
Map<String, String> map = new HashMap<String, String>();
SAXReader reader = new SAXReader();
InputStream ins = req.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;
}
/**
*
* @param text
* @return
*/
public static String textMessageToXml(TestMessage textmessage) {
// TODO Auto-generated method stub
XStream xtream = new XStream(new StaxDriver());
xtream.alias("xml", textmessage.getClass());
return xtream.toXML(textmessage);
}
/**
* 3.主菜单
*/
public static String menuText(){
StringBuffer sb=new StringBuffer();
sb.append("欢迎您关注,请按照菜单提示进行操作:\n\n");
sb.append("1.公众号介绍\n");
sb.append("2.开发者介绍\n\n");
sb.append("回复\"?\"调出此菜单。");
return sb.toString();
}
/**
* 4.组合文本消息
* @param toUserName
* @param fromUserName
* @param content
* @return
*/
public static String initText(String toUserName,String fromUserName,String content){
TestMessage textMessage=new TestMessage();
textMessage.setFromUserName(toUserName);
textMessage.setToUserName(fromUserName);
textMessage.setContent(content);
textMessage.setMsgType(MessageUtil.MESSAGE_TEXT);
textMessage.setCreateTime(Long.valueOf(new Date().getTime()));
return textMessageToXml(textMessage);
}
/**
* 5.第一个子菜单:1--公众号介绍
*/
public static String firstSubMenu(){
StringBuffer sb=new StringBuffer();
sb.append("Hello World");
return sb.toString();
}
/**
* 6.第二个子菜单:2--开发者介绍
*/
public static String secondSubMenu(){
StringBuffer sb=new StringBuffer();
sb.append("我是xqs,我很帅的呢!");
return sb.toString();
}
}
四.国内Natapp内网穿透
详解请看:https://natapp.cn/(一分钟新手教程)
完成后你就可以拥有自己掌控的微信平台了,祝你成功!!!
源码下载(全套):https://download.csdn.net/download/blogsdemo/10380621