C#钉钉信息推送

本文实例讲述了C#实现推送钉钉消息的方法。分享给大家供大家参考,具体如下:

利用钉钉提供的API可以推送消息到用户的钉钉app。根据钉钉的官方文档
1.首先进入钉钉后台管理
C#钉钉信息推送_第1张图片
2.创建应用
C#钉钉信息推送_第2张图片
C#钉钉信息推送_第3张图片
3.获取已创建应用的对应的ID
C#钉钉信息推送_第4张图片
4.获取钉钉接口SDK
https://developers.dingtalk.com/document/app/sdk-download
C#钉钉信息推送_第5张图片
5.开始敲代码了,首先创建项目
C#钉钉信息推送_第6张图片
6.引用钉钉下载sdk中的TopSdk.dll
C#钉钉信息推送_第7张图片
7.直接上代码,先写一个工具类用于get,post请求

public class HelperTools
    {
        string DingAppkey = "ding4vnqvr37dshot4zh";//钉钉  应用的唯一标识key
        string DingAppsecret = "6Dy4pH0JnFylnAFffkyWktV6chPJwp35AtEZS5DYXXOOO2E3S7LsaVzhYCa4-AXR";//钉钉  应用的密钥
        public static string dingAccessToken = "1120087037"; //钉钉接口调用凭证
                                                             // 
        /// 调用钉钉的api需要一个AccessToken,我们先获取这个AccessToken。
        /// 
        /// 
        public string GetDingAccessToken()
        {
            string access_token = string.Empty;
            try
            {
                string accessToken = string.Empty;
                //引用钉钉SDK的dll文件
                DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
                OapiGettokenRequest request = new OapiGettokenRequest();
                request.Appkey = DingAppkey;//钉钉  应用的唯一标识key
                request.Appsecret = DingAppsecret;//钉钉  应用的密钥
                request.SetHttpMethod("GET");
                OapiGettokenResponse response = client.Execute(request);
                access_token = response.AccessToken;
            }
            catch (Exception ex)
            {


            }
            return access_token;
        }
        /// 
        /// 指定Post地址使用Get 方式获取全部字符串
        /// 
        /// 请求后台地址
        /// 
        public string Post(string url, Dictionary<string, string> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;

        }

        /// 
        /// 发送Get请求
        /// 
        /// 地址
        /// 请求参数定义
        /// 
        public string Get(string url, Dictionary<string, string> dic)
        {
            string result = "";
            StringBuilder builder = new StringBuilder();
            builder.Append(url);
            if (dic.Count > 0)
            {
                builder.Append("?");
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
            }
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(builder.ToString());
            //添加参数
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            try
            {
                //获取内容
                using (StreamReader reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                }
            }
            finally
            {
                stream.Close();
            }
            return result;

        }

    }

8.调用接口

class Program
    {
        static void Main(string[] args)
        {
            HelperTools tool = new HelperTools();
            //这个接口是获取部门详细信息的
            string urls = "https://oapi.dingtalk.com/topapi/v2/department/get";
            Dictionary<string, string> listS = new Dictionary<string, string>();
            listS.Add("access_token", tool.GetDingAccessToken().ToString());
            listS.Add("dept_id", "469642677");
            listS.Add("language", "zh_CN");
            string str = tool.Get(urls, listS);
            //这个是根据部门ID查询对应下面人的userid_list
            string urlt = "https://oapi.dingtalk.com/topapi/user/listid";
            Dictionary<string, string> listt = new Dictionary<string, string>();
            listt.Add("access_token", tool.GetDingAccessToken().ToString());
            listt.Add("dept_id", "469642677");
            string strr = tool.Post(urlt, listt);
            //这个是发送请求的接口 发送消息
            Dictionary<string, string> list = new Dictionary<string, string>();
            string url = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" + tool.GetDingAccessToken().ToString();
            list.Add("agent_id", "1120087037");
            list.Add("userid_list", "manager6916");
            list.Add("dept_id_list", "469642677");
            list.Add("to_all_user", "false");//这个false 可以针对单个部门 或者单个人,如果设成true 就是对全公司的发信息
                                             //这个你只需要改content 里面的内容就可以了  这个内容不能重复 重复的话 就只能发一次
            string Msg = "{\"msgtype\": \"text\",\"text\": {\"content\": \"月会通知" + DateTime.Now.ToString() + "\"}}";
            list.Add("msg", Msg);
            //这是返回调用接口的结果
            string msg = tool.Post(url, list);
        }
    }

9.直接看效果图 接口的调用对应参数 ,钉钉文档有写
C#钉钉信息推送_第8张图片
希望这篇文章对你有用

你可能感兴趣的:(c#,restful,mvc)