暫無描述

FeiShuiHelper.cs 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Net.Http.Headers;
  9. using System.Text;
  10. namespace CallCenter.Utility
  11. {
  12. public class FeiShuiHelper
  13. {
  14. static string app_id = Configs.GetValue("FeiShui_AppId");
  15. static string app_secret = Configs.GetValue("FeiShui_AppSecret");
  16. //获取tenant_access_token
  17. private static string GetTenantAccessToken()
  18. {
  19. string result = string.Empty;
  20. var param = new
  21. {
  22. app_id = app_id,
  23. app_secret = app_secret,
  24. };
  25. var strresult = HttpMethods.HttpPost("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal", param.ToJson(),"application/json; charset=utf-8");
  26. if (!string.IsNullOrEmpty(strresult))
  27. {
  28. var resultobj = strresult.ToJObject();
  29. if (resultobj["code"].ToString() != "0")
  30. {
  31. LogFactory.GetLogger("tenant_access_token").Error(strresult);
  32. result = resultobj["msg"].ToString();
  33. }
  34. else
  35. {
  36. result = resultobj["tenant_access_token"].ToString();
  37. }
  38. }
  39. return result;
  40. }
  41. //获取user_access_token
  42. private static string GetUserAccessToken(string code)
  43. {
  44. string result = string.Empty;
  45. var param = new
  46. {
  47. grant_type = "authorization_code",
  48. client_id = app_id,
  49. client_secret=app_secret,
  50. code= code
  51. };
  52. var strresult = HttpMethods.HttpPost("https://open.feishu.cn/open-apis/authen/v2/oauth/token", param.ToJson(), "application/json; charset=utf-8");
  53. if (!string.IsNullOrEmpty(strresult))
  54. {
  55. var resultobj = strresult.ToJObject();
  56. if (resultobj["code"].ToString() != "0")
  57. {
  58. LogFactory.GetLogger("error").Error(strresult);
  59. result = resultobj["error"].ToString();
  60. }
  61. else
  62. {
  63. result = resultobj["access_token"].ToString();
  64. }
  65. }
  66. return result;
  67. }
  68. //通过手机号获取用户id
  69. private static string GetUserid(string mobile)
  70. {
  71. string result = string.Empty;
  72. //Dictionary<string, object> param = new Dictionary<string, object>();
  73. //param.Add("mobiles", new string[] { mobile });
  74. //param.Add("include_resigned", true);
  75. var postData = new { mobiles = new string[] { mobile }, include_resigned = true };
  76. var strresult = SendPostRequest
  77. ("https://open.feishu.cn/open-apis/contact/v3/users/batch_get_id?user_id_type=user_id", postData);
  78. if (!string.IsNullOrEmpty(strresult))
  79. {
  80. generalResult<userslist> resultobj = JsonConvert.
  81. DeserializeObject<generalResult<userslist>>(strresult);
  82. if (resultobj.code != "0")
  83. {
  84. LogFactory.GetLogger("GetUserid").Error(resultobj.msg);
  85. result = resultobj.msg;
  86. }
  87. else
  88. {
  89. if (resultobj.data!=null&& resultobj.data.user_list.Count>0)
  90. result = resultobj.data.user_list[0].user_id;
  91. }
  92. }
  93. return result;
  94. }
  95. //发送消息
  96. public static string SendMsg(string mobile,string msg)
  97. {
  98. string userid = GetUserid(mobile);
  99. if (string.IsNullOrEmpty(mobile))
  100. return "";
  101. Guid guid = Guid.NewGuid();
  102. string uuid = guid.ToString();
  103. string result = string.Empty;
  104. //Dictionary<string, object> param = new Dictionary<string, object>();
  105. //param.Add("receive_id", userid);
  106. //param.Add("msg_type", "text");
  107. //param.Add( "content", "{\"text\":\"" + msg + "\"}");
  108. //param.Add("uuid", uuid);
  109. var postData = new { receive_id = userid, msg_type = "post",
  110. content = "{\"zh_cn\":{\"title\":\""+ msg + "\",\"content\":[[{\"tag\":\"text\",\"text\":\"地址 :\"},{\"tag\":\"a\",\"href\":\"http://www.feishu.cn\",\"text\":\"超链接\"}]]}}",
  111. uuid = uuid,
  112. };
  113. var strresult = SendPostRequest
  114. ("https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=user_id", postData);
  115. if (!string.IsNullOrEmpty(strresult))
  116. {
  117. var resultobj = strresult.ToJObject();
  118. if (resultobj["code"].ToString() != "0")
  119. {
  120. LogFactory.GetLogger("SendMsg").Error(strresult);
  121. result = resultobj["msg"].ToString();
  122. }
  123. else
  124. {
  125. result = resultobj.ToJson() ;
  126. }
  127. }
  128. return result;
  129. }
  130. //获取单个用户
  131. public static string GetUser(string code)
  132. {
  133. string token = GetUserAccessToken(code);
  134. Guid guid = Guid.NewGuid();
  135. string uuid = guid.ToString();
  136. string result = string.Empty;
  137. var strresult = SendGetRequest("https://open.feishu.cn/open-apis/authen/v1/user_info",token);
  138. if (!string.IsNullOrEmpty(strresult))
  139. {
  140. generalResult<user> resultobj = JsonConvert.DeserializeObject<generalResult<user>>(strresult);
  141. if (resultobj.code != "0")
  142. {
  143. LogFactory.GetLogger("GetUser").Error(resultobj.msg);
  144. result = resultobj.msg;
  145. }
  146. else
  147. {
  148. if (resultobj.data != null )
  149. result = resultobj.data.mobile;
  150. }
  151. }
  152. return result;
  153. }
  154. public static string SendGetRequest(string url, string authToken)
  155. {
  156. // 创建请求对象
  157. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  158. request.Method = "GET";
  159. request.ContentType = "application/json; charset=utf-8"; // 设置 Content-Type
  160. request.Headers.Add("Authorization", $"Bearer {authToken}");
  161. // 如果需要忽略 SSL 证书验证(仅测试环境使用)
  162. // ServicePointManager.ServerCertificateValidationCallback +=
  163. // (sender, certificate, chain, sslPolicyErrors) => true;
  164. try
  165. {
  166. // 获取响应
  167. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  168. using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
  169. {
  170. return reader.ReadToEnd();
  171. }
  172. }
  173. catch (WebException ex)
  174. {
  175. // 处理错误响应
  176. if (ex.Response is HttpWebResponse errorResponse)
  177. {
  178. using (Stream errorStream = errorResponse.GetResponseStream())
  179. using (StreamReader reader = new StreamReader(errorStream, Encoding.UTF8))
  180. {
  181. string errorContent = reader.ReadToEnd();
  182. throw new Exception($"HTTP Error {(int)errorResponse.StatusCode}: {errorContent}");
  183. }
  184. }
  185. throw;
  186. }
  187. }
  188. public static string HttpGet(string url, string token)
  189. {
  190. ServicePointManager.Expect100Continue = true;
  191. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
  192. ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
  193. HttpClient client = new HttpClient();
  194. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json; charset=utf-8"));
  195. client.DefaultRequestHeaders.Authorization = new
  196. AuthenticationHeaderValue
  197. ("Bearer", token);
  198. var result = client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;
  199. return result;
  200. }
  201. public static string SendPostRequest(string url, object data)
  202. {
  203. string authToken = GetTenantAccessToken();
  204. // 创建请求对象
  205. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  206. request.Method = "POST";
  207. request.ContentType = "application/json; charset=utf-8";
  208. // 添加 Authorization 头
  209. request.Headers.Add("Authorization", $"Bearer {authToken}");
  210. // 如果需要忽略 SSL 证书验证(仅测试环境使用)
  211. // ServicePointManager.ServerCertificateValidationCallback +=
  212. // (sender, certificate, chain, sslPolicyErrors) => true;
  213. try
  214. {
  215. // 序列化数据为 JSON
  216. string json = JsonConvert.SerializeObject(data);
  217. byte[] postData = Encoding.UTF8.GetBytes(json);
  218. // 写入请求体
  219. request.ContentLength = postData.Length;
  220. using (Stream stream = request.GetRequestStream())
  221. {
  222. stream.Write(postData, 0, postData.Length);
  223. }
  224. // 获取响应
  225. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  226. using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
  227. {
  228. return reader.ReadToEnd();
  229. }
  230. }
  231. catch (WebException ex)
  232. {
  233. // 处理错误响应
  234. if (ex.Response is HttpWebResponse errorResponse)
  235. {
  236. using (Stream errorStream = errorResponse.GetResponseStream())
  237. using (StreamReader reader = new StreamReader(errorStream, Encoding.UTF8))
  238. {
  239. string errorContent = reader.ReadToEnd();
  240. throw new Exception($"HTTP Error {(int)errorResponse.StatusCode}: {errorContent}");
  241. }
  242. }
  243. throw;
  244. }
  245. }
  246. public static string HttpPost(string url, Dictionary<string, object> dic)
  247. {
  248. string result = ""; string token = GetTenantAccessToken();
  249. try
  250. {
  251. // 创建 HttpWebRequest 对象
  252. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  253. // 设置请求方法为 POST
  254. request.Method = "POST";
  255. // 设置 Content-Type
  256. request.ContentType = "application/json; charset=utf-8";
  257. // 设置 Authorization 头部
  258. request.Headers.Add("Authorization", token);
  259. var d = JsonConvert.SerializeObject(dic);
  260. // 将请求体数据转换为字节数组
  261. byte[] requestBodyBytes = Encoding.UTF8.GetBytes(d);
  262. // 设置请求体的长度
  263. request.ContentLength = requestBodyBytes.Length;
  264. // 获取请求流
  265. using (Stream requestStream = request.GetRequestStream())
  266. {
  267. // 将请求体数据写入请求流
  268. requestStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
  269. }
  270. // 发送请求并获取响应
  271. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  272. {
  273. // 检查响应状态码
  274. if (response.StatusCode == HttpStatusCode.OK)
  275. {
  276. // 获取响应流
  277. using (Stream responseStream = response.GetResponseStream())
  278. {
  279. if (responseStream != null)
  280. {
  281. // 创建 StreamReader 用于读取响应流
  282. using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
  283. {
  284. // 读取响应内容
  285. string responseBody = reader.ReadToEnd();
  286. Console.WriteLine("请求成功,响应内容:");
  287. return responseBody;
  288. }
  289. }
  290. }
  291. }
  292. else
  293. {
  294. return $"请求失败,状态码:{response.StatusCode}";
  295. }
  296. }
  297. }
  298. catch (WebException ex)
  299. {
  300. if (ex.Status == WebExceptionStatus.ProtocolError)
  301. {
  302. HttpWebResponse errorResponse = (HttpWebResponse)ex.Response;
  303. return $"请求失败,状态码:{errorResponse.StatusCode}";
  304. }
  305. else
  306. {
  307. return $"发生网络异常:{ex.Message}";
  308. }
  309. }
  310. catch (Exception ex)
  311. {
  312. return $"发生异常:{ex.Message}";
  313. }
  314. return result;
  315. }
  316. private class generalResult<T> where T : class
  317. {
  318. public string code { get; set; }
  319. public string msg { get; set; }
  320. public T data { get; set; }
  321. }
  322. private class userlist
  323. {
  324. public string user_id { get; set; }
  325. }
  326. private class userslist
  327. {
  328. public List<userlist> user_list { get; set; }
  329. }
  330. private class user
  331. {
  332. public string mobile { get; set; }
  333. }
  334. }
  335. }