| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443 |
-
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- 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 DingTalkHelper
- {
- /// <summary>
- /// 获取AccessToken
- /// </summary>
- /// <returns></returns>
- public static string GetAccessToken()
- {
- var accesstoken = RedisHelper1.StringGet("DingTalkToken")?.ToString() ?? "";
- if (string.IsNullOrEmpty(accesstoken))
- {
- string result = HttpMethods.HttpGet(string.Format("https://oapi.dingtalk.com/gettoken?appkey={0}&appsecret={1}",
- Configs.GetValue("DingTalk_AppKey"), Configs.GetValue("DingTalk_AppSecret")));
- var resultobj = result.ToJObject();
- if (resultobj["errcode"].ToString() == "0")
- {
- accesstoken = resultobj["access_token"].ToString();
- string cachetime = Configs.GetValue("DingTalk_TokenCacheTime");
- RedisHelper1.StringSet("DingTalkToken", accesstoken, new TimeSpan(0, 0, int.Parse(cachetime)));
- }
- }
- return accesstoken;
- }
- /// <summary>
- /// 根据手机号获取用户id
- /// </summary>
- /// <param name="mobile">手机号</param>
- /// <returns></returns>
- public static string GetUserIdByMobile(string mobile)
- {
- string userid = string.Empty;
- var param = new
- {
- mobile = mobile
- };
- var strresult = HttpMethods.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/v2/user/getbymobile?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
- if (!string.IsNullOrEmpty(strresult))
- {
- var resultobj = strresult.ToJObject();
- if (resultobj["errcode"].ToString() != "0")
- {
- LogFactory.GetLogger("DINGDING ").Error(strresult);
- //userid = resultobj["errmsg"].ToString();
- }
- else
- {
- var robj = resultobj["result"].ToString().ToJObject();
- userid = robj["userid"].ToString();
- }
- }
- return userid;
- }
- /// <summary>
- /// 发送模板消息
- /// </summary>
- /// <param name="userids">多个用户逗号隔开</param>
- /// <param name="deptids">多个部门逗号隔开</param>
- /// <param name="msgjson">模板参数json</param>
- /// <param name="templateid">模板ID</param>
- /// <returns></returns>
- public static string SendMessageByTemplate(string userids, string deptids, string msgjson, string templateid)
- {
- string result = string.Empty;
- var param = new
- {
- agent_id = Configs.GetValue("DingTalk_AgentId"),
- template_id = templateid,
- //data = "{\"name\":\"淘宝6\",\"name2\":\"http://www.taobao.com\"}",
- data = msgjson,
- //userid_list = "213,234,123",
- userid_list = userids,
- //dept_id_list = "421,897,262"
- dept_id_list = deptids
- };
- var strresult = HttpMethods.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/message/corpconversation/sendbytemplate?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
- if (!string.IsNullOrEmpty(strresult))
- {
- var resultobj = strresult.ToJObject();
- if (resultobj["errcode"].ToString() != "0")
- {
- LogFactory.GetLogger("DINGDING ").Error(strresult);
- result = resultobj["errmsg"].ToString();
- }
- }
- return result;
- }
- /// <summary>
- /// 发送工作通知
- /// </summary>
- /// <param name="userids">多个用户逗号隔开</param>
- /// <param name="deptids">多个部门逗号隔开</param>
- /// <param name="msgjson">内容json</param>
- /// <param name="isall">是否全部群发</param>
- /// <returns></returns>
- public static string SendMessage(string userids, string deptids, string msgjson, bool isall = false)
- {
- string result = string.Empty;
- var param = new JObject();
- param["agent_id"] = Configs.GetValue("DingTalk_AgentId");
- if (!string.IsNullOrEmpty(userids))
- {
- param["userid_list"] = userids;
- }
- if (!string.IsNullOrEmpty(deptids))
- {
- param["dept_id_list"] = deptids;
- }
- param["to_all_user"] = isall;
- param["msg"] = msgjson.ToJObject();
- //var param=new
- //{
- // agent_id = ConfigHelper.GetValue("DingTalk_AgentId"),
- // //userid_list = "213,234,123",
- // userid_list = userids,
- // //dept_id_list = "421,897,262"
- // dept_id_list = deptids,
- // to_all_user = isall,
- // //msg = new {
- // // msgtype="text",
- // // text = new {content="内容" }
- // //},
- // //msg = new
- // //{
- // // msgtype = "markdown",
- // // markdown = new { text = "内容",title="标题" }
- // //},
- // msg
- //};
- var strresult = HttpMethods.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
- if (!string.IsNullOrEmpty(strresult))
- {
- var resultobj = strresult.ToJObject();
- if (resultobj["errcode"].ToString() != "0")
- {
- LogFactory.GetLogger("DINGDING ").Error(strresult);
- result = resultobj["errmsg"].ToString();
- }
- else
- {
- result = resultobj["task_id"].ToString();
- }
- }
- return result;
- }
- /// <summary>
- /// 发送工作通知-文本
- /// </summary>
- /// <param name="userids">多个用户逗号隔开</param>
- /// <param name="deptids">多个部门逗号隔开</param>
- /// <param name="content">文本内容</param>
- /// <returns></returns>
- public static string SendMessageText(string userids, string deptids, string content)
- {
- var msg = new
- {
- msgtype = "text",
- text = new { content }
- };
- string result = SendMessage(userids, deptids, msg.ToJson());
- return result;
- }
- /// <summary>
- /// 发送链接工作通知-文本
- /// </summary>
- /// <param name="userids">多个用户逗号隔开</param>
- /// <param name="deptids">多个部门逗号隔开</param>
- /// <param name="content">文本内容</param>
- /// <returns></returns>
- public static string SendUrlText(string userids, string deptids, string content, string url, string title, string pc_message_url, string picurl = "@lALPDeC286_fT0rNAePNAnM")
- {
- var msg = new
- {
- msgtype = "oa",
- oa = new
- {
- message_url = url,
- pc_message_url,
- head = new { bgcolor = "FFBBBBBB", text = title },
- body = new { title, content = content }
- }
- };
- string result = SendMessage(userids, deptids, msg.ToJson());
- return result;
- }
- /// <summary>
- /// 获取工作通知结果
- /// <returns></returns>
- public static int GetMessage(string task_id)
- {
- int result = 0;
- var param = new JObject();
- param["agent_id"] = Configs.GetValue("DingTalk_AgentId");
- if (!string.IsNullOrEmpty(task_id))
- {
- param["task_id"] = task_id;
- }
- var strresult = HttpMethods.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/message/corpconversation/getsendresult?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
- if (!string.IsNullOrEmpty(strresult))
- {
- var resultobj = strresult.ToJObject();
- if (resultobj["errcode"].ToString() != "0")
- {
- LogFactory.GetLogger("DINGDING ").Error(strresult);
- result = 0;
- }
- else
- {
- send_result jo = JsonConvert.DeserializeObject<send_result>(resultobj["send_result"].ToString());
- if (jo != null)
- {
- if (jo.read_user_id_list != null && jo.read_user_id_list.Count > 0)
- result = 1;
- else if (jo.unread_user_id_list != null && jo.unread_user_id_list.Count > 0)
- result = 2;
- }
- }
- }
- return result;
- }
- /// <summary>
- /// 通过免登码获取用户信息
- /// <returns></returns>
- public static string GetUserInfo(string code)
- {
- string result = "";
- var param = new JObject();
- if (!string.IsNullOrEmpty(code))
- {
- param["code"] = code;
- }
- var strresult = HttpMethods.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
- if (!string.IsNullOrEmpty(strresult))
- {
- JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);
- if (jo["errcode"].ToString() != "0")
- {
- LogFactory.GetLogger("DINGDING ").Error(strresult);
- result = "err";
- }
- else
- {
- var message = jo["result"].ToString();
- var messages = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(message);
- result = messages["userid"].ToString();
- }
- }
- return result;
- }
- /// <summary>
- /// 上传附件
- /// <returns></returns>
- public static string Upload(string media)
- {
- string result = "";
- using (var client = new HttpClient())
- {
- using (var content = new MultipartFormDataContent())
- {
- NameValueCollection fileCollection = new NameValueCollection();
- fileCollection.Add("media", media);
- //处理文件内容
- string[] fileKeys = fileCollection.AllKeys;
- foreach (string key in fileKeys)
- {
- byte[] bmpBytes = File.ReadAllBytes(fileCollection[key]);
- var fileContent = new ByteArrayContent(bmpBytes);//填充文件字节
- fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
- {
- Name = key,
- FileName = Path.GetFileName(fileCollection[key])
- };
- content.Add(fileContent);
- }
- var Postresult = client.PostAsync(string.Format("https://oapi.dingtalk.com/media/upload?access_token={0}&type=image", GetAccessToken()), content).Result;//post请求
- string strresult = Postresult.Content.ReadAsStringAsync().Result;
- if (!string.IsNullOrEmpty(strresult))
- {
- JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);
- if (jo["errcode"].ToString() != "0")
- {
- LogFactory.GetLogger("DINGDING ").Error(strresult);
- result = "err";
- }
- else
- {
- result = jo["media_id"].ToString();
- }
- }
- }
- }
- return result;
- }
- /// <summary>
- /// 查询用户详情
- /// <returns></returns>
- public static string GetUser(string userid)
- {
- string result = "";
- var param = new JObject();
- if (!string.IsNullOrEmpty(userid))
- {
- param["userid"] = userid;
- param["language"] = "zh_CN";
- }
- var strresult = HttpMethods.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/v2/user/get?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
- if (!string.IsNullOrEmpty(strresult))
- {
- JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);
- if (jo["errcode"].ToString() != "0")
- {
- LogFactory.GetLogger("DINGDING ").Error(strresult);
- result = "err";
- }
- else
- {
- var message = jo["result"].ToString();
- var messages = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(message);
- result = messages["mobile"].ToString();
- }
- }
- return result;
- }
- public class send_result
- {
- public List<string> read_user_id_list { set; get; }
- public List<string> unread_user_id_list { set; get; }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="userid"></param>
- /// <returns></returns>
- public static string GetUserInfoByUserId(string userid)
- {
- //WebClient web = new WebClient();
- //web.Encoding = Encoding.UTF8;
- //string strresult = web.DownloadString(string.Format("https://oapi.dingtalk.com/user/get?access_token={0}&userid={1}", GetAccessToken(), userid));
- //JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);
- //return jo.ToJson();
- string url = string.Format("https://oapi.dingtalk.com/user/get?access_token={0}&userid={1}", GetAccessToken(), userid);
- var strresult = HttpMethods.HttpGet(url);
- return strresult;
- }
- //给某个部门的所有的人发消息
- /// <summary>
- /// 获取部门列表 参数传1 是根节点的子部门
- /// https://open.dingtalk.com/document/orgapp-server/obtain-the-department-list-v2
- /// </summary>
- /// <returns></returns>
- public static string GetDeptlist()
- {
- WebClient web = new WebClient();
- web.Encoding = Encoding.UTF8;
- string strresult = web.DownloadString(string.Format("https://oapi.dingtalk.com/topapi/v2/department/listsub?access_token={0}&dept_id={1}", GetAccessToken(), 1));
- JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);
- return jo.ToJson();
- }
- /// <summary>
- /// 获取部门所有的userid
- /// </summary>
- /// <param name="deptid">Get https://oapi.dingtalk.com/user/getDeptMember </param>
- /// <returns></returns>
- public static string GetUserIdsByDeptId(double deptid)
- {
- WebClient web = new WebClient();
- web.Encoding = Encoding.UTF8;
- string strresult = web.DownloadString(string.Format("https://oapi.dingtalk.com/user/getDeptMember?access_token={0}&deptId={1}", GetAccessToken(), deptid));
- JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);
- if (jo != null && jo["userIds"] != null)
- {
- return jo["userIds"].ToString();
- }
- //JsonConvert.SerializeObject();
- //TreeModel model= JsonConvert.DeserializeObject<TreeModel>(strresult);
- return "";
- }
- }
- }
|