微信公众号发送图文消息
简单介绍一下:群发图文消息分为三步:先上传图片获得图片的id,再上传图文素材获得Id,最后把素材Id群发给目标
参考本文建议结合微信官方文档:
点击进入微信官方文档.
1.上传图片
/**
* 上传图片
* @param file 图片文件
* @return
*/
@RequestMapping("uoloadimage")
public String uploadMedia() {
//获取微信公众号access_token
String token = WeChatUtils.getAccessToken();
String type = "image";
File file = new File("C:\\Users\\zhangyue\\Pictures\\u=3277802382,3438848628&fm=11&gp=0.jpg");
//图片上传到微信服务器地址
String url = "https://api.weixin.qq.com/cgi-bin/media/upload";
com.alibaba.fastjson.JSONObject jsonObject = null;
//使用post方式上传
PostMethod post = new PostMethod(url);
post.setRequestHeader("Connection", "Keep-Alive");
post.setRequestHeader("Cache-Control", "no-cache");
FilePart media;
HttpClient httpClient = new HttpClient();
//信任任何类型的证书
Protocol myhttps = new Protocol("https", new SSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", myhttps);
try {
media = new FilePart("media", file);
Part[] parts = new Part[]{new StringPart("access_token", token),
new StringPart("type", type), media};
MultipartRequestEntity entity = new MultipartRequestEntity(parts,
post.getParams());
post.setRequestEntity(entity);
int status = httpClient.executeMethod(post);
if (status == HttpStatus.SC_OK) {
String text = post.getResponseBodyAsString();
jsonObject = com.alibaba.fastjson.JSONObject.parseObject(text);
} else {
System.out.println("upload Media failure status is:" + status);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String media_id = jsonObject.get("media_id").toString();
System.out.println("media_id=" + media_id);
return media_id;
}
也可以把要传的图片写在参数里,像这样:
注意:
1、access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。获取方法见下文
2、type支持四种类型素材,分别是:video、image、voice、thumb
3、返回的media_id 是下一步需要的图片Id。
附上官方文档说明及参数说明:
2.上传素材
/**
* 上传图文消息素材
* @param articleParamVo
*/
@RequestMapping("uploadnews")
public void uploadnews(ArticleParamVo articleParamVo) {
//图文素材参数封装成实体类
ArticleParamVo paramVo = new ArticleParamVo();
paramVo = articleParamVo;
List<ArticleParamVo> paramVos = new ArrayList<ArticleParamVo>();
paramVos.add(paramVo);
System.out.println(paramVos);
//使用json格式上传微信接口
JSONObject js = new JSONObject();
js.put("articles", paramVos);
String jsstring = js.toString();
//微信接口地址,需要拼接上accesstoken
String url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN".replaceAll("ACCESS_TOKEN", WeChatUtils.getAccessToken());
System.out.println(jsstring);
String httpsResponse = doTemplateMsgPost(url, jsstring);
System.out.println(httpsResponse);
//JSONObject newsjs = JSONObject.fromObject(httpsResponse);
//方式2
Gson gson = new Gson();
String json = gson.toJson(httpsResponse);
//String newsmedia = newsjs.getString("media_id");
}
附上官方文档说明:
- 群发
/**
* 上传的图文素材群发
* @param mediaId 媒体id,第二部返回的媒体id
*/
@RequestMapping("sendall")
public void sendall(String mediaId) {
//封装成json格式
JSONObject j1 = new JSONObject();
JSONObject j11 = new JSONObject();
JSONObject j21 = new JSONObject();
j11.put("is_to_all", true);
j21.put("media_id", mediaId);
j1.put("filter", j11);
j1.put("mpnews", j21);
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", WeChatUtils.getAccessToken());
//信息推送给微信接口,具体方法详见下文
String httpsResponse = doTemplateMsgPost(url, j1.toString());
System.out.println(httpsResponse);
}
附上官方文档说明及参数说明:
如果你想给具体的目标发送需要使用这种形式,此处方法不在说明
特别注意:
只有实名认证过的才能发送成功,遇到错误直接百度,流程是没问题的,错误可能是自己的参数或者自己公众号的问题,测试公众号没法用,如果你想看效果可以把第三步换成预览的方法,预览方法如下
/**
* 推送预览
*/
@RequestMapping("preview")
public void preview() {
String j = "{\n" +
" \"touser\": \"o7hfJw8sh3k8ZlXZ_KJmiRG-reJ8\", \n" +
" \"mpnews\": {\n" +
" \"media_id\": \"YkKBvc8I4ZKVCV4judwuoS-8QH2HRW77GIUhX_FEboCfyJs-T0Akn9bryS9FeYY9\"\n" +
" }, \n" +
" \"msgtype\": \"mpnews\"\n" +
"}";
String url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", WeChatUtils.getAccessToken());
String httpsResponse = doTemplateMsgPost(url, j);
System.out.println(httpsResponse
}
附上官方文档及参数说明:
- 使用到的工具方法
- 获取token
/**
* 获取access_token的接口地址
*/
public static final String GET_ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
/**
* 发送模板消息的接口
*/
public static final String SEND_TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
/**
* 缓存的access_token
*/
private static String accessToken;
/**
* access_token的失效时间
*/
private static long expiresTime;
/**
* 获取accessToken
* @return
*/
public static String getAccessToken(){
//判断accessToken是否已经过期,如果过期需要重新获取
if(accessToken==null||expiresTime < System.currentTimeMillis()){
//发起请求获取accessToken
String result = HttpClientUtil.doGet(GET_ACCESSTOKEN_URL.replace("APPID", APPID).replace("APPSECRET", SECRET));
JSONObject json = JSONObject.parseObject(result);
//缓存accessToken
accessToken = json.getString("access_token");
//设置accessToken的失效时间
long expires_in = json.getLong("expires_in");
//失效时间 = 当前时间 + 有效期(提前一分钟)
expiresTime = System.currentTimeMillis()+ (expires_in-60) * 1000;
}
return accessToken;
}
- 上传图文消息参数实体类封装
@Data
public class ArticleParamVo {
/**图文消息的封面图片素材id*/
private String thumb_media_id;
/**标题*/
private String author;
/**Uint32 是否粉丝才可评论,0所有人可评论,1粉丝才可评论*/
private String only_fans_can_comment;
/**图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空。如果本字段为没有填写,则默认抓取正文前64个字*/
private String digest;
/**是否显示封面,0为false,即不显示,1为true,即显示*/
private String show_cover_pic;
/**图文消息的原文地址,即点击“阅读原文”后的URL*/
private String content_source_url;
/**Uint32 是否打开评论,0不打开,1打开*/
private String need_open_comment;
/**标题*/
private String title;
/**图文消息的具体内容,涉及图片url必须来源 "上传图文消息内的图片获取URL"接口获取*/
private String content;
}
- 消息推送方法
/**
* 发送模板消息的方法
*
* @param templateMsgUrl
* @param paramStr
* @return
*/
public String doTemplateMsgPost(String templateMsgUrl, String paramStr) {
String res = null;
URL url = null;
try {
url = new URL(templateMsgUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
if (null != paramStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(paramStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
conn.disconnect();
res = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
- 查看效果