企业微信接口上传临时素材
我们在企业微信里创建自建应用时,有时候需要根据用户的输入内容反馈对应的素材信息的功能,这时候就需要用到上传临时素材的接口。通过此接口可以上传临时文件(3天有效期),再配合自建应用就可以推送素材内容给用户。
上传临时素材接口文档:https://developer.work.weixin.qq.com/document/path/90253,下面是测试通过的上传临时素材的完整代码:
string corpId = "xxx"; //去企业微信后台管理页面获取
string corpsecret = "xxx"; //去企业微信后台管理页面获取
string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + corpsecret;
string reval = HttpUtil.GetData(url);
JavaScriptSerializer js = new JavaScriptSerializer();
dynamic temp = js.Deserialize<dynamic>(reval);
string access_token = temp["access_token"]; //获得access_token
Console.WriteLine(access_token);
string postUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type=file";
string filePath = string.Empty;
//控制台传参,传入素材文件夹的路径,循环遍历文件夹中所有的素材文件,作用是更新文件media_id
string dir = args[0];
string[] dirFiles = Directory.GetFiles(dir);
for (int i = 0; i < dirFiles.Length; i++)
{
filePath = dirFiles[i];
string name = Path.GetFileName(filePath);
using (FileStream fs = File.OpenRead(filePath))
{
byte[] bs = new byte[fs.Length];
fs.Read(bs, 0, bs.Length);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(postUrl);
CookieContainer cookieContainer = new CookieContainer();
req.CookieContainer = cookieContainer;
req.AllowAutoRedirect = true;
req.Method = "POST";
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
req.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
string fileName = Path.GetFileName(filePath);
//请求头部信息
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"media\";filename=\"{0}\";filelength=" + bs.Length + "\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
string responseData = String.Empty;
//请求
using (Stream postStream = req.GetRequestStream())
{
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(bs, 0, bs.Length);
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
}
//响应
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
responseData = reader.ReadToEnd();
}
}
Console.WriteLine(responseData);
//反序列化json获得媒体文件id
ReturnData data = (ReturnData)js.Deserialize<ReturnData>(responseData);
string media_id = data.media_id; //获得更新的media_id
//此处省略数据库更新记录代码...
}
}
但是要注意,临时素材有效期只有3天,所以需要做个计划任务定期的更新media_id。
计划任务的创建:
1).每隔3天执行一次
2).执行程序及传入控制台程序的参数(我这里是存放素材的路径)