我們在企業微信里創建自建應用時,有時候需要根據用戶的輸入內容反饋對應的素材信息的功能,這時候就需要用到上傳臨時素材的接口。通過此接口可以上傳臨時文件(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).執行程序及傳入控制台程序的參數(我這里是存放素材的路徑)