最近产品经理要做每天推送图文信息的功能,哎,还要超链接传递不同的参数,苦逼呀。。网上查了一些资料,下面讲解一下群发素材
要群发素材,首先要先获得素材,素材都是以图片和文字的形式推送给用户的,所以要首先获得图片和文字
微信的上传媒体接口:https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE
可以用来上传图片,上传成功返回:{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789},其中media_id就是图片在微信服务器的标识。
上传方法:
///
/// 上传媒体返回媒体ID
///
public static string UploadMedia(string access_token, string type, string path)
{
// 设置参数
string url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", access_token, type);
return HttpRequestUtil.HttpUploadFile(url, path);
}
第二步:拼接图文消息素材Json字符串,其中msg就是上述的微信服务器传回来的媒体ID
///
/// 拼接图文消息素材Json字符串
///
public static string GetArticlesJsonStr(string access_token,string msg)
{
StringBuilder sbArticlesJson = new StringBuilder();
sbArticlesJson.Append("{\"articles\":[");
//string media_id = Tools.GetJsonValue(msg, "media_id");
// string media_id = (msg,"media_id");
sbArticlesJson.Append("{");
// sbArticlesJson.Append();
sbArticlesJson.Append("\"thumb_media_id\":\"" + msg + "\",");
sbArticlesJson.Append("\"author\":\"" + "王华涛" + "\",");
sbArticlesJson.Append("\"title\":\"" + "作业已经完成" + "\",");
sbArticlesJson.Append("\"content_source_url\":\"" + "http://。。。。" + "\",");
sbArticlesJson.Append("\"content\":\"" + "作业信息" + "\",");
sbArticlesJson.Append("\"digest\":\"" +"您孩子的作业已经完成" + "\",");
sbArticlesJson.Append("\"show_cover_pic\":\"1\"}");
sbArticlesJson.Append("]}");
return sbArticlesJson.ToString();
}
第三步:上传图文消息素材,其中postData就是拼接图文消息素材Json字符串,调用微信接口上传之后获得media_id
///
/// 上传图文消息素材返回media_id
///
public static string UploadNews(string access_token, string postData)
{
return HttpRequestUtil.PostUrl(string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}", access_token), postData);
}
第四步:图文消息json,添加发送用户openid
///
/// 图文消息json
///
public static string CreateNewsJson(string media_id, List openids)
{
StringBuilder sb = new StringBuilder();
sb.Append("{\"touser\":[\"");
foreach(string openid in openids)
{
sb.Append(openid);
sb.Append("\",\"");
}
sb.Append("\"],");
sb.Append("\"msgtype\":\"mpnews\",");
sb.Append("\"mpnews\":{\"media_id\":\"" + media_id + "\"}");
sb.Append("}");
return sb.ToString();
}
第五步:调用微信发送素材接口,根据OpenID列表群发素材信息
///
/// 根据OpenID列表群发
///
public static string Send(string access_token, string postData)
{
return HttpRequestUtil.PostUrl(string.Format("https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token={0}", access_token), postData);
}