Wechat Development Picture and Text Message Sending

Posted by D1proball on Tue, 16 Jul 2019 01:51:17 +0200

Wechat Text Message Sending:

In order to send pictures and text messages, we need to know several interfaces, active and passive sending. The active meaning here is the public number of pictures and text messages, which are sent to the concerned users actively. The passive meaning is the message that the service number replies to the user when it receives the user's request or other events. Let's take a look at Wechat's initiative to send graphic messages to users.
The first factor is whether our public number or service number needs to be certified. Of course, the object of sending is also the user who pays attention to our service number. The basis for these operations is the user's openId. Only when the user's openId is obtained, can the group send messages according to the openId. Of course, the group send messages according to the group. What we are talking about here is just the group send messages according to the openId.
Or the first two sections said that we need to obtain the user's openId, that is, to authenticate, of course, openId does not need personal information such as nicknames, we can do silent authorization in a way that users do not perceive. Well, if openId has the graphical information we need to send, the rest is the graphical material. Now let's talk about this picture material in detail.
1. Composition of graphic materials:
1.1 Picture Material, Picture Material is the pictures we send in Picture Material. The value of this parameter is thumb_media_id in the image material uploaded later.
1.2 title: title for sending graphic message material
1.3 Author:author,
1.4 Summary of graphic and text messages, only single graphic and text messages have a summary, multi-graphic and text here is empty: digest
1.5 Whether to display the cover, 0 is false, that is not, 1 is true, that is, show CoverPic, this field sets whether to display the logo of the home page when we click on the message sent.
1.6 Specific content of graphic message, support HTML tag, must be less than 20,000 characters, less than 1M, and here will remove JS, content, if the service number supports payment function, the content can use a tag, click on the text message sent to enter at any time an image arc image can enter us. The page you want users to see. If there is no payment function, it can only guide users to click on the original text and enter the page we want users to enter.
1.7 The original address of the graphic message, that is, click the URL after "reading the original text", contentSourceUrl. If our service number supports payment function, this connection can be configured in the response link of clicking on the picture.
2. When we understand the composition of graphic materials, we upload them.
2.1 First, upload pictures.
2.2 Get the image material uploaded in the previous step, and upload the image material as the parameter of the image material.
3. Send pictures and text messages by uploading pictures and text materials. Users can receive messages and click to view them.

Let's take a look at uploading 1. uploading pictures. 2. Upload graphic materials.
1. Upload picture material. Notice the difference between here and in the document. But in general, it is still installed on the document, that is, the given Url, using the one we use here, personal testing is effective!!!

//Note that the URl given in this URL document does not have this parameter: type, but this parameter is necessary. If we upload pictures here, we can just use image.
private static String ADD_MATERIAL_URL = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=%s&type=%s";
    String addImageMedia(String type, File imageFile, String token) {
        String url = String.format(ADD_MATERIAL_URL, token, type);
        String materialResult = null;
        try {
            LOGGER.info("Upload pictures and texts of micro-letters Url :{}", url);
            materialResult = HttpsUtil.connectHttpsByPost(url, null, imageFile);
            LOGGER.info("Result of uploading pictures and texts of micro-messages:{}", materialResult);
        } catch (Exception ex) {
            LOGGER.error("Exceptions in uploading pictures and texts of Weibo:", ex);
        }
        return materialResult;
    }

The three request parameters are:
Type: The type of file uploaded, even if the picture is image.
imageFile: The path to upload files. Here's where we prepare to upload files. It's convenient for programs to find the resources we upload.
Token: The credentials for each interface call. This value is 7200 valid time, and there are interface request limits, so make a cache, or do a task timing brush, then a token is OK.
The post method of https is used, and the result is:

{"media_id":"dQ30hiyMqdIdtRcsy7yc6_w5rcmiAMAmaw5g9_XXdZo",
"url":"http:\/\/mmbiz.qpic.cn\/mmbiz_png\/c9uhCXXHZCxNWH4hknQw2rFchdGCrI1jbsvN9KhRHOBiaj6kbGh6SfCUB9VKU561gibpnN3Azuz6esvvMxYJWCiag\/0?wx_fmt=png"}
What we need to pay attention to is the text message we send. The picture material we use must be the permanent picture material. The temporary picture material does not work. The media_id we get here is thumb_media_id for uploading graphic material next.
2. Well, after uploading the pictures, let's upload the pictures and texts.

//Upload pictures and texts
 private static final String PERMANENT_MEDIA_URL = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=%s";

    String addPermanentMediaArticle(MediaArticle mediaArticle) {
        String url = String.format(PERMANENT_MEDIA_URL, mediaArticle.getToken());
        try {
            Map<String, Object> paramMap = Maps.newHashMap();

            List<Map> articleList = Lists.newArrayList();

            for (MediaArticle.Article article : mediaArticle.getArticles()) {
                Map<String, String> articleMap = Maps.newHashMap();
                articleMap.put("title", article.getTitle());
                articleMap.put("thumb_media_id", article.getThumbMediaId());
                articleMap.put("author", article.getAuthor());
                articleMap.put("digest", article.getDigest());
                articleMap.put("show_cover_pic", article.getShowCoverPic());
                articleMap.put("content", article.getContent());
                articleMap.put("content_source_url", article.getContentSourceUrl());
                articleList.add(articleMap);
            }
            paramMap.put("articles", articleList);
            String param = GsonHolder.getGson().toJson(paramMap);
            LOGGER.info("Adding Wechat Text Material Request url:{},parameter:{}", url, param);
            String result = HttpClientUtils.sendHttpsPost(url, param);
            LOGGER.info("Return results by adding textual and graphical materials of Wechat:{}", result);
            return result;
        } catch (Exception ex) {
            LOGGER.error("Adding Abnormal Text Material to Wechat:", ex);
        }
        return null;
    }

1. Or use https, the post method to request, url directly with our interface request credentials parameter token.
2. Let's take a look at these request parameters: the parameters here are not exhaustive, the parameters here are listed above.
Let's look at the return value:

//media_id returned by permanent text message
{"media_id":"dQ30hiyMqdIdtRcsy7yc6xsMazGcezOQXYb6GvcoWWw"}

Use the media_id returned above to send a text message.

3. Let's try sending text messages. Here we can use the formal online environment API to send formal notification messages directly, or use the preview interface to send some people to see the results first. The call limit of the preview interface is 100 times a day.

    /**
     * Preview of Text and Picture Material Sending
     */
    private static String MEDIA_PRE_VIEW_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=%s";

    String mediaPreView(String mediaId, String msgtype, String openId, String token) {

        String url = String.format(MEDIA_PRE_VIEW_URL, token);

        String preViewResult = null;
        try {
            Map<String, Object> paramMap = Maps.newHashMap();
            Map<String, String> touser = Maps.newHashMap();
            paramMap.put("touser", openId);
            paramMap.put("msgtype", msgtype);
            touser.put("media_id", mediaId);
            paramMap.put("mpnews", touser);
            String param = GsonHolder.getGson().toJson(paramMap);
            LOGGER.info("Graphic Message Sending Preview,url:{}, param:{}", url, param);
            preViewResult = HttpClientUtils.sendHttpsPost(url, param);
            LOGGER.info("Graphic Message Sending Preview,result:{}", preViewResult);
        } catch (Exception ex) {
            LOGGER.error("Graphic Message Sending Preview Exception:", ex);
        }
        return preViewResult;
    }

This is our preview interface to send text messages, expired clicks are invalid. touser is the openIds that need to send messages. Note that if you send messages in groups, there must be more than two openIds in this set. msgtype is the image type: mpnews, mpnews is the parameter of media_id of the graphic message we got above.
ErroCode: 0, errorMessage: success

Well, in this issue, we have seen the sending of pictures and texts, and in the next issue, we will take a look at the management of materials for Weixin.

Topics: less REST