WeChat public account development attention to push graphic messages

Follow/unfollow events

When users follow and unfollow the official account, WeChat will push the event to the URL filled in by the developer. It is convenient for developers to send welcome messages to users or to unbind accounts.

If the WeChat server does not receive a response within five seconds, the connection will be disconnected, and the request will be re-initialized for a total of three retries.

Regarding the retry message queue, it is recommended to use FromUserName + CreateTime to queue.

If the server cannot guarantee to process and reply within five seconds, it can directly reply with an empty string, and the WeChat server will not do anything to this, and will not initiate a retry.

Example of push XML packet:

<xml><ToUserName>< ![CDATA[toUser] ]></ToUserName><FromUserName>< ![CDATA[FromUser] ]></FromUserName><CreateTime>123456789</CreateTime><MsgType>< ![CDATA[event] ]></MsgType><Event>< ![CDATA[subscribe] ]></Event></xml>

Parameter Description:

parameter describe
ToUserName Developer WeChat
FromUserName Sender account number (an OpenID)
CreateTime message creation time (integer)
MsgType message type, event
Event Event type, subscribe (subscribe), unsubscribe (unsubscribe)

Reply to text messages

<xml><ToUserName>< ![CDATA[toUser] ]></ToUserName><FromUserName>< ![CDATA[fromUser] ]></FromUserName><CreateTime>12345678</CreateTime><MsgType>< ![CDATA[news] ]></MsgType><ArticleCount>2</ArticleCount><Articles><item><Title>< ![CDATA[title1] ]></Title> <Description>< ![CDATA[description1] ]></Description><PicUrl>< ![CDATA[picurl] ]></PicUrl><Url>< ![CDATA[url] ]></Url></item><item><Title>< ![CDATA[title] ]></Title><Description>< ![CDATA[description] ]></Description><PicUrl>< ![CDATA[picurl] ]></PicUrl><Url>< ![CDATA[url] ]></Url></item></Articles></xml>
parameter Is it necessary illustrate
ToUserName Yes Receiver account number (OpenID received)
FromUserName Yes Developer WeChat
CreateTime Yes message creation time (integer)
MsgType Yes news
ArticleCount Yes The number of text messages is limited to 8
Articles Yes Multiple graphic message information, the default first item is a large image, note that if the number of graphic text exceeds 8, there will be no response
Title Yes Text message title
Description Yes Text message description
PicUrl Yes Image link, support JPG, PNG format, the better effect is 360*200 for large image and 200*200 for small image
Url Yes Click on the text message jump link
The detailed code is as follows
News.java
public class News {
    private String Title;//Graphic title
    private String Description;//Graphic description
    private String PicUrl;//Picture link, support JPG, PNG format, the better effect is 360*200 for large picture and 200*200 for small picture
    private String Url;//Click on the jump link of the graphic message

    public News(String title, String description, String picUrl, String url) {
        this.Title = title;
        this.Description = description;
        this.PicUrl = picUrl;
        this.Url = url;
    }
    public News(){super();}

    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;
    }
}

NewsMessage.java

public class NewsMessage extends BaseMessage {
    private int ArticleCount;//图文消息个数,限制为8条以内
    private List<News> Articles;//多条图文消息信息,默认第一个item为大图,注意,如果图文数超过8,则将会无响应
    public NewsMessage(String toUserName, String fromUserName, Long createTime, String msgType, Integer articleCount, List<News> articles) {
        super(toUserName, fromUserName, createTime, msgType);
        this.ArticleCount = articleCount;
        this.Articles = articles;
    }

    public NewsMessage() {
        super();
    }


    public int getArticleCount() {
        return ArticleCount;
    }

    public void setArticleCount(int articleCount) {
        this.ArticleCount = articleCount;
    }

    public List<News> getArticles() {
        return Articles;
    }

    public void setArticles(List<News> articles) {
        this.Articles = articles;
    }
}

初始化图文消息:

    /**
     * 初始化图文消息
     */
    public static String initNewsMessage(String toUSerName, String fromUserName) {
        List<News> newsList = new ArrayList<News>();
        NewsMessage newsMessage = new NewsMessage();
        //组建一条图文↓ ↓ ↓
        News newsItem = new News();
        newsItem.setTitle("欢迎关注我的公众号");
        newsItem.setDescription("进行操作之前请先注册!");
        newsItem.setPicUrl(WXConstants.BASE_SERVER + "/image/wx/login_article_cover.png");
        newsItem.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WXConstants.APPID + "&redirect_uri=" + WXConstants.BASE_SERVER + "/wxuser/toRegister&response_type=code&scope=snsapi_base&state=BINDFACE#wechat_redirect");
        newsList.add(newsItem);
        //组装图文消息相关信息
        newsMessage.setToUserName(fromUserName);
        newsMessage.setFromUserName(toUSerName);
        newsMessage.setCreateTime(new Date().getTime());
        newsMessage.setMsgType(WXConstants.MESSAGE_NEWS);
        newsMessage.setArticles(newsList);
        newsMessage.setArticleCount(newsList.size());
        //调用newsMessageToXml将图文消息转化为XML结构并返回
        return MessageUtil.newsMessageToXml(newsMessage);
    }
    /**
     * 图文消息转XML结构方法
     */
    public static String newsMessageToXml(NewsMessage message) {
        XStream xs = new XStream();
        //由于转换后xml根节点默认为class类,需转化为<xml>
        xs.alias("xml", message.getClass());
        xs.alias("item", new News().getClass());
        return xs.toXML(message);
    }

测试关注:

@Controller
@RequestMapping("/wechat")
public class WxController {

    private final static String MEDIATYPE_CHARSET_JSON_UTF8 = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8";
    private static Logger log = LoggerFactory.getLogger(WxController.class);

    @RequestMapping(value = "/chat", method = {RequestMethod.GET, RequestMethod.POST}, produces = MEDIATYPE_CHARSET_JSON_UTF8)
    public void get(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //如果为get请求,则为开发者模式验证
        if ("get".equals(request.getMethod().toLowerCase())) {
            doGet();//在开发者模式验证中已处理,在此省略
        } else {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            try {
                Map<String, String> map = MessageUtil.xmlToMap(request);
                String ToUserName = map.get("ToUserName");
                String FromUserName = map.get("FromUserName");
                request.getSession().setAttribute("openid",FromUserName);
                String CreateTime = map.get("CreateTime");
                String MsgType = map.get("MsgType");
                String message = null;
                if (MsgType.equals(WXConstants.MESSAGE_EVENT)) {
                    //从集合中,获取是哪一种事件传入
                    String eventType = map.get("Event");
                    if (eventType.equals(WXConstants.MESSAGE_SUBSCRIBE)) {
                        message = MessageUtil.initNewsMessage(ToUserName, FromUserName);
                    }
                }
                out.print(message); //返回转换后的XML字符串
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            out.close();
        }
    }
}

关注测试号,弹出如下结果:


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325805733&siteId=291194637