.Net调用钉钉接口,实现发送企业消息功能

我在钉钉官网上看了下,关于调用钉钉接口,发送企业消息通知,他给的核心代码总共几行。

用到的一个接口引用

TopSDK.dll 下载网址https://open-doc.dingtalk.com/doc/sdk.htm?spm=a219a.7629140.0.0.mItbfA&treeId=177&articleId=104963&docType=1 选择 .Net版本TOP接入SDK

1             IDingTalkClient client = new DefaultDingTalkClient("https://eco.taobao.com/router/rest");
2             CorpMessageCorpconversationAsyncsendRequest req = new CorpMessageCorpconversationAsyncsendRequest();
3             req.Msgtype = "oa";//发送消息是以oa的形式发送的,其他的还有text,image等形式
4             req.AgentId = 167524917;//微应用ID
5             req.UseridList = "manager7626";//收信息的userId,这个是by公司来区分,在该公司内这是一个唯一标识符
6             req.DeptIdList = "123,456";//部门ID
7             req.ToAllUser = false;//是否发给所有人
        //消息文本
8 req.Msgcontent = "{\"message_url\": \"http://dingtalk.com\",\"head\": {\"bgcolor\": \"FFBBBBBB\",\"text\": \"头部标题\"},\"body\": {\"title\": \"测试文本\",\"form\": [{\"key\": \"姓名:\",\"value\": \"张三\"},{\"key\": \"爱好:\",\"value\": \"打球、听音乐\"}],\"rich\": {\"num\": \"15.6\",\"unit\": \"元\"},\"content\": \"大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本大段文本\",\"image\": \"@lADOADmaWMzazQKA\",\"file_count\": \"3\",\"author\": \"李四 \"}}"; 9 CorpMessageCorpconversationAsyncsendResponse rsp = client.Execute(req, "402107cac8ff329d91baa5b2b7797068");//发送消息

这是钉钉官网上给的Demo。我把代码改copy下来以后,改成我的userid和我的access_token以后,提交的代码。执行以后,我的钉钉收到以下提示:

.Net调用钉钉接口,实现发送企业消息功能_第1张图片

好了,效果达到了,接下详细说说我的代码过程。

 1.创建测试企业

在钉钉上面创建一个测试企业。这是用来测试的。

2.创建微应用

在钉钉左边点击那四个正方形堆在一起的按钮==》进入应用中心==》管理应用==》进入管理后台==》工作台==》创建一个应用==》拿到AgentId.

这个值很重要,企业通知消息就是通过这个微信用发送出去的。

.Net调用钉钉接口,实现发送企业消息功能_第2张图片

 

 2.获得access_token

1>获得CorpId和CorpSecret

 

 .Net调用钉钉接口,实现发送企业消息功能_第3张图片

 

 2>获得access_token

全部上代码了

专门用一个类来封装。

  1 using Newtonsoft.Json;
  2 using System;
  3 using System.Collections.Generic;
  4 using System.IO;
  5 using System.Linq;
  6 using System.Net;
  7 using System.Text;
  8 using System.Threading.Tasks;
  9 
 10 
 11 
 12 namespace ConsoleApplication6
 13 {
 14     public class Class1
 15     {
 16 
 17         //https://oapi.dingtalk.com/gettoken?corpid=ding892914b21488a37b35c2f4657eb6378f&corpsecret=XVP6U8FCqj-9trQ8zDDCgZILXGH6Q4FXu40h4_-_MztCWy4w0KVPaP3ZIoLDuSRJ
 18 
 19         /// 
 20         /// CorpId
 21         /// 
 22         private static string CorpId = "CorpId:ding892914b21488a37b35c2f4657eb6378f ";
 23         /// 
 24         /// CorpSecret
 25         /// 
 26         private static string CorpSecret = "XVP6U8FCqj-9trQ8zDDCgZILXGH6Q4FXu40h4_-_MztCWy4w0KVPaP3ZIoLDuSRJ";
 27 
 28         private static int AgentID = 167524917;
 29 
 30 
 31 
 32         private static DateTime GetTime { get; set; }
 33 
 34         //public DingTalkApiService()
 35         //{
 36         //    if (string.IsNullOrEmpty(Access_Token))
 37         //    {
 38         //        GetAccessToken();//重新发送get请求获得获得access_token值
 39         //    }
 40         //}
 41         public Class1()
 42         {
 43             if (string.IsNullOrEmpty(Access_Token))
 44             {
 45                 Access_Token = GetAccessToken();
 46             }
 47         }
 48 
 49 
 50         private static string Access_Token { get; set; }
 51 
 52         public string GetAccessToken()
 53         {
 54             //根据CorpId和CorpSecret发送get请求获得access_token
 55             string url = "https://oapi.dingtalk.com/gettoken?corpid=" + CorpId + "&corpsecret=" + CorpSecret;
 56             //创建请求
 57             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 58 
 59             //GET请求
 60             request.Method = "GET";
 61             request.ReadWriteTimeout = 5000;
 62             Encoding encode = Encoding.UTF8;
 63             //request.ContentType = "text/html;charset=UTF-8";
 64             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 65             Stream myResponseStream = response.GetResponseStream();
 66             StreamReader myStreamReader = new StreamReader(myResponseStream, encode);
 67 
 68             //返回内容
 69             string retString = myStreamReader.ReadToEnd();
 70 
 71             JsonSerializer serializer = new JsonSerializer();
 72             StringReader sr = new StringReader(retString);
 73             object o = serializer.Deserialize(new JsonTextReader(sr), typeof(AccessToken));
 74             AccessToken t = o as AccessToken;
 75 
 76             string m = t.Access_Token;
 77             //AccessToken entity=JsonHelper
 78             //string s=    myStreamReader.ReadLineAsync();
 79             string accessToken = retString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[1].Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries)[1].Replace("\"", "");
 80             //string[] t = retString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
 81             //string s = t[1];
 82             //string a = s.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries)[1];
 83             return accessToken;
 84         }
 85 
 86         //根据传进来的人获得钉钉的userid
 87 
 88         public string GetDepartment(string depName)
 89         {
 90             string url = "https://oapi.dingtalk.com/department/list?access_token=" + Access_Token;
 91 
 92             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 93             //GET请求
 94             request.Method = "GET";
 95             request.ReadWriteTimeout = 5000;
 96             Encoding encode = Encoding.UTF8;
 97             //request.ContentType = "text/html;charset=UTF-8";
 98             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 99             Stream myResponseStream = response.GetResponseStream();
100             StreamReader myStreamReader = new StreamReader(myResponseStream, encode);
101 
102             //返回内容
103             string retString = myStreamReader.ReadToEnd();
104             //{"errcode":0,"department":[{"createDeptGroup":true,"name":"公司Test","id":1,"autoAddUser":true},{"createDeptGroup":false,"name":"运营部","id":61877829,"autoAddUser":false,"parentid":1},{"createDeptGroup":false,"name":"推广部","id":61933824,"autoAddUser":false,"parentid":1},{"createDeptGroup":false,"name":"生产部","id":61939784,"autoAddUser":false,"parentid":1},{"createDeptGroup":false,"name":"产品部","id":61943823,"autoAddUser":false,"parentid":1},{"createDeptGroup":false,"name":"物流部","id":61985767,"autoAddUser":false,"parentid":1},{"createDeptGroup":false,"name":"设计部","id":62021758,"autoAddUser":false,"parentid":1}],"errmsg":"ok"}
105             //var department = new { name = string.Empty, id = 0, autoAddUser = false, parentid =1};
106             //var tempEntity = new { errcode = string.Empty, List=null, errmsg=string.Empty };
107             DepartmentJson dep = new DepartmentJson();
108             JsonSerializer serializer = new JsonSerializer();
109             StringReader sr = new StringReader(retString);
110             //tempEntity = JsonConvert.DeserializeAnonymousType(retString, tempEntity);
111             object o = serializer.Deserialize(new JsonTextReader(sr), typeof(DepartmentJson));
112             DepartmentJson t = o as DepartmentJson;
113 
114             List s = t.department;
115 
116             string m = s.Where(p => p.Name == "运营部").Select(w => w.Name).ToList().ToString();
117             var id = s.Where(p => p.Name == "运营部").Select(x => x.id).ToList()[0];
118 
119 
120             url = "https://oapi.dingtalk.com/user/simplelist?access_token=" + Access_Token + "&department_id=" + id;
121 
122             HttpWebRequest requestNew = (HttpWebRequest)WebRequest.Create(url);
123             //GET请求
124             requestNew.Method = "GET";
125             requestNew.ReadWriteTimeout = 5000;
126             //Encoding encode = Encoding.UTF8;
127             //request.ContentType = "text/html;charset=UTF-8";
128             HttpWebResponse responseNew = (HttpWebResponse)requestNew.GetResponse();
129             Stream myResponseStreamNew = responseNew.GetResponseStream();
130             StreamReader myStreamReaderNew = new StreamReader(myResponseStreamNew, encode);
131 
132             //返回内容
133             string retStringNew = myStreamReaderNew.ReadToEnd();
134 
135             //{"errcode":0,"errmsg":"ok","userlist":[{"name":"张三","userid":"33333333333333333333333333"},{"name":"李四","userid":"3333333333333333"},{"name":"王五","userid":"333333333333"},{"name":"赵六","userid":"4444444444444"}]}
136             UserJson user = new UserJson();
137             //JsonSerializer serializer = new JsonSerializer();
138             StringReader srNew = new StringReader(retStringNew);
139             //tempEntity = JsonConvert.DeserializeAnonymousType(retString, tempEntity);
140             object oNew = serializer.Deserialize(new JsonTextReader(srNew), typeof(UserJson));
141             UserJson v = oNew as UserJson;
142 
143             List z = v.userlist;
144 
145 
146             var q = z.Where(p => p.Name == "李七").Select(i => i.UserId).ToList()[0];
147             decimal b = Convert.ToDecimal(q);
148             return b + "ddddd";
149         }
150 
151     }
152 }

里面用到的一些类都是根据返回结果封装的一些类,用于json的反序列化时存值。

这是自己写的一个小测试Demo.

一切为了测试,所以很多一些编程习惯和命名习惯都没有遵守。权当大家作一个参考!

你可能感兴趣的:(.Net调用钉钉接口,实现发送企业消息功能)