永久图文素材代码

永久图文素材代码C#新增永久图文素材新增永久图文素材接口调用请求说明http请求方式: POST,https协议 https://api.weixin..c

大家好,欢迎来到IT知识分享网。

C#新增永久图文素材
新增永久图文素材
接口调用请求说明
http请求方式: POST,https协议 https://api.weixin..com/cgi-bin/material/add_news?access_token=ACCESS_TOKEN
//同步公众号素材
                    JavaScriptSerializer Jss = new JavaScriptSerializer();
                    string respText = cwebcms.Web.user.BasicApi.WebRequestPostOrGet(string.Format("https://api.weixin..com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppID, AppSecret), "");
                    Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);
                    string accessToken = respDic["access_token"].ToString();
                    //上传封面图片获取media_id
                    string ssPath = Server.MapPath(uc.PicURL);
                    string re = cwebcms.Common.Public.add_material("image/jpeg", ssPath, accessToken);
                    string thumb_media_id = "";
                    respDic = (Dictionary<string, object>)Jss.DeserializeObject(re);
                    if (respDic.ContainsKey("media_id"))
                    {
                        thumb_media_id = respDic["media_id"].ToString();
                    }

                    cwebcms.Common.Public.saveLogFiles(5, "re" + re, "errmsg:", "thumb_media_id:" + thumb_media_id);
                    //上传图文消息内的图片获取URL
//替换内容区的所有图片为素材中的图片
                    string content = uc.Content;
                    string pattern = "\\<img\\ [\\s\\S]*?src=['\"]?(?<f>[^'\"\\>\\ ]+)['\"\\>\\ ]";
                    Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    Match match = reg.Match(content);
                    string gPicURL = "", img_url = "";
                    int Picnumj = 1;
                    while (match.Success)
                    {
                        gPicURL = match.Groups["f"].Value;
                        ssPath = Server.MapPath(gPicURL);
                        re = cwebcms.Common.Public.uploadimg(ssPath, accessToken);
                        respDic = (Dictionary<string, object>)Jss.DeserializeObject(re);
                        if (respDic.ContainsKey("url"))
                        {
                            img_url = respDic["url"].ToString();
                        }
                        content = content.Replace(gPicURL, img_url);
                        Picnumj++;
                        match = match.NextMatch();
                    }

                    string url = "https://api.weixin..com/cgi-bin/material/add_news?access_token=" + accessToken;
                    string str = "{" +
                                "\"articles\": [{" +
                                 "\"title\": \"" + uc.NewsTitle + "\"," +
                                "\"thumb_media_id\": \"" + thumb_media_id + "\"," +
                                "\"author\": \"" + uc.Author + "\"," +
                                "\"digest\": \"" + uc.naviContent + "\"," +
                                "\"show_cover_pic\": 1," +
                                "\"content\": \"" + content.Replace("\"", "\'") + "\"," +
                                "\"content_source_url\": \"https://ft.cwebcrm.cn/mmg/user/view_detail.html?companyid=gzh&id=" + uc.ID + "\"," +
                                "\"need_open_comment\":1," +
                                "\"only_fans_can_comment\":1" +
                                "\"}," +
                                //若新增的是多图文素材,则此处应还有几段articles结构
                                "\"]" +
                                "\"}        ";


                    cwebcms.Common.Public.saveLogFiles(5, "@url" + url, "errmsg:", "str:" + str);核心代码
                    string media_id = "";
                    string strReturn = cwebcms.Common.Public.PostUrl(@url, str);
                    cwebcms.Common.Public.saveLogFiles(5, "n", "", "strReturn:" + strReturn);
                    respDic = (Dictionary<string, object>)Jss.DeserializeObject(strReturn);
                    if (respDic.ContainsKey("media_id"))
                    {
                        media_id = respDic["media_id"].ToString();
                    }
                    string sql = "update cwebcms_news set media_id='" + media_id + "' where NewsID='" + uc.NewsID + "'";
                    int n = sd.updatesql(sql); 
//上传封面图片
上传图文消息内的图片获取URL
本接口所上传的图片不占用公众号的素材库中图片数量的100000个的限制。图片仅支持jpg/png格式,大小必须在1MB以下。
接口调用请求说明
http请求方式: POST,https协议 https://api.weixin..com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN 调用示例(使用curl命令,用FORM表单方式上传一个图片): curl -F media=@test.jpg "https://api.weixin..com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN"
public static  string uploadimg(string file,string accessToken)
        {
            string fileName = file;
            string url = string.Format("https://api.weixin..com/cgi-bin/media/uploadimg?access_token={0}", accessToken);
            FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Read);
            byte[] fileByte = new byte[fs.Length];
            fs.Read(fileByte, 0, fileByte.Length);
            fs.Close();
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            string boundary = DateTime.Now.Ticks.ToString("X"); // 隨機分隔線
            request.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");
            //请求头部信息
            StringBuilder sbHeader =
                new StringBuilder(
                    string.Format(
                        "Content-Disposition:form-data;name=\"media\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n",
                        fileName));
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            postStream.Write(fileByte, 0, fileByte.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            postStream.Close();
 
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            string content = sr.ReadToEnd();
            return content;
        }
新增其他类型永久素材(注意视频接口不可用,上传也不审核)
接口调用请求说明
通过POST表单来调用接口,表单id为media,包含需要上传的素材内容,有filename、filelength、content-type等信息。请注意:图片素材将进入公众平台官网素材管理模块中的默认分组。
http请求方式: POST,需使用https https://api.weixin..com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE 调用示例(使用curl命令,用FORM表单方式新增一个其他类型的永久素材,curl命令的使用请自行查阅资料)

public static string add_material(string type, string file,  string accessToken)
        {
            string fileName = file;
            string url = string.Format("https://api.weixin..com/cgi-bin/material/add_material?access_token={0}&type={1}", accessToken, type);
            FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Read);
            byte[] fileByte = new byte[fs.Length];
            fs.Read(fileByte, 0, fileByte.Length);
            fs.Close();
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            string boundary = DateTime.Now.Ticks.ToString("X"); // 隨機分隔線
            request.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");
            //请求头部信息
            StringBuilder sbHeader =
                new StringBuilder(
                    string.Format(
                        "Content-Disposition:form-data;name=\"media\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n",
                        fileName));
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            postStream.Write(fileByte, 0, fileByte.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            postStream.Close();

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            string content = sr.ReadToEnd();
            return content;
        }
//
public static string PostUrl(string url, string postData)
        {
            string result = "";

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.Method = "POST";

            req.Timeout = 5000;//设置请求超时时间,单位为毫秒

            req.ContentType = "application/json";

            byte[] data = Encoding.UTF8.GetBytes(postData);

            req.ContentLength = data.Length;

            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);

                reqStream.Close();
            }

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            Stream stream = resp.GetResponseStream();

            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }

            return result;
        }

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/50550.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信