欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# 企业微信消息推送

程序员文章站 2024-03-13 12:48:51
...

企业微信开发API文档链接

第一步 注册企业微信

只需要填写下基本资料就可以。

C# 企业微信消息推送

第二步

记下企业微信 CorpID

C# 企业微信消息推送

第三步 创建应用,并记下 AgentId与Secret

C# 企业微信消息推送
C# 企业微信消息推送
C# 企业微信消息推送

第四步 写代码实现App内推送消息

  1. 新建项目(本文以类库项目为例)
    C# 企业微信消息推送
    在实际项目项目中引用时,需配置一下关键值。
    C# 企业微信消息推送
    CorpSendBase:企业号发送消息的基类,因为消息类别有多种,可以推送文本、图片、视频、文件、图文等类型。

    /// <summary>
    /// 企业号发送消息的基础消息内容
    /// </summary>
    class CorpSendBase
    {
        /// <summary>
        /// UserID列表(消息接收者,多个接收者用‘|’分隔)。特殊情况:指定为@all,则向关注该企业应用的全部成员发送
        /// </summary>
        public string touser { get; set; }
        /// <summary>
        /// PartyID列表,多个接受者用‘|’分隔。当touser为@all时忽略本参数
        /// </summary>
        public string toparty { get; set; }
        /// <summary>
        /// TagID列表,多个接受者用‘|’分隔。当touser为@all时忽略本参数
        /// </summary>
        public string totag { get; set; }
        /// <summary>
        /// 消息类型
        /// </summary>
        public string msgtype { get; set; }
        /// <summary>
        /// 企业应用的id,整型。可在应用的设置页面查看
        /// </summary>
        public string agentid { get; set; }
        /// <summary>
        /// 表示是否是保密消息,0表示否,1表示是,默认0
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string safe { get; set; }
        public CorpSendBase()
        {
            this.agentid = System.Configuration.ConfigurationManager.AppSettings["CorpSendBaseAgentID"].ToString();
            this.safe = "0";
        }
    }

    CorpSendText:用来发送文本消息。

    class Text
    {
        private string _content;
        /// <summary>
        /// 要发送的文本内容字段,必须小写,企业微信API不识别大写。
        /// </summary>
        public string content
        {
            get { return _content; }
            set { _content = value; }
        }
    
    }
    class CorpSendText: CorpSendBase
    {
        private Text _text;
        /// <summary>
        /// 要发送的文本,必须小写,企业微信API不识别大写。
        /// </summary>
        public Text text
        {
            get { return _text; }
            set { this._text = value; }
        }
    
    
        public CorpSendText(string content)
        {
            base.msgtype = "text";
            this.text = new Text
            {
                content = content
            };
        }
    }

    QYWeixinHelper:消息发送工具类。

    public class QYWeixinHelper
    {
        static string corpid = System.Configuration.ConfigurationManager.AppSettings["corpid"].ToString();
        static string corpsecret = System.Configuration.ConfigurationManager.AppSettings["secret"].ToString();
        static string messageSendURI = System.Configuration.ConfigurationManager.AppSettings["messageSendURI"].ToString();
    
        /// <summary>
        /// 获取企业号的accessToken
        /// </summary>
        /// <param name="corpid">企业号ID</param>
        /// <param name="corpsecret">管理组**</param>
        /// <returns></returns>
        static string GetQYAccessToken(string corpid, string corpsecret)
        {
            string getAccessTokenUrl = System.Configuration.ConfigurationManager.AppSettings["getAccessTokenUrl"].ToString(); 
            string accessToken = "";
    
            string respText = "";
    
            //获取josn数据
            string url = string.Format(getAccessTokenUrl, corpid, corpsecret);
    
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
            using (Stream resStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(resStream, Encoding.Default);
                respText = reader.ReadToEnd();
                resStream.Close();
            }
    
            try
            {
                JavaScriptSerializer Jss = new JavaScriptSerializer();
                Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);
                //通过键access_token获取值
                accessToken = respDic["access_token"].ToString();
            }
            catch (Exception) { }
    
            return accessToken;
        }
    
        /// <summary>
        /// Post数据接口
        /// </summary>
        /// <param name="postUrl">接口地址</param>
        /// <param name="paramData">提交json数据</param>
        /// <param name="dataEncode">编码方式</param>
        /// <returns></returns>
        static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
        {
            string ret = string.Empty;
            try
            {
                byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
    
                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return ret;
        }
    
        /// <summary>
        /// 推送信息
        /// </summary>
        /// <param name="corpid">企业号ID</param>
        /// <param name="corpsecret">管理组**</param>
        /// <param name="paramData">提交的数据json</param>
        /// <param name="dataEncode">编码方式</param>
        /// <returns></returns>
        public static void SendText(string empCode, string message)
        {
            string accessToken = "";
            string postUrl = "";
            string param = "";
            string postResult = "";
    
            accessToken = GetQYAccessToken(corpid, corpsecret);
            postUrl = string.Format(messageSendURI, accessToken);
            CorpSendText paramData = new CorpSendText(message);
            foreach (string item in empCode.Split('|'))
            {
                //paramData.touser = GetOAUserId(item);//在实际应用中需要判断接收消息的成员是否在系统账号中存在。
                paramData.touser = item;
                param = JsonConvert.SerializeObject(paramData);
                if (paramData.touser != null)
                {
                    postResult = PostWebRequest(postUrl, param, Encoding.UTF8);
                }
                else
                {
                    postResult = "账号" + paramData.touser + "在OA中不存在!";
                }
                CreateLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss") + ":\t" + item + "\t" + param + "\t" + postResult);
            }
        }
    
        private static void CreateLog(string strlog)
        {
            string str1 = "QYWeixin_log" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            //BS CS应用日志自适应
            string path = System.Web.HttpContext.Current == null ? Path.GetFullPath("..") + "\\temp\\" : System.Web.HttpContext.Current.Server.MapPath("temp");
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path = Path.Combine(path, str1);
                StreamWriter sw = File.AppendText(path);
                sw.WriteLine(strlog);
                sw.Flush();
                sw.Close();
    
            }
            catch
            {
            }
        }

第五步 测试消息推送

    class Program
    {
        static void Main(string[] args)
        {
            string touser = "Kiaka";";
            Console.WriteLine("回车终止:");
            do
            {
                QYWeixin.QYWeixinHelper.SendText(touser, "消息推送测试_:</br>"+"a:"+"xxx" + DateTime.Now.ToString());
            } while (Console.ReadKey().Key != ConsoleKey.Enter);
        }
    }