C#实现钉钉消息推送

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

利用钉钉提供的API可以推送消息到用户的钉钉app。根据钉钉的官方文档
1.首先登陆钉钉开发者后台 https://ding-doc.dingtalk.com/
C#实现钉钉消息推送_第1张图片

2.选择H5微应用,创建应用
C#实现钉钉消息推送_第2张图片
3.创建好了接口测试应用拿到对应的ID
C#实现钉钉消息推送_第3张图片
4.废话不多说直接上代码
我们首先建立一个工具类,用于post get的请求
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;
            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 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 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;

    }
    6.我们建立控制台程序
       HelperTools tool = new HelperTools();
        //这个接口是获取部门详细信息的
        string urls = "https://oapi.dingtalk.com/topapi/v2/department/get";
        Dictionary listS = new Dictionary();
        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 listt = new Dictionary();
        listt.Add("access_token", tool.GetDingAccessToken().ToString());
        listt.Add("dept_id", "469642677");
        string strr = tool.Post(urlt, listt);
        //这个是发送请求的接口 发送消息
        Dictionary list = new Dictionary();
        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);
  7.直接看效果图 接口的调用对应参数 ,钉钉文档有写

C#实现钉钉消息推送_第4张图片

好了,这样就大功告成了!!!

你可能感兴趣的:(技术,C#,ajax,接口,http,c#)