.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

             IDingTalkClient client = new DefaultDingTalkClient("https://eco.taobao.com/router/rest");
CorpMessageCorpconversationAsyncsendRequest req = new CorpMessageCorpconversationAsyncsendRequest();
req.Msgtype = "oa";//发送消息是以oa的形式发送的,其他的还有text,image等形式
req.AgentId = ;//微应用ID
req.UseridList = "manager7626";//收信息的userId,这个是by公司来区分,在该公司内这是一个唯一标识符
req.DeptIdList = "123,456";//部门ID
req.ToAllUser = false;//是否发给所有人
        //消息文本
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\": \"李四 \"}}";
CorpMessageCorpconversationAsyncsendResponse rsp = client.Execute(req, "402107cac8ff329d91baa5b2b7797068");//发送消息

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

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

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

1.创建测试企业

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

2.创建微应用

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

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

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

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

2.获得access_token

1>获得CorpId和CorpSecret

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

2>获得access_token

全部上代码了

专门用一个类来封装。

 using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication6
{
public class Class1
{ //https://oapi.dingtalk.com/gettoken?corpid=ding892914b21488a37b35c2f4657eb6378f&corpsecret=XVP6U8FCqj-9trQ8zDDCgZILXGH6Q4FXu40h4_-_MztCWy4w0KVPaP3ZIoLDuSRJ /// <summary>
/// CorpId
/// </summary>
private static string CorpId = "CorpId:ding892914b21488a37b35c2f4657eb6378f ";
/// <summary>
/// CorpSecret
/// </summary>
private static string CorpSecret = "XVP6U8FCqj-9trQ8zDDCgZILXGH6Q4FXu40h4_-_MztCWy4w0KVPaP3ZIoLDuSRJ"; private static int AgentID = ; private static DateTime GetTime { get; set; } //public DingTalkApiService()
//{
// if (string.IsNullOrEmpty(Access_Token))
// {
// GetAccessToken();//重新发送get请求获得获得access_token值
// }
//}
public Class1()
{
if (string.IsNullOrEmpty(Access_Token))
{
Access_Token = GetAccessToken();
}
} private static string Access_Token { get; set; } public string GetAccessToken()
{
//根据CorpId和CorpSecret发送get请求获得access_token
string url = "https://oapi.dingtalk.com/gettoken?corpid=" + CorpId + "&corpsecret=" + CorpSecret;
//创建请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //GET请求
request.Method = "GET";
request.ReadWriteTimeout = ;
Encoding encode = Encoding.UTF8;
//request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, encode); //返回内容
string retString = myStreamReader.ReadToEnd(); JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(retString);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(AccessToken));
AccessToken t = o as AccessToken; string m = t.Access_Token;
//AccessToken entity=JsonHelper
//string s= myStreamReader.ReadLineAsync();
string accessToken = retString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[].Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries)[].Replace("\"", "");
//string[] t = retString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
//string s = t[1];
//string a = s.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries)[1];
return accessToken;
} //根据传进来的人获得钉钉的userid public string GetDepartment(string depName)
{
string url = "https://oapi.dingtalk.com/department/list?access_token=" + Access_Token; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//GET请求
request.Method = "GET";
request.ReadWriteTimeout = ;
Encoding encode = Encoding.UTF8;
//request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, encode); //返回内容
string retString = myStreamReader.ReadToEnd();
//{"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"}
//var department = new { name = string.Empty, id = 0, autoAddUser = false, parentid =1};
//var tempEntity = new { errcode = string.Empty, List<department>=null, errmsg=string.Empty };
DepartmentJson dep = new DepartmentJson();
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(retString);
//tempEntity = JsonConvert.DeserializeAnonymousType(retString, tempEntity);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(DepartmentJson));
DepartmentJson t = o as DepartmentJson; List<department> s = t.department; string m = s.Where(p => p.Name == "运营部").Select(w => w.Name).ToList().ToString();
var id = s.Where(p => p.Name == "运营部").Select(x => x.id).ToList()[]; url = "https://oapi.dingtalk.com/user/simplelist?access_token=" + Access_Token + "&department_id=" + id; HttpWebRequest requestNew = (HttpWebRequest)WebRequest.Create(url);
//GET请求
requestNew.Method = "GET";
requestNew.ReadWriteTimeout = ;
//Encoding encode = Encoding.UTF8;
//request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse responseNew = (HttpWebResponse)requestNew.GetResponse();
Stream myResponseStreamNew = responseNew.GetResponseStream();
StreamReader myStreamReaderNew = new StreamReader(myResponseStreamNew, encode); //返回内容
string retStringNew = myStreamReaderNew.ReadToEnd(); //{"errcode":0,"errmsg":"ok","userlist":[{"name":"张三","userid":"33333333333333333333333333"},{"name":"李四","userid":"3333333333333333"},{"name":"王五","userid":"333333333333"},{"name":"赵六","userid":"4444444444444"}]}
UserJson user = new UserJson();
//JsonSerializer serializer = new JsonSerializer();
StringReader srNew = new StringReader(retStringNew);
//tempEntity = JsonConvert.DeserializeAnonymousType(retString, tempEntity);
object oNew = serializer.Deserialize(new JsonTextReader(srNew), typeof(UserJson));
UserJson v = oNew as UserJson; List<Users> z = v.userlist; var q = z.Where(p => p.Name == "李七").Select(i => i.UserId).ToList()[];
decimal b = Convert.ToDecimal(q);
return b + "ddddd";
} }
}

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

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

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

上一篇:HDU 4907 Task schedule


下一篇:使用web api开发微信公众号,调用图灵机器人接口(二)