当前位置:   article > 正文

第三方平台一键发布视频至抖音:基于.NET CORE_第三方发布视频到抖音

第三方发布视频到抖音

前言

既上次介绍了如何通过.net core控制台应用一键发布公众号消息后,这次来介绍一下,如何通过.net core 控制台应用一键发布视频内容至抖音,可以作为第三方分享内容至抖音的服务端方法参考,官方的示例没有提供C#的代码,并且文档也超级坑,api设计也很不友好,返回的错误码并不能真正反映问题所在,总之就是不够restful。。。这个坑我觉得比微信的文档还大。。废话不多说,开始吧

开发流程

(1)申请并成功配置应用

这里我就不多介绍了,参考这一篇博客:https://blog.csdn.net/I_lost/article/details/104520655,注意将授权回调域设置好

(2)获取用户授权code

随便说点,代码中的注释已经够清楚了。

强调一下,请求地址:https://open.douyin.com/platform/oauth/connect/

里面配置query的部分只需要注意:回调地址即redirect_uri需要在应用的配置的授权域名下,其他没啥了。。都很简单,我这里是控制台应用,会调用本地浏览器打开抖音扫码界面

  1. private string GetDouYinCode()
  2. {
  3. Dictionary<string, string> requestParameters = new Dictionary<string, string>();
  4. //这里的client_key以及client_secret需要自己到开发者平台去开通一个应用得到
  5. requestParameters.Add("client_key", "client_key");
  6. requestParameters.Add("response_type", "code");
  7. requestParameters.Add("scope", "video.create");
  8. //redirect_uri 回调的地址,需要在开发者平台配置这个地址
  9. requestParameters.Add("redirect_uri", "http://ccciie.com/eyuntong/(S(amksryslevropj3ib0nl0jha))/Default.aspx?id=V2.0");
  10. string requestUrl = "https://open.douyin.com/platform/oauth/connect/";
  11. StringBuilder stringBuilder = new StringBuilder();
  12. stringBuilder.Append(requestUrl);
  13. if (requestParameters.Count > 0)
  14. {
  15. stringBuilder.Append("?");
  16. foreach (var item in requestParameters)
  17. {
  18. stringBuilder.Append("&");
  19. stringBuilder.AppendFormat("{0}={1}", item.Key, item.Value);
  20. }
  21. }
  22. string codeRequest = stringBuilder.ToString();
  23. Console.WriteLine(codeRequest);
  24. // 控制台打开浏览器或者web 中打开新的窗口进行扫码跳转,等待用户输入code
  25. //将跳转后UTL的“code=“到”&“之间的字符复制下来,如下:6yNlI4Xu1Rc923iBNTvzQAsvK00nnie8yiTJ
  26. //https://www.a9blmo3lvm.54http.tech/?code=6yNlI4Xu1Rc923iBNTvzQAsvK00nnie8yiTJ&state=
  27. string code = OpenBrowerInputCode(codeRequest);
  28. return code;
  29. }
  30. private string OpenBrowerInputCode(string codeRequest)
  31. {
  32. // 控制台打开浏览器窗口或者web 跳转到新的页面, 地址是:codeRequest
  33. // 我这里因为是控制台应用,就用了System.Diagnostics.Process()方法,web中弄个a标签跳转到codeRequest这个地址即可,
  34. System.Diagnostics.Process.Start(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", codeRequest);
  35. //用户将这个code复制下来,作为GetDouYinAcessToken(code)的传入参数
  36. //扫码跳转后的地址示例:https://www.a9blmo3lvm.54http.tech/?code=6yNlI4Xu1Rc923iBNTvzQAsvK00nnie8yiTJ&state=
  37. string code = Console.ReadLine();
  38. if (!string.IsNullOrWhiteSpace(code))
  39. {
  40. return code;
  41. }
  42. return new Exception("code不能为空").ToString();
  43. }

等待用户扫码跳转确认,确认后将代码中所说的code复制到控制台中,等待执行下一步

 

(3)获取AcessToken

简单说一下,这里对通过服务端方法对https://open.douyin.com/oauth/access_token/发起请求,最后将返回的open_id以及access_token取出来,用作下一步的进行视频上传的接口的参数

  1. private void GetDouYinAcessToken(string code)
  2. {
  3. Dictionary<string, string> requestParameters = new Dictionary<string, string>();
  4. requestParameters.Add("client_key", "client_key");
  5. requestParameters.Add("client_secret", "client_secret");
  6. requestParameters.Add("code", code);
  7. requestParameters.Add("grant_type", "authorization_code");
  8. string requestUrl = "https://open.douyin.com/oauth/access_token/";
  9. StringBuilder stringBuilder = new StringBuilder();
  10. stringBuilder.Append(requestUrl);
  11. if (requestParameters.Count > 0)
  12. {
  13. stringBuilder.Append("?");
  14. foreach (var item in requestParameters)
  15. {
  16. stringBuilder.Append("&");
  17. stringBuilder.AppendFormat("{0}={1}", item.Key, item.Value);
  18. }
  19. }
  20. HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(stringBuilder.ToString());
  21. httpWebRequest.ContentType = "application/json";
  22. httpWebRequest.Method = "GET";
  23. httpWebRequest.Timeout = 20000;
  24. HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  25. StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
  26. string responseContent = streamReader.ReadToEnd();
  27. JObject jsonresult = JsonConvert.DeserializeObject<JObject>(responseContent);
  28. if (jsonresult["data"]["access_token"] != null && jsonresult["data"]["open_id"] != null)
  29. {
  30. AcessToken = jsonresult["data"]["access_token"].ToString();
  31. OpenId = jsonresult["data"]["open_id"].ToString();
  32. }
  33. streamReader.Close();
  34. httpWebResponse.Close();
  35. httpWebRequest.Abort();
  36. //return jsonresult;
  37. }

(4)上传视频至服务器

这里是最坑的地方。。。文档很坑,并且对于C#一点也不友好,我调试了很久,才最终上传成功。

  1. /// <summary>
  2. /// 视频上传方法
  3. /// </summary>
  4. /// <param name="path">视频文件路径,视频大小不能超过128M,时长不能超过15分钟</param>
  5. /// <param name="videoTitle">视频的标题</param>
  6. /// <returns></returns>
  7. private JObject UploadVideoToDouYin(string path, string videoTitle)
  8. {
  9. FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
  10. byte[] bArr = new byte[fs.Length];
  11. fs.Read(bArr, 0, bArr.Length);
  12. string url = string.Format("https://open.douyin.com/video/upload/?open_id={1}&access_token={0}", AcessToken, OpenId);
  13. HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
  14. //httpWebRequest.AllowAutoRedirect = true;
  15. httpWebRequest.Method = "POST";
  16. httpWebRequest.Timeout = 20000;
  17. string boundary = DateTime.Now.Ticks.ToString("X");
  18. httpWebRequest.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
  19. byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
  20. byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
  21. int pos = path.LastIndexOf("\\");
  22. string fileName = path.Substring(pos + 1);
  23. //组织表单数据
  24. StringBuilder sbHeader = new StringBuilder();
  25. sbHeader.Append("Content-Disposition: form-data; name=\"video\"; filename=\"" + path + "\"; filelength=\"" + fs.Length + "\"");
  26. sbHeader.Append("\r\n");
  27. //其他视频格式需要修改Content-Type:video/mp4; 格式必须是”video/“开头
  28. sbHeader.Append("Content-Type:video/mp4;");
  29. sbHeader.Append("\r\n\r\n");
  30. byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
  31. Stream postStream = httpWebRequest.GetRequestStream();
  32. postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
  33. postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
  34. postStream.Write(bArr, 0, bArr.Length);
  35. postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  36. postStream.Close();
  37. fs.Close();
  38. fs.Dispose();
  39. HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  40. StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
  41. string responseContent = streamReader.ReadToEnd();
  42. JObject jsonresult = JsonConvert.DeserializeObject<JObject>(responseContent);
  43. streamReader.Close();
  44. httpWebResponse.Close();
  45. httpWebRequest.Abort();
  46. if (jsonresult["data"]["video"]["video_id"] != null)
  47. {
  48. VideoId = jsonresult["data"]["video"]["video_id"].ToString();
  49. Console.WriteLine(VideoId);
  50. CrateVideoForDouYin(videoTitle);
  51. }
  52. return jsonresult;
  53. }

(5)发布内容

到这就没啥问题了,直接参考官方文档,对内容做相应的配置即可。

  1. private JObject CrateVideoForDouYin(string videoTitle)
  2. {
  3. //发送视频的的标题,不支持艾特某个用户
  4. string videoContext = @"{""text"":""测试视频:人生的意义在于旅行"",""video_id"":""""}";
  5. JObject requsetToken = JsonConvert.DeserializeObject<JObject>(videoContext);
  6. requsetToken["text"] = videoTitle;
  7. requsetToken["video_id"] = VideoId;
  8. string requestUrl = string.Format("https://open.douyin.com/video/create/?open_id={0}&access_token={1}", OpenId, AcessToken);
  9. HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
  10. httpWebRequest.ContentType = "application/json";
  11. httpWebRequest.Method = "POST";
  12. httpWebRequest.Timeout = 10000;
  13. Console.WriteLine("请求的参数为\n" + requsetToken);
  14. byte[] plcByte = Encoding.UTF8.GetBytes(requsetToken.ToString());
  15. httpWebRequest.ContentLength = plcByte.Length;
  16. httpWebRequest.GetRequestStream().Write(plcByte, 0, plcByte.Length);
  17. HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  18. StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
  19. string responseContent = streamReader.ReadToEnd();
  20. JObject responseJson = JsonConvert.DeserializeObject<JObject>(responseContent);
  21. streamReader.Close();
  22. httpWebResponse.Close();
  23. httpWebRequest.Abort();
  24. return responseJson;
  25. }

(6)完成发布

打开抖音可以看到刚才发布的视频,在集成到真的平台应用上,再写个方法将回调里的code自动抓取到,整个过程只需要用户扫码授权就可以自动发布了

 

水平不够,又很忙,写的代码看起来比较繁琐,大家将就看看吧。。。

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/90540
推荐阅读
相关标签
  

闽ICP备14008679号