.net微信--素材上傳

wangwenrui40發表於2020-10-21

不解釋了,會一點微信開發,分析下程式碼就會了

using Abp.Authorization;
using Microsoft.AspNetCore.Mvc;
using MkGzhh.Authorization;
using MkGzhh.Wechat.Dto;
using MkGzhh.Wechat.ReturnDto;
using MkGzhh.Wechat.WechatMessages;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace MkGzhh.Wechat
{

    /// <summary>
    /// 微信素材管理
    /// </summary>
    [AbpAuthorize(PermissionNames.weChatmaterial)]
    public class WechatMaterialService : MkGzhhAppServiceBase, IWechatMaterialService
    {
        public string urlname { get; set; }
        /// <summary>
        /// http協議
        /// </summary>
        HttpClient httpClient = new HttpClient();

        private readonly IWechatUserTagService _wechatUserTagService;
        /// <summary>
        /// 依賴注入
        /// </summary>
        /// <param name="wechatUserTagService"></param>
        public WechatMaterialService(IWechatUserTagService wechatUserTagService)
        {
            _wechatUserTagService = wechatUserTagService;
        }

        /// <summary>
        /// 得到ACCESS_TOKEN
        /// </summary>
        /// <returns></returns>
        private async Task<string> GetACCESS_TOKEN()
        {
            var getParameter = await _wechatUserTagService.GetACCESS_TOKEN();
            return getParameter;
        }

        /// <summary>
        /// 新增素材。臨時素材的有效時間為3天
        /// imgurl為 伺服器檔案的物理路徑,可用Request.MapPath將虛擬路徑轉換為物理路徑。也可為網路路徑,如:http://XXXX
        /// </summary>
        /// <param name="imgurl"></param>
        /// <param name="urlname">檔案的名字(如果不傳就預設為地址的名字,當vue的檔案上傳控制元件會出錯)</param>
        /// <param name="IsTemp">是否為臨時素材 只有永久輸出會在平臺展示</param>
        /// <param name="videotitle">視訊標題</param>
        /// <param name="mediaType">image 圖片(image)格式語音(voice)視訊(video):10MB,支援MP4格式縮圖(thumb):64KB,支援JPG格式,圖文(news)</param>
        /// <param name="videointroduction">視訊描述</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JObject> UpdateMaterial(string imgurl, string urlname, string mediaType, bool IsTemp, string videotitle = "", string videointroduction = "")
        {
            this.urlname = urlname;
            string url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}";
            if (!IsTemp)
            {
                //永久素材介面
                url = "http://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}";
            }
            //把內容存進表單
            var formlist = new List<FormEntity>
                {
                    new FormEntity {IsFile = true, Name = "media",  Value = imgurl}
                };

            //如果是視訊型別就做特殊處理
            if (mediaType == "video" && !IsTemp)
            {
                //新增視訊素材的特殊處理 就是加 標題和描述2個引數列
                var value = JsonConvert.SerializeObject(new { title = videotitle, introduction = videointroduction });
                //加進資料表單
                formlist.Add(new FormEntity { IsFile = false, Name = "description", Value = value });
            }

            var accessToken = await GetACCESS_TOKEN();
            string filename = imgurl;
            var set = PostResult(formlist, string.Format(url, accessToken, mediaType.ToString()));
            return set;

        }

        /// <summary>
        /// 獲取臨時素材的url
        /// </summary>
        /// <param name="mediaId">素材ID</param>
        /// <returns>url</returns>
        public async Task<string> GetTempUrlAsync(string mediaId)
        {
            string accessToken = await GetACCESS_TOKEN();
            var url = "http://api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}";
            var upload = string.Format(url, accessToken, mediaId);
            return upload;
        }

        /// <summary>
        /// 獲取永久素材的url
        /// </summary>
        /// <param name="mediaId">素材ID</param>
        /// <param name="stream"></param>
        /// <returns>url</returns>
        public async Task<JObject> GetperpetualUrlAsync(mediaIdDto mediaId)
        {
            string accessToken = await GetACCESS_TOKEN();
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/material/get_material?access_token={0}", accessToken);
            //序列化為json
            var myContent = JsonConvert.SerializeObject(mediaId);
            var byteContent = new StringContent(myContent);
            var getParameter = await httpClient.PostAsync(url, byteContent);
            var retdata = await getParameter.Content.ReadAsStringAsync();
            JObject jb = (JObject)JsonConvert.DeserializeObject(retdata);
            return jb;

        }

        public async Task<JObject> GetnewUrlAsync(mediaIdDto mediaId)
        {
            var access_token = await GetACCESS_TOKEN();
            //序列化為json
            var myContent = JsonConvert.SerializeObject(mediaId);
            var byteContent = new StringContent(myContent);
            //傳送
            var getParameter = await httpClient.PostAsync("https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" + access_token, byteContent);
            //傳送後返回的內容
            var magess = await getParameter.Content.ReadAsStringAsync();
            JObject jb = (JObject)JsonConvert.DeserializeObject(magess);
            return jb;

        }
        /// <summary>
        /// 新增永久圖文素材
        /// </summary>
        /// <param name="articles"></param>
        /// <returns></returns>
        public async Task<JObject> AddArticleAsync(Article2Dto articles)
        {
            var access_token = await GetACCESS_TOKEN();
            //序列化為json
            var myContent = JsonConvert.SerializeObject(articles);
            var byteContent = new StringContent(myContent);
            //傳送
            var getParameter = await httpClient.PostAsync("https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=" + access_token, byteContent);
            //傳送後返回的內容
            var magess = await getParameter.Content.ReadAsStringAsync();
            JObject jb = (JObject)JsonConvert.DeserializeObject(magess);
            return jb;
        }
        /// <summary>
        /// 獲取素材總數
        /// </summary>
        /// <returns></returns>
        public async Task<JObject> GetAllMaterialCount()
        {

            var access_token = await GetACCESS_TOKEN();
            var getParameter = await httpClient.GetStringAsync("https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=" + access_token);
            JObject jb = (JObject)JsonConvert.DeserializeObject(getParameter);
            return jb;

        }

        /// <summary>
        /// 獲取素材列表
        /// </summary>
        /// <param name="Magess"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JObject> GetMaterialList(GetMaterialListDto Magess)
        {
            var access_token = await GetACCESS_TOKEN();
            //序列化為json
            var myContent = JsonConvert.SerializeObject(Magess);
            var byteContent = new StringContent(myContent);
            //傳送
            var getParameter = await httpClient.PostAsync("https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + access_token, byteContent);
            //傳送後返回的內容
            var magess = await getParameter.Content.ReadAsStringAsync();
            JObject jb = (JObject)JsonConvert.DeserializeObject(magess);
            return jb;
        }
        /// <summary>
        /// 刪除永久性素材
        /// </summary>
        /// <param name="Magess">永久素材的ID</param>
        /// <returns></returns>
        public async Task<JObject> DelMaterial(DelMaterialDto Magess)
        {
            var access_token = await GetACCESS_TOKEN();
            //序列化為json
            var myContent = JsonConvert.SerializeObject(Magess);
            var byteContent = new StringContent(myContent);
            //傳送
            var getParameter = await httpClient.PostAsync("https://api.weixin.qq.com/cgi-bin/material/del_material?access_token=" + access_token, byteContent);
            //傳送後返回的內容
            var magess = await getParameter.Content.ReadAsStringAsync();
            JObject jb = (JObject)JsonConvert.DeserializeObject(magess);
            return jb;

        }


        //--------------------------------------------

        /// <summary>
        /// 發起post請求,並獲取請求返回值
        /// </summary>
        /// <typeparam name="T">返回值型別</typeparam>
        /// <param name="formEntities"></param>
        /// <param name="url">介面地址</param>
        public JObject PostResult(List<FormEntity> formEntities, string url)
        {
            var retdata = HttpPostForm(url, formEntities);
            JObject jb = (JObject)JsonConvert.DeserializeObject(retdata);
            return jb;
        }

        /// <summary>
        /// 解析地址表單
        /// </summary>
        /// <param name="url"></param>
        /// <param name="formEntities"></param>
        /// <returns></returns>
        public string HttpPostForm(string url, List<FormEntity> formEntities)
        {
            //分割字串
            var boundary = "----" + DateTime.Now.Ticks.ToString("x");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((a, b, c, d) => true);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            MemoryStream stream = new MemoryStream();
            #region 將非檔案表單寫入到記憶體流中
            foreach (var entity in formEntities.Where(f => f.IsFile == false))
            {
                var temp = new StringBuilder();
                temp.AppendFormat("\r\n--{0}", boundary);
                temp.AppendFormat("\r\nContent-Disposition: form-data; name=\"{0}\"", entity.Name);
                temp.Append("\r\n\r\n");
                temp.Append(entity.Value);
                byte[] b = Encoding.UTF8.GetBytes(temp.ToString());
                stream.Write(b, 0, b.Length);
            }
            #endregion
            #region 將檔案表單寫入到記憶體流
            foreach (var entity in formEntities.Where(f => f.IsFile == true))
            {
                byte[] filedata = null;
                //+".jpg"

                var filename = Path.GetFileName(entity.Value);
                if (this.urlname != null)
                {
                    filename = this.urlname;
                }
                //表示是網路資源
                if (entity.Value.Contains("http"))
                {
                    //處理網路檔案 ,就是通過 DownloadData 這個方法把,連線的流資料讀出來
                    using (var client = new WebClient())
                    {
                        filedata = client.DownloadData(entity.Value);

                    }
                }
                else
                {
                    //處理物理路徑檔案
                    using (FileStream file = new FileStream(entity.Value, FileMode.Open, FileAccess.Read))
                    {

                        filedata = new byte[file.Length];
                        file.Read(filedata, 0, (int)file.Length);
                    }
                }
                var temp = string.Format("\r\n--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\n\r\n",
                   boundary, entity.Name, filename);
                byte[] b = Encoding.UTF8.GetBytes(temp);
                stream.Write(b, 0, b.Length);
                stream.Write(filedata, 0, filedata.Length);
            }
            #endregion
            //結束標記
            byte[] foot_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
            stream.Write(foot_data, 0, foot_data.Length);
            Stream reqStream = request.GetRequestStream();
            stream.Position = 0L;
            //將Form表單生成流寫入到請求流中
            stream.CopyTo(reqStream);
            stream.Close();
            reqStream.Close();
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();//獲取響應
                }
            }
        }

        /// <summary>
        /// HTTP POST請求URL。
        /// </summary>
        /// <param name="url">請求的url</param>
        /// <param name="param">請求的引數</param>
        /// <param name="stream">如果響應的是檔案,則此參數列示的是檔案流</param>
        public static string HttpPost(string url, string param, out FileStreamInfo stream)
        {
            stream = null;
            //當請求為https時,驗證伺服器證書
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((a, b, c, d) => { return true; });
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;
            string responseStr = "";
            using (StreamWriter requestStream = new StreamWriter(request.GetRequestStream()))
            {
                requestStream.Write(param);//將請求的資料寫入到請求流中
            }
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {

                if (response.ContentType == "application/octet-stream")//如果響應的是檔案流,則不將響應流轉換成字串
                {
                    stream = new FileStreamInfo();
                    response.GetResponseStream().CopyTo(stream);
                    #region 獲取響應的檔名
                    Regex reg = new Regex(@"(\w+)\.(\w+)");
                    var result = reg.Match(response.GetResponseHeader("Content-disposition")).Groups;
                    stream.FileName = result[0].Value;
                    #endregion
                    responseStr = "";
                }
                else
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        responseStr = reader.ReadToEnd();//獲取響應
                    }
                }

            }
            return responseStr;
        }




    }
}

 

相關文章