using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; namespace CallCenter.Utility { public class FeiShuiHelper { static string app_id = Configs.GetValue("FeiShui_AppId"); static string app_secret = Configs.GetValue("FeiShui_AppSecret"); //获取tenant_access_token private static string GetTenantAccessToken() { string result = string.Empty; var param = new { app_id = app_id, app_secret = app_secret, }; var strresult = HttpMethods.HttpPost("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal", param.ToJson(),"application/json; charset=utf-8"); if (!string.IsNullOrEmpty(strresult)) { var resultobj = strresult.ToJObject(); if (resultobj["code"].ToString() != "0") { LogFactory.GetLogger("tenant_access_token").Error(strresult); result = resultobj["msg"].ToString(); } else { result = resultobj["tenant_access_token"].ToString(); } } return result; } //获取user_access_token private static string GetUserAccessToken(string code) { string result = string.Empty; var param = new { grant_type = "authorization_code", client_id = app_id, client_secret=app_secret, code= code }; var strresult = HttpMethods.HttpPost("https://open.feishu.cn/open-apis/authen/v2/oauth/token", param.ToJson(), "application/json; charset=utf-8"); if (!string.IsNullOrEmpty(strresult)) { var resultobj = strresult.ToJObject(); if (resultobj["code"].ToString() != "0") { LogFactory.GetLogger("error").Error(strresult); result = resultobj["error"].ToString(); } else { result = resultobj["access_token"].ToString(); } } return result; } //通过手机号获取用户id private static string GetUserid(string mobile) { string result = string.Empty; //Dictionary param = new Dictionary(); //param.Add("mobiles", new string[] { mobile }); //param.Add("include_resigned", true); var postData = new { mobiles = new string[] { mobile }, include_resigned = true }; var strresult = SendPostRequest ("https://open.feishu.cn/open-apis/contact/v3/users/batch_get_id?user_id_type=user_id", postData); if (!string.IsNullOrEmpty(strresult)) { generalResult resultobj = JsonConvert. DeserializeObject>(strresult); if (resultobj.code != "0") { LogFactory.GetLogger("GetUserid").Error(resultobj.msg); result = resultobj.msg; } else { if (resultobj.data!=null&& resultobj.data.user_list.Count>0) result = resultobj.data.user_list[0].user_id; } } return result; } //发送消息 public static string SendMsg(string mobile,string msg) { string userid = GetUserid(mobile); if (string.IsNullOrEmpty(mobile)) return ""; Guid guid = Guid.NewGuid(); string uuid = guid.ToString(); string result = string.Empty; //Dictionary param = new Dictionary(); //param.Add("receive_id", userid); //param.Add("msg_type", "text"); //param.Add( "content", "{\"text\":\"" + msg + "\"}"); //param.Add("uuid", uuid); var postData = new { receive_id = userid, msg_type = "post", content = "{\"zh_cn\":{\"title\":\""+ msg + "\",\"content\":[[{\"tag\":\"text\",\"text\":\"地址 :\"},{\"tag\":\"a\",\"href\":\"http://www.feishu.cn\",\"text\":\"超链接\"}]]}}", uuid = uuid, }; var strresult = SendPostRequest ("https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=user_id", postData); if (!string.IsNullOrEmpty(strresult)) { var resultobj = strresult.ToJObject(); if (resultobj["code"].ToString() != "0") { LogFactory.GetLogger("SendMsg").Error(strresult); result = resultobj["msg"].ToString(); } else { result = resultobj.ToJson() ; } } return result; } //获取单个用户 public static string GetUser(string code) { string token = GetUserAccessToken(code); Guid guid = Guid.NewGuid(); string uuid = guid.ToString(); string result = string.Empty; var strresult = SendGetRequest("https://open.feishu.cn/open-apis/authen/v1/user_info",token); if (!string.IsNullOrEmpty(strresult)) { generalResult resultobj = JsonConvert.DeserializeObject>(strresult); if (resultobj.code != "0") { LogFactory.GetLogger("GetUser").Error(resultobj.msg); result = resultobj.msg; } else { if (resultobj.data != null ) result = resultobj.data.mobile; } } return result; } public static string SendGetRequest(string url, string authToken) { // 创建请求对象 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.ContentType = "application/json; charset=utf-8"; // 设置 Content-Type request.Headers.Add("Authorization", $"Bearer {authToken}"); // 如果需要忽略 SSL 证书验证(仅测试环境使用) // ServicePointManager.ServerCertificateValidationCallback += // (sender, certificate, chain, sslPolicyErrors) => true; try { // 获取响应 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } } catch (WebException ex) { // 处理错误响应 if (ex.Response is HttpWebResponse errorResponse) { using (Stream errorStream = errorResponse.GetResponseStream()) using (StreamReader reader = new StreamReader(errorStream, Encoding.UTF8)) { string errorContent = reader.ReadToEnd(); throw new Exception($"HTTP Error {(int)errorResponse.StatusCode}: {errorContent}"); } } throw; } } public static string HttpGet(string url, string token) { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json; charset=utf-8")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ("Bearer", token); var result = client.GetAsync(url).Result.Content.ReadAsStringAsync().Result; return result; } public static string SendPostRequest(string url, object data) { string authToken = GetTenantAccessToken(); // 创建请求对象 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json; charset=utf-8"; // 添加 Authorization 头 request.Headers.Add("Authorization", $"Bearer {authToken}"); // 如果需要忽略 SSL 证书验证(仅测试环境使用) // ServicePointManager.ServerCertificateValidationCallback += // (sender, certificate, chain, sslPolicyErrors) => true; try { // 序列化数据为 JSON string json = JsonConvert.SerializeObject(data); byte[] postData = Encoding.UTF8.GetBytes(json); // 写入请求体 request.ContentLength = postData.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(postData, 0, postData.Length); } // 获取响应 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } } catch (WebException ex) { // 处理错误响应 if (ex.Response is HttpWebResponse errorResponse) { using (Stream errorStream = errorResponse.GetResponseStream()) using (StreamReader reader = new StreamReader(errorStream, Encoding.UTF8)) { string errorContent = reader.ReadToEnd(); throw new Exception($"HTTP Error {(int)errorResponse.StatusCode}: {errorContent}"); } } throw; } } public static string HttpPost(string url, Dictionary dic) { string result = ""; string token = GetTenantAccessToken(); try { // 创建 HttpWebRequest 对象 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); // 设置请求方法为 POST request.Method = "POST"; // 设置 Content-Type request.ContentType = "application/json; charset=utf-8"; // 设置 Authorization 头部 request.Headers.Add("Authorization", token); var d = JsonConvert.SerializeObject(dic); // 将请求体数据转换为字节数组 byte[] requestBodyBytes = Encoding.UTF8.GetBytes(d); // 设置请求体的长度 request.ContentLength = requestBodyBytes.Length; // 获取请求流 using (Stream requestStream = request.GetRequestStream()) { // 将请求体数据写入请求流 requestStream.Write(requestBodyBytes, 0, requestBodyBytes.Length); } // 发送请求并获取响应 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { // 检查响应状态码 if (response.StatusCode == HttpStatusCode.OK) { // 获取响应流 using (Stream responseStream = response.GetResponseStream()) { if (responseStream != null) { // 创建 StreamReader 用于读取响应流 using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8)) { // 读取响应内容 string responseBody = reader.ReadToEnd(); Console.WriteLine("请求成功,响应内容:"); return responseBody; } } } } else { return $"请求失败,状态码:{response.StatusCode}"; } } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { HttpWebResponse errorResponse = (HttpWebResponse)ex.Response; return $"请求失败,状态码:{errorResponse.StatusCode}"; } else { return $"发生网络异常:{ex.Message}"; } } catch (Exception ex) { return $"发生异常:{ex.Message}"; } return result; } private class generalResult where T : class { public string code { get; set; } public string msg { get; set; } public T data { get; set; } } private class userlist { public string user_id { get; set; } } private class userslist { public List user_list { get; set; } } private class user { public string mobile { get; set; } } } }