1、获取配置文件内的注册信息
public static string appkey = ConfigurationManager.AppSettings["Appkey"];
public static string appsecret = ConfigurationManager.AppSettings["Appsecret"];
public static string agentId = ConfigurationManager.AppSettings["AgentId"];
2、声明全局变量
public DateTime? datetime = null;//判断token是否过期
public string access_token = null;//会话token
public string chatid = null;//会话Id
3、获取token
/// <summary>
/// 获取会话token
/// </summary>
/// <returns></returns>
public void GetToKen()
{
try
{
#region 根据微应用的key和secret获取token
IDingTalkClient gettokenclient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
OapiGettokenRequest gettokenreq = new OapiGettokenRequest();
gettokenreq.Appkey = appkey;
gettokenreq.Appsecret = appsecret;
gettokenreq.SetHttpMethod("GET");
OapiGettokenResponse gettokenrsp = gettokenclient.Execute(gettokenreq, access_token);
dynamic jsonModel = JsonConvert.DeserializeObject(gettokenrsp.Body);
access_token = jsonModel.access_token;
datetime = DateTime.Now;
#endregion
}
catch (Exception err)
{
throw;
}
}
4、根据会话token获取企业群Id
/// <summary>
/// 根据token获取企业群Id
/// </summary>
public void GetChatIdforToken()
{
if (string.IsNullOrWhiteSpace(access_token))
GetToKen();
IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/get");
OapiDepartmentGetRequest req = new OapiDepartmentGetRequest();
req.Id = "1";
req.SetHttpMethod("GET");
OapiDepartmentGetResponse rsp = client.Execute(req, access_token);
//Console.WriteLine(rsp.Body);
dynamic jsonModel = JsonConvert.DeserializeObject(rsp.Body);
chatid = jsonModel.deptGroupChatId;
}
5、推送消息
/// <summary>
/// 发送消息
/// </summary>
/// <param name="title">消息标题</param>
/// <param name="msg">消息内容</param>
public void SendMessage(string title,string msg)
{
DateTime dateTime = DateTime.Now;
if (datetime == null)//初次加载
{
GetToKen();
}
else
{
TimeSpan sp = dateTime.Subtract(Convert.ToDateTime(datetime));
if (sp.Seconds > 7000)//token过期
GetToKen();
}
if (string.IsNullOrWhiteSpace(access_token))
GetToKen();
if (string.IsNullOrWhiteSpace(chatid))
GetChatIdforToken();
#region 推送信息
IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/chat/send");
OapiChatSendRequest req = new OapiChatSendRequest();
req.Chatid = chatid;
req.Msgtype = "markdown";
OapiChatSendRequest.MarkdownDomain obj1 = new OapiChatSendRequest.MarkdownDomain();
obj1.Title = title;
obj1.Text = msg;
req.Markdown_ = obj1;
OapiChatSendResponse rsp = client.Execute(req, access_token);
#endregion
}
原文:https://www.cnblogs.com/Worknotes/p/14436261.html