微信公眾號開發之上傳圖文消息素材(十二)


群發消息太重要了,公眾號管理員需要定期通過公眾號群發一些消息,用戶通過推送的消息可以定期了解公眾號的最新信息。

群發圖文消息的過程如下:

  1. 首先,預先將圖文消息中需要用到的圖片,使用上傳圖文消息內圖片接口,上傳成功並獲得圖片 URL;
  2. 上傳圖文消息素材,需要用到圖片時,請使用上一步獲取的圖片 URL;
  3. 使用對用戶標簽的群發,或對 OpenID 列表的群發,將圖文消息群發出去,群發時微信會進行原創校驗,並返回群發操作結果;
  4. 在上述過程中,如果需要,還可以預覽圖文消息、查詢群發狀態,或刪除已群發的消息等。

群發圖片、文本等其他消息類型的過程如下:

  1. 如果是群發文本消息,則直接根據下面的接口說明進行群發即可;
  2. 如果是群發圖片、視頻等消息,則需要預先通過素材管理接口准備好 mediaID。

這一篇具體內容特別多,更多開發細節和注意事項請參考微信公眾號開發文檔【群發接口和原創校驗】仔細閱讀其他部分!!!

目錄【這是微信開發文檔提供的目錄,我們只演示部分重要的模塊!!!】

1 上傳圖文消息內的圖片獲取URL【訂閱號與服務號認證后均可用】

2 上傳圖文消息素材【訂閱號與服務號認證后均可用】

3 根據標簽進行群發【訂閱號與服務號認證后均可用】

4 根據OpenID列表群發【訂閱號不可用,服務號認證后可用】

5 刪除群發【訂閱號與服務號認證后均可用】

6 預覽接口【訂閱號與服務號認證后均可用】

7 查詢群發消息發送狀態【訂閱號與服務號認證后均可用】

8 事件推送群發結果

9 使用 clientmsgid 參數,避免重復推送

10 控制群發速度

一、上傳圖文消息內的圖片獲取URL【訂閱號與服務號認證后均可用】

 

請注意,本接口所上傳的圖片不占用公眾號的素材庫中圖片數量的5000個的限制。圖片僅支持jpg/png格式,大小必須在1MB以下。

接口調用請求說明

http請求方式: POST https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN 調用示例(使用curl命令,用FORM表單方式上傳一個圖片): curl -F media=@test.jpg "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN"

/**
     上傳圖文消息內的圖片獲取URL
     */
    public String uploadimg(String filePath) {

        String accessToken = accessTokenUtil.getAccessToken();
        if (accessToken != null) {
            String url = URIConstant.UPLOAD_IMG_URL.replace("ACCESS_TOKEN", accessToken);
            log.info("UPLOAD_IMG_URL:{}",url);

            //設置請求體,注意是LinkedMultiValueMap
            MultiValueMap<String, Object> data = new LinkedMultiValueMap<>();

            //設置上傳文件
            FileSystemResource fileSystemResource = new FileSystemResource(filePath);
            data.add("media", fileSystemResource);

            //上傳文件,設置請求頭
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
            httpHeaders.setContentLength(fileSystemResource.getFile().length());

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(data,
                    httpHeaders);
            try{
                //這里RestTemplate請求返回的字符串直接轉換成JSONObject會報異常,后續深入找一下原因
//                ResponseEntity<JSONObject> resultEntity = restTemplate.exchange(url,
//                        HttpMethod.POST, requestEntity, JSONObject.class);
                String resultJSON = restTemplate.postForObject(url, requestEntity, String.class);
                log.info("上傳返回的信息是:{}",resultJSON);
                return resultJSON;
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }
        return null;

    }

@ApiOperation(value = "上傳圖文消息內的圖片獲取URL")
@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
public Object uploadImg(String filePath) {

    String result = newsUtil.uploadimg(filePath);
    log.info("resut:{}",JSONObject.parseObject(result).toJSONString());
    return result;
}

我們在swagger中測試這個上傳圖文素材圖片接口,填寫一個正確的圖片路徑

結果如下

二、上傳圖文消息素材【訂閱號與服務號認證后均可用】

接口調用請求說明

http請求方式: POST https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN

POST數據說明

POST數據示例如下:

{
   "articles": [	 
        {
            "thumb_media_id":"qI6_Ze_6PtV7svjolgs-rN6stStuHIjs9_DidOHaj0Q-mwvBelOXCFZiq2OsIU-p",
            "author":"xxx",		
            "title":"Happy Day",		 
            "content_source_url":"www.qq.com",		
            "content":"content",		 
            "digest":"digest",
            "show_cover_pic":1,
            "need_open_comment":1,
            "only_fans_can_comment":1
        },	 
        {
            "thumb_media_id":"qI6_Ze_6PtV7svjolgs-rN6stStuHIjs9_DidOHaj0Q-mwvBelOXCFZiq2OsIU-p",
            "author":"xxx",		
            "title":"Happy Day",		 
            "content_source_url":"www.qq.com",		
            "content":"content",		 
            "digest":"digest",
            "show_cover_pic":0,
            "need_open_comment":1,
            "only_fans_can_comment":1
        }
   ]
}

 限於文章篇幅有限,字段詳細說明請自行參照開發文檔

 

package com.xu.wemall.pojo.news;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "新聞消息發送對象")
public class News {

    @ApiModelProperty(value = "標題")
    private String title;

    @ApiModelProperty(value = "圖文消息的封面圖片素材id(必須是永久 media_ID)")
    private String thumb_media_id;

    @ApiModelProperty(value = "作者")
    private String author;

    @ApiModelProperty(value = "圖文消息的摘要,僅有單圖文消息才有摘要,多圖文此處為空")
    private String digest;

    @ApiModelProperty(value = "是否顯示封面,0為false,即不顯示,1為true,即顯示")
    private Integer show_cover_pic;

    @ApiModelProperty(value = "圖文消息的具體內容,支持HTML標簽,必須少於2萬字符,小於1M,且此處會去除JS")
    private String content;

    @ApiModelProperty(value = "圖文消息的原文地址,即點擊“閱讀原文”后的URL")
    private String content_source_url;

    @ApiModelProperty(value = "是否打開評論,0不打開,1打開")
    private Integer need_open_comment;

    @ApiModelProperty(value = "是否粉絲才可評論,0所有人可評論,1粉絲才可評論")
    private Integer only_fans_can_comment;

}

 

package com.xu.wemall.pojo.news;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class Articles {

    List<News> articles; } 

 這里重點要說一下thumb_media_id這個參數,他是一個上傳永久圖片素材type是thumb獲得的media_id,,接口地址是

https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE

package com.xu.wemall.components.weixin;

import com.alibaba.fastjson.JSONObject;
import com.xu.wemall.commons.constants.URIConstant;
import com.xu.wemall.pojo.news.Articles;
import com.xu.wemall.pojo.news.News;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能:圖文素材工具類
 */
@Slf4j
@Component
public class NewsUtil {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private AccessTokenUtil accessTokenUtil;

    private Articles createArticles(){

        Articles articles = new Articles();

        List<News> dataList = new ArrayList<>();
        News  news1 = new News();
        news1.setTitle("標題");
        news1.setThumb_media_id("J49eq_VE823b_wZH3Op4DFkLa4Lm4jkTSxX_VbiBWhY");
        news1.setAuthor("作者");
        news1.setDigest("圖文消息的摘要,僅有單圖文消息才有摘要,多圖文此處為空。如果本字段為沒有填寫,則默認抓取正文前64個字。");
        news1.setShow_cover_pic(1);//顯示封面
        news1.setContent("圖文消息的具體內容,支持HTML標簽,必須少於2萬字符,小於1M,且此處會去除JS,涉及圖片url必須來源 \"上傳圖文消息內的圖片獲取URL\"接口獲取。外部圖片url將被過濾。");
        news1.setContent_source_url("https://www.baidu.com/");  //圖文消息的原文地址,即點擊“閱讀原文”后的URL
        news1.setNeed_open_comment(1);   //Uint32  是否打開評論,0不打開,1打開
        news1.setOnly_fans_can_comment(1);    //Uint32 是否粉絲才可評論,0所有人可評論,1粉絲才可評論


        News  news2 = new News();
        news2.setTitle("標題");
        news2.setThumb_media_id("J49eq_VE823b_wZH3Op4DOvK45tuhPJfr3n1_h1w1h8");
        news2.setAuthor("作者");
        news2.setDigest("圖文消息的摘要,僅有單圖文消息才有摘要,多圖文此處為空。如果本字段為沒有填寫,則默認抓取正文前64個字。");
        news2.setShow_cover_pic(1);//顯示封面
        news2.setContent("圖文消息的具體內容,支持HTML標簽,必須少於2萬字符,小於1M,且此處會去除JS,涉及圖片url必須來源 \"上傳圖文消息內的圖片獲取URL\"接口獲取。外部圖片url將被過濾。");
        news2.setContent_source_url("https://www.baidu.com/");  //圖文消息的原文地址,即點擊“閱讀原文”后的URL
        news2.setNeed_open_comment(1);   //Uint32  是否打開評論,0不打開,1打開
        news2.setOnly_fans_can_comment(1);    //Uint32 是否粉絲才可評論,0所有人可評論,1粉絲才可評論
        dataList.add(news1);
        dataList.add(news2);

        articles.setArticles(dataList);
        return articles;

    }
    /**
     *新增永久圖文素材
     */
    public String addNews() {

        Articles articles = this.createArticles();
        String accessToken = accessTokenUtil.getAccessToken();
        if (accessToken != null) {
            log.info("URL{}", URIConstant.ADD_NEWS_URL);
            String url = URIConstant.ADD_NEWS_URL.replace("ACCESS_TOKEN", accessToken);
            log.info("ADD_NEWS_URL:{}", url);

            //將菜單對象轉換成JSON字符串
            String jsonNews = JSONObject.toJSONString(articles);
            log.info("JSONNEWS:{}",jsonNews);

            //發起POST請求創建菜單
            String jsonObject = restTemplate.postForObject(url, jsonNews,String.class);

            return jsonObject;
        }
        return null;
    }

    /**
     *上傳圖文消息素材
     */
    public String uploadNews() {

        Articles articles = this.createArticles();
        String accessToken = accessTokenUtil.getAccessToken();
        if (accessToken != null) {
            log.info("URL{}", URIConstant.UPLOAD_NEWS_URL);
            String url = URIConstant.UPLOAD_NEWS_URL.replace("ACCESS_TOKEN", accessToken);
            log.info("UPLOAD_NEWS_URL:{}", url);

            //將菜單對象轉換成JSON字符串
            String jsonNews = JSONObject.toJSONString(articles);
            log.info("JSONNEWS:{}",jsonNews);

            //發起POST請求創建菜單
            String jsonObject = restTemplate.postForObject(url, jsonNews,String.class);

            return jsonObject;
        }
        return null;
    }

    /**
     上傳圖文消息內的圖片獲取URL
     */
    public String uploadimg(String filePath) {

        String accessToken = accessTokenUtil.getAccessToken();
        if (accessToken != null) {
            String url = URIConstant.UPLOAD_IMG_URL.replace("ACCESS_TOKEN", accessToken);
            log.info("UPLOAD_IMG_URL:{}",url);

            //設置請求體,注意是LinkedMultiValueMap
            MultiValueMap<String, Object> data = new LinkedMultiValueMap<>();

            //設置上傳文件
            FileSystemResource fileSystemResource = new FileSystemResource(filePath);
            data.add("media", fileSystemResource);

            //上傳文件,設置請求頭
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
            httpHeaders.setContentLength(fileSystemResource.getFile().length());

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(data,
                    httpHeaders);
            try{
                //這里RestTemplate請求返回的字符串直接轉換成JSONObject會報異常,后續深入找一下原因
//                ResponseEntity<JSONObject> resultEntity = restTemplate.exchange(url,
//                        HttpMethod.POST, requestEntity, JSONObject.class);
                String resultJSON = restTemplate.postForObject(url, requestEntity, String.class);
                log.info("上傳返回的信息是:{}",resultJSON);
                return resultJSON;
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }
        return null;

    }

}

我們在Controller中添加我們的方法 

 

package com.xu.wemall.controller.weixin;

import com.alibaba.fastjson.JSONObject;
import com.xu.wemall.components.weixin.NewsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 類名稱: NewsController
 * 類描述: 圖文素材接口
 */
@Slf4j
@RestController
@Api(tags = "圖文素材接口")
@RequestMapping(value = "/news")
public class NewsController {

    @Autowired
    private NewsUtil newsUtil;

    @ApiOperation(value = "上傳圖文素材")
    @RequestMapping(value = "/addNews", method = RequestMethod.POST)
    public Object addNews() throws Exception{

        String result = newsUtil.addNews();
        //log.info("resut:{}",JSONObject.parseObject(result).toJSONString());
        return result;
    }

    @ApiOperation(value = "上傳圖文消息素材")
    @RequestMapping(value = "/uploadNews", method = RequestMethod.POST)
    public Object uploadNews() throws Exception{

        String result = newsUtil.uploadNews();
        //log.info("resut:{}",JSONObject.parseObject(result).toJSONString());
        return result;
    }

    @ApiOperation(value = "上傳圖文消息內的圖片獲取URL")
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    public Object uploadImg(String filePath) {

        String result = newsUtil.uploadimg(filePath);
        log.info("resut:{}",JSONObject.parseObject(result).toJSONString());
        return result;
    }



}

打開swagger,測試一下我們的controller方法,我們先上傳幾個type=thumb的永久素材

獲得media_id后設置到我們的

最后上傳圖文消息素材

如果需要在群發圖文中插入小程序,則在調用上傳圖文消息素材接口時,需在content字段中添加小程序跳轉鏈接,有三種樣式的可供選擇,具體請仔細參考開發文檔【群發接口和原創校驗

今天的內容先到這里,我們下回再見!

如果您覺得此文有幫助,可以小小打賞一下,持續更新更有動力喲!


免責聲明!

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



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