一、注册企业钉钉
1、登陆企业钉钉,并选择开发平台
2、登陆开发者后台
3、选择应用 ,点击创建应用,前面默认必填项都填写好并点击下一步
4、主要讲一下服务器IP,其实就是白名单,就是钉钉允许访问它接口的IP地址 ,可以使用这个网址来查看本机IP
5、点击进入新创建好的应用,并选择接口权限,后把高级权限-企业通讯录都申请授权,以便都过手机号获取userid
二、查看开发文档,获取钉钉提供的官方SDK,按自己需求下载对于的SDK,我就选择.NET的下载并把TopSdk.dll引入相关项目
AccessToken.xml的格式:
utXRVL1FWalC3cDm-0jv_NXcVFz1TpW6MCnQQim0VKOus2wYjLt4j4jS678w9OsGCIEuBuXj3dgK7Zbv5Z1gUFvNZFxd9a0-1FseLxujuf65Z8ippqkmhDqBZeu64dO08LKS6hoBhBgGkntn4GZgs1ALi_-70FVwbMeX1f4y-zUXHVbmn7GMpcFLmZ7GXqbdbF7-6OCHvcmQOluS3J62GA
2019/11/18 16:41:41
1、获取accessToken,并存储到本地xml,记录获取时间,来判断是否过期
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
///
/// OperationXml 的摘要说明
///
public class OperationXml
{
public OperationXml()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
///
/// 获取XML文件路径
///
public static string xmlName = AppDomain.CurrentDomain.BaseDirectory + @"AccessToken.xml";
///
/// 读取XML Token
///
///
///
public static string GetXMLToken()
{
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlName);
XmlNode xn = xmlDoc.SelectSingleNode("ACCESS_TOKEN");
XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型
string Token = "";
string CreateTime = "";
foreach (XmlNode xn1 in xe)//遍历
{
XmlElement xe2 = (XmlElement)xn1;//转换类型
if (xe2.Name == "Token")//如果找到
{
Token = xe2.InnerText;//则修改
}
if (xe2.Name == "CreateTime")//如果找到
{
CreateTime = xe2.InnerText;//则修改
}
}
int seconds = 0;
if (CreateTime.Trim() != "")
{
DateTime ct = Convert.ToDateTime(CreateTime);
TimeSpan ts = (DateTime.Now - ct);
seconds =ts.Days*24*60*60+ts.Hours*60*60+ts.Seconds+Convert.ToInt32(ts.Milliseconds*0.001);
}
MessageHelper.WriteLog("Token:" + Token);
if (seconds > 7200 || seconds == 0)
{
return "";
}
else
{
return Token;
}
}
catch (Exception ex)
{
MessageHelper.WriteLog("异常:" + ex.ToString());
return "";
}
}
///
/// 修改Token
///
///
///
public static void UpdateXMLToken(string token, DateTime createTime)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlName);
XmlNode xn = xmlDoc.SelectSingleNode("ACCESS_TOKEN");
XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型
foreach (XmlNode xn1 in xe)//遍历
{
XmlElement xe2 = (XmlElement)xn1;//转换类型
if (xe2.Name == "Token")//如果找到
{
xe2.InnerText = token;//则修改
}
if (xe2.Name == "CreateTime")//如果找到
{
xe2.InnerText = createTime.ToString();//则修改
}
}
xmlDoc.Save(xmlName);
}
}
2、钉钉消息发送工具类源码
using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
///
/// Test 的摘要说明
///
public class DingDingUtil
{
public DingDingUtil()
{
}
public string getAccessToken()
{
string token = OperationXml.GetXMLToken();
if (token == "")
{
DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
OapiGettokenRequest request = new OapiGettokenRequest();
request.Appkey = "dingch9jauuv7cxeu4f6";
request.Appsecret = "tIom9d5h0FSbfCLGloiHgX-6_LbpbpFKwfB6HLQYzWpkAIAV_9dPOo7TO4Z38G6H";
request.SetHttpMethod("GET");
OapiGettokenResponse response = client.Execute(request);
OperationXml.UpdateXMLToken(response.AccessToken, DateTime.Now);
token = response.AccessToken;
}
return token;
}
public string sendMessage()
{
IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
request.UseridList= getUserIdByPhone("13260550213");
request.AgentId=long.Parse("326528237");
request.ToAllUser=false;
OapiMessageCorpconversationAsyncsendV2Request.MsgDomain msg = new OapiMessageCorpconversationAsyncsendV2Request.MsgDomain();
//msg.Msgtype="text";
//msg.Text=new OapiMessageCorpconversationAsyncsendV2Request.TextDomain();
//msg.Text.Content="test123";
//request.Msg_=msg;
//msg.setMsgtype("image");
//msg.setImage(new OapiMessageCorpconversationAsyncsendV2Request.Image());
//msg.getImage().setMediaId("@lADOdvRYes0CbM0CbA");
//request.setMsg(msg);
//msg.setMsgtype("file");
//msg.setFile(new OapiMessageCorpconversationAsyncsendV2Request.File());
//msg.getFile().setMediaId("@lADOdvRYes0CbM0CbA");
//request.setMsg(msg);
//msg.setMsgtype("link");
//msg.setLink(new OapiMessageCorpconversationAsyncsendV2Request.Link());
//msg.getLink().setTitle("test");
//msg.getLink().setText("test");
//msg.getLink().setMessageUrl("test");
//msg.getLink().setPicUrl("test");
//request.setMsg(msg);
//msg.Msgtype="markdown";
//msg.Markdown=(new OapiMessageCorpconversationAsyncsendV2Request.MarkdownDomain());
//msg.Markdown.Text="##### text";
//msg.Markdown.Title="### Title";
//request.Msg_=msg;
msg.Oa=(new OapiMessageCorpconversationAsyncsendV2Request.OADomain());
msg.Oa.Head=(new OapiMessageCorpconversationAsyncsendV2Request.HeadDomain());
msg.Oa.Head.Text="head";
msg.Oa.Body=(new OapiMessageCorpconversationAsyncsendV2Request.BodyDomain());
msg.Oa.Body.Content=@"异常消息通知
一号班组出现一异常";
msg.Msgtype="oa";
request.Msg_=msg;
//msg.ActionCard=(new OapiMessageCorpconversationAsyncsendV2Request.ActionCardDomain());
//msg.ActionCard.Title="异常消息发送通知";
//msg.ActionCard.Markdown= "异常消息发送通知";
//msg.ActionCard.SingleTitle="测试测试
sssss";
//msg.ActionCard.SingleUrl = "https://www.baidu.com";
//msg.Msgtype="action_card";
//request.Msg_=msg;
OapiMessageCorpconversationAsyncsendV2Response response = client.Execute(request, getAccessToken());
return response.Body;
}
public void getUserIdBydepartment()
{
IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getDeptMember");
OapiUserGetDeptMemberRequest req = new OapiUserGetDeptMemberRequest();
req.DeptId="xxx";
req.SetHttpMethod("GET");
OapiUserGetDeptMemberResponse rsp = client.Execute(req, getAccessToken());
string ss = rsp.Body;
}
public string getAdminList()
{
IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get_admin");
OapiUserGetAdminRequest request = new OapiUserGetAdminRequest();
request.SetHttpMethod("GET");
OapiUserGetAdminResponse response = client.Execute(request, getAccessToken());
return response.Body;
}
public string getUserIdByPhone(string phoneNum)
{
IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get_by_mobile");
OapiUserGetByMobileRequest request = new OapiUserGetByMobileRequest();
request.Mobile= phoneNum;
request.SetHttpMethod("GET");
OapiUserGetByMobileResponse response = client.Execute(request, getAccessToken());
return GetJsonValue(response.Body, "userid");
}
#region 获取Json字符串某节点的值
///
/// 获取Json字符串某节点的值
///
public static string GetJsonValue(string jsonStr, string key)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(jsonStr))
{
key = "\"" + key.Trim('"') + "\"";
int index = jsonStr.IndexOf(key) + key.Length + 1;
if (index > key.Length + 1)
{
//先截逗号,若是最后一个,截“}”号,取最小值
int end = jsonStr.IndexOf(',', index);
if (end == -1)
{
end = jsonStr.IndexOf('}', index);
}
result = jsonStr.Substring(index, end - index);
result = result.Trim(new char[] { '"', ' ', '\'' }); //过滤引号或空格
}
}
return result;
}
#endregion
}