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
{
///
/// 获取AccessToken
///
///
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;
}
///
/// 根据手机号获取用户id
///
/// 手机号
///
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;
}
///
/// 发送模板消息
///
/// 多个用户逗号隔开
/// 多个部门逗号隔开
/// 模板参数json
/// 模板ID
///
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;
}
///
/// 发送工作通知
///
/// 多个用户逗号隔开
/// 多个部门逗号隔开
/// 内容json
/// 是否全部群发
///
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;
}
///
/// 发送工作通知-文本
///
/// 多个用户逗号隔开
/// 多个部门逗号隔开
/// 文本内容
///
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;
}
///
/// 发送链接工作通知-文本
///
/// 多个用户逗号隔开
/// 多个部门逗号隔开
/// 文本内容
///
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;
}
///
/// 获取工作通知结果
///
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(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;
}
///
/// 通过免登码获取用户信息
///
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;
}
///
/// 上传附件
///
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;
}
///
/// 查询用户详情
///
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 read_user_id_list { set; get; }
public List unread_user_id_list { set; get; }
}
///
///
///
///
///
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;
}
//给某个部门的所有的人发消息
///
/// 获取部门列表 参数传1 是根节点的子部门
/// https://open.dingtalk.com/document/orgapp-server/obtain-the-department-list-v2
///
///
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();
}
///
/// 获取部门所有的userid
///
/// Get https://oapi.dingtalk.com/user/getDeptMember
///
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(strresult);
return "";
}
}
}