赞
踩
既上次介绍了如何通过.net core控制台应用一键发布公众号消息后,这次来介绍一下,如何通过.net core 控制台应用一键发布视频内容至抖音,可以作为第三方分享内容至抖音的服务端方法参考,官方的示例没有提供C#的代码,并且文档也超级坑,api设计也很不友好,返回的错误码并不能真正反映问题所在,总之就是不够restful。。。这个坑我觉得比微信的文档还大。。废话不多说,开始吧
这里我就不多介绍了,参考这一篇博客:https://blog.csdn.net/I_lost/article/details/104520655,注意将授权回调域设置好
随便说点,代码中的注释已经够清楚了。
强调一下,请求地址:https://open.douyin.com/platform/oauth/connect/
里面配置query的部分只需要注意:回调地址即redirect_uri需要在应用的配置的授权域名下,其他没啥了。。都很简单,我这里是控制台应用,会调用本地浏览器打开抖音扫码界面
- private string GetDouYinCode()
- {
- Dictionary<string, string> requestParameters = new Dictionary<string, string>();
- //这里的client_key以及client_secret需要自己到开发者平台去开通一个应用得到
- requestParameters.Add("client_key", "client_key");
- requestParameters.Add("response_type", "code");
- requestParameters.Add("scope", "video.create");
- //redirect_uri 回调的地址,需要在开发者平台配置这个地址
- requestParameters.Add("redirect_uri", "http://ccciie.com/eyuntong/(S(amksryslevropj3ib0nl0jha))/Default.aspx?id=V2.0");
- string requestUrl = "https://open.douyin.com/platform/oauth/connect/";
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.Append(requestUrl);
-
- if (requestParameters.Count > 0)
- {
- stringBuilder.Append("?");
- foreach (var item in requestParameters)
- {
- stringBuilder.Append("&");
- stringBuilder.AppendFormat("{0}={1}", item.Key, item.Value);
- }
- }
- string codeRequest = stringBuilder.ToString();
- Console.WriteLine(codeRequest);
-
- // 控制台打开浏览器或者web 中打开新的窗口进行扫码跳转,等待用户输入code
-
- //将跳转后UTL的“code=“到”&“之间的字符复制下来,如下:6yNlI4Xu1Rc923iBNTvzQAsvK00nnie8yiTJ
- //https://www.a9blmo3lvm.54http.tech/?code=6yNlI4Xu1Rc923iBNTvzQAsvK00nnie8yiTJ&state=
-
- string code = OpenBrowerInputCode(codeRequest);
- return code;
- }
- private string OpenBrowerInputCode(string codeRequest)
- {
- // 控制台打开浏览器窗口或者web 跳转到新的页面, 地址是:codeRequest
- // 我这里因为是控制台应用,就用了System.Diagnostics.Process()方法,web中弄个a标签跳转到codeRequest这个地址即可,
- System.Diagnostics.Process.Start(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", codeRequest);
-
- //用户将这个code复制下来,作为GetDouYinAcessToken(code)的传入参数
- //扫码跳转后的地址示例:https://www.a9blmo3lvm.54http.tech/?code=6yNlI4Xu1Rc923iBNTvzQAsvK00nnie8yiTJ&state=
-
- string code = Console.ReadLine();
- if (!string.IsNullOrWhiteSpace(code))
- {
- return code;
- }
- return new Exception("code不能为空").ToString();
- }
等待用户扫码跳转确认,确认后将代码中所说的code复制到控制台中,等待执行下一步
简单说一下,这里对通过服务端方法对https://open.douyin.com/oauth/access_token/发起请求,最后将返回的open_id以及access_token取出来,用作下一步的进行视频上传的接口的参数
- private void GetDouYinAcessToken(string code)
- {
- Dictionary<string, string> requestParameters = new Dictionary<string, string>();
- requestParameters.Add("client_key", "client_key");
- requestParameters.Add("client_secret", "client_secret");
- requestParameters.Add("code", code);
- requestParameters.Add("grant_type", "authorization_code");
- string requestUrl = "https://open.douyin.com/oauth/access_token/";
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.Append(requestUrl);
-
- if (requestParameters.Count > 0)
- {
- stringBuilder.Append("?");
- foreach (var item in requestParameters)
- {
- stringBuilder.Append("&");
- stringBuilder.AppendFormat("{0}={1}", item.Key, item.Value);
- }
- }
- HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(stringBuilder.ToString());
- httpWebRequest.ContentType = "application/json";
- httpWebRequest.Method = "GET";
- httpWebRequest.Timeout = 20000;
-
- HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
- StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
- string responseContent = streamReader.ReadToEnd();
- JObject jsonresult = JsonConvert.DeserializeObject<JObject>(responseContent);
-
- if (jsonresult["data"]["access_token"] != null && jsonresult["data"]["open_id"] != null)
- {
- AcessToken = jsonresult["data"]["access_token"].ToString();
- OpenId = jsonresult["data"]["open_id"].ToString();
- }
-
- streamReader.Close();
- httpWebResponse.Close();
- httpWebRequest.Abort();
- //return jsonresult;
- }
这里是最坑的地方。。。文档很坑,并且对于C#一点也不友好,我调试了很久,才最终上传成功。
- /// <summary>
- /// 视频上传方法
- /// </summary>
- /// <param name="path">视频文件路径,视频大小不能超过128M,时长不能超过15分钟</param>
- /// <param name="videoTitle">视频的标题</param>
- /// <returns></returns>
- private JObject UploadVideoToDouYin(string path, string videoTitle)
- {
- FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
- byte[] bArr = new byte[fs.Length];
- fs.Read(bArr, 0, bArr.Length);
- string url = string.Format("https://open.douyin.com/video/upload/?open_id={1}&access_token={0}", AcessToken, OpenId);
- HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
- //httpWebRequest.AllowAutoRedirect = true;
- httpWebRequest.Method = "POST";
- httpWebRequest.Timeout = 20000;
- string boundary = DateTime.Now.Ticks.ToString("X");
-
- httpWebRequest.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");
-
- int pos = path.LastIndexOf("\\");
- string fileName = path.Substring(pos + 1);
-
- //组织表单数据
- StringBuilder sbHeader = new StringBuilder();
- sbHeader.Append("Content-Disposition: form-data; name=\"video\"; filename=\"" + path + "\"; filelength=\"" + fs.Length + "\"");
- sbHeader.Append("\r\n");
- //其他视频格式需要修改Content-Type:video/mp4; 格式必须是”video/“开头
- sbHeader.Append("Content-Type:video/mp4;");
- sbHeader.Append("\r\n\r\n");
-
- byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
- Stream postStream = httpWebRequest.GetRequestStream();
-
- postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
- postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
- postStream.Write(bArr, 0, bArr.Length);
- postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
- postStream.Close();
-
- fs.Close();
- fs.Dispose();
-
- HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
- StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
- string responseContent = streamReader.ReadToEnd();
- JObject jsonresult = JsonConvert.DeserializeObject<JObject>(responseContent);
- streamReader.Close();
- httpWebResponse.Close();
- httpWebRequest.Abort();
- if (jsonresult["data"]["video"]["video_id"] != null)
- {
- VideoId = jsonresult["data"]["video"]["video_id"].ToString();
- Console.WriteLine(VideoId);
- CrateVideoForDouYin(videoTitle);
- }
-
- return jsonresult;
- }
到这就没啥问题了,直接参考官方文档,对内容做相应的配置即可。
- private JObject CrateVideoForDouYin(string videoTitle)
- {
- //发送视频的的标题,不支持艾特某个用户
- string videoContext = @"{""text"":""测试视频:人生的意义在于旅行"",""video_id"":""""}";
- JObject requsetToken = JsonConvert.DeserializeObject<JObject>(videoContext);
- requsetToken["text"] = videoTitle;
- requsetToken["video_id"] = VideoId;
- string requestUrl = string.Format("https://open.douyin.com/video/create/?open_id={0}&access_token={1}", OpenId, AcessToken);
- HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
- httpWebRequest.ContentType = "application/json";
- httpWebRequest.Method = "POST";
- httpWebRequest.Timeout = 10000;
-
- Console.WriteLine("请求的参数为\n" + requsetToken);
- byte[] plcByte = Encoding.UTF8.GetBytes(requsetToken.ToString());
- httpWebRequest.ContentLength = plcByte.Length;
- httpWebRequest.GetRequestStream().Write(plcByte, 0, plcByte.Length);
-
- HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
- StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
- string responseContent = streamReader.ReadToEnd();
- JObject responseJson = JsonConvert.DeserializeObject<JObject>(responseContent);
- streamReader.Close();
- httpWebResponse.Close();
- httpWebRequest.Abort();
- return responseJson;
- }
打开抖音可以看到刚才发布的视频,在集成到真的平台应用上,再写个方法将回调里的code自动抓取到,整个过程只需要用户扫码授权就可以自动发布了
水平不够,又很忙,写的代码看起来比较繁琐,大家将就看看吧。。。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。