微信公眾號開發--群發推送圖文消息


群發推送消息,分為三步,先上傳圖片獲得圖片的id,再上傳圖文素材獲得Id,最后把素材Id群發給目標

一 上傳圖片

 1  /**
 2      * 上傳圖片
 3      *
 4      * @param file  表單名稱media
 5      * @param token access_token  type = "image";
 6      * @param type  type只支持四種類型素材(video/image/voice/thumb)
 7      */
 8     @RequestMapping("uoloadimage.action")
 9     public String uploadMedia( ) {
10        /* if (file == null || token == null || type == null) {
11             return null;
12         }
13 
14         if (!file.exists()) {
15             System.out.println("上傳文件不存在,請檢查!");
16             return null;
17         }*/
18         String token=WxaApi.accessToken.getAccessToken();
19         String type="image";
20         File file=new File("D:/1.JPG");
21         /*
22          * 
23          */
24         String url = "https://api.weixin.qq.com/cgi-bin/media/upload";
25         com.alibaba.fastjson.JSONObject jsonObject = null;
26         PostMethod post = new PostMethod(url);
27         post.setRequestHeader("Connection", "Keep-Alive");
28         post.setRequestHeader("Cache-Control", "no-cache");
29         FilePart media;
30         HttpClient httpClient = new HttpClient();
31         //信任任何類型的證書
32         Protocol myhttps = new Protocol("https", new SSLProtocolSocketFactory(), 443);
33         Protocol.registerProtocol("https", myhttps);
34 
35         try {
36             media = new FilePart("media", file);
37             Part[] parts = new Part[]{new StringPart("access_token", token),
38                     new StringPart("type", type), media};
39             MultipartRequestEntity entity = new MultipartRequestEntity(parts,
40                     post.getParams());
41             post.setRequestEntity(entity);
42             int status = httpClient.executeMethod(post);
43             if (status == HttpStatus.SC_OK) {
44                 String text = post.getResponseBodyAsString();
45                 jsonObject = com.alibaba.fastjson.JSONObject.parseObject(text);
46             } else {
47                 System.out.println("upload Media failure status is:" + status);
48             }
49         } catch (FileNotFoundException e) {
50             e.printStackTrace();
51         } catch (HttpException e) {
52             e.printStackTrace();
53         } catch (IOException e) {
54             e.printStackTrace();
55         }
56         String media_id = jsonObject.get("media_id").toString();
57         System.out.println("media_id="+media_id);
58         return null;
59     }
media_id 為下一步需要的圖片Id

二 上傳素材
 1 /**
 2      * 上傳圖文消息素材
 3      */
 4     @RequestMapping("uploadnews.action")
 5     public void uploadnews(){
 6         /*Articles    是    圖文消息,一個圖文消息支持1到8條圖文
 7          *thumb_media_id    是    圖文消息縮略圖的media_id,可以在基礎支持-上傳多媒體文件接口中獲得
 8          *author    否    圖文消息的作者
 9          *title    是    圖文消息的標題
10          *content_source_url    否    在圖文消息頁面點擊“閱讀原文”后的頁面,受安全限制,如需跳轉Appstore,可以使用itun.es或appsto.re的短鏈服務,並在短鏈后增加 #wechat_redirect 后綴。
11          *content    是    圖文消息頁面的內容,支持HTML標簽。具備微信支付權限的公眾號,可以使用a標簽,其他公眾號不能使用,如需插入小程序卡片,可參考下文。
12          *digest    否    圖文消息的描述,如本字段為空,則默認抓取正文前64個字
13          *show_cover_pic    否    是否顯示封面,1為顯示,0為不顯示
14          *need_open_comment    否    Uint32 是否打開評論,0不打開,1打開
15          *only_fans_can_comment    否    Uint32 是否粉絲才可評論,0所有人可評論,1粉絲才可評論*/
16          JSONObject js1=new JSONObject();
17          js1.put("thumb_media_id", "y06hl0sGMuo9UEOFSk-*******-R7-BCYRZzuk1vuJ7zsmfZdm2nmpExnt7wddB");
18          js1.put("author", "wu");
19          js1.put("title", "推送1");js1.put("content_source_url", "");js1.put("content", "這是測試公眾號推送1");
20          js1.put("digest", "");js1.put("show_cover_pic", "1");js1.put("need_open_comment", "1");
21          js1.put("only_fans_can_comment", "0");
22          
23          JSONObject js2=new JSONObject();
24          js2.put("thumb_media_id", "hxlqiCyuyv4_paYLZjKQ7*************w9XHaxjLL87QqcvLf74dG60kdEDRv");
25          js2.put("author", "chao");
26          js2.put("title", "推送2");js2.put("content_source_url", "");js2.put("content", "這是測試公眾號推送2");js2.put("digest", "");
27          js2.put("show_cover_pic", "1");js2.put("need_open_comment", "1");
28          js2.put("only_fans_can_comment", "0");
29          
30          JSONArray jsarray=new JSONArray();
31          jsarray.add(js1.toString());jsarray.add(js2.toString());
32          
33          JSONObject js=new JSONObject();
34          js.put("articles", jsarray.toString());
35          
36          String jsstring = js.toString();
37          System.out.println(jsstring);
38          String url="https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN".replaceAll("ACCESS_TOKEN", WxaApi.accessToken.getAccessToken());
39          String httpsResponse = netWorkHelper.getHttpsResponse(url, "POST", jsstring);
40          System.out.println(httpsResponse);
41          JSONObject newsjs=JSONObject.fromObject(httpsResponse);
42          String newsmedia = newsjs.getString("media_id");
43          
44     }

json字符串的格式可以參考開發文檔,本Demo是發送兩條數據

 

三 群發

/**
     * 上傳的圖文素材群發
     */
    @RequestMapping("sendall.get")
    public void sendall(){
        /*
         *     filter    是    用於設定圖文消息的接收者
                is_to_all    否    用於設定是否向全部用戶發送,值為true或false,選擇true該消息群發給所有用戶,選擇false可根據tag_id發送給指定群組的用戶
            mpnews    是    用於設定即將發送的圖文消息
                media_id    是    用於群發的消息的media_id
            msgtype    是    群發的消息類型,圖文消息為mpnews,文本消息為text,語音為voice,音樂為music,圖片為image,視頻為video,卡券為wxcard
            send_ignore_reprint    是    圖文消息被判定為轉載時,是否繼續群發。 1為繼續群發(轉載),0為停止群發。 該參數默認為0。
         */
        JSONObject j1=new JSONObject();
        JSONObject j11=new JSONObject();
        JSONObject j21=new JSONObject();
        j11.put("is_to_all", true);
        j21.put("media_id", "BiawhA7misCxWfAiuXUSi******************UYVf-baKrSsmTouuxCzIcR_k43Hg2oeFo");
        j1.put("filter",j11.toString());
        j1.put("mpnews", j21.toString());
        j1.put("msgtype", "mpnews");
        j1.put("send_ignore_reprint", 1);
        System.out.println(j1.toString());
        
        String url="https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", WxaApi.accessToken.getAccessToken());
        String httpsResponse = netWorkHelper.getHttpsResponse(url, "POST", j1.toString());
        System.out.println(httpsResponse);
    }

只有實名認證過的才能發送成功,遇到錯誤直接百度,流程是沒問題的,錯誤可能是自己的參數或者自己公眾號的問題,測試公眾號沒法用,可以把第三步換成預覽的方法,預覽方法如下

 1 /**
 2      * 推送預覽
 3      */
 4     @RequestMapping("preview.action")
 5     public void preview (){
 6         JSONObject j1=new JSONObject();
 7         j1.put("media_id", "這為第二步返回的iD    ::iuXUSiShxnw6xeJSUYVf-baKrSsmTouuxCzIcR_k43Hg2oeFo");
 8         JSONObject j=new JSONObject();
 9         j.put("touser", "這是發送目標的微信openid");
10         j.put("mpnews", j1.toString());
11         j.put("msgtype", "mpnews");
12         String url="https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", WxaApi.accessToken.getAccessToken());
13         String httpsResponse = netWorkHelper.getHttpsResponse(url, "POST", j.toString());
14         System.out.println(httpsResponse);
15     }
netWorkHelper工具類 可以翻我其他的隨筆有代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM