C# 企业微信API开发(获取Token,给用户发送消息)

        #region 获取Token
        /// <summary>
        /// 获取Token
        /// </summary>
        public string GetAccessToken()
        {
            string requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=xxxxxxxxx&corpsecret=xxxxxxxxxxxxxxxxxxxxxxxx";
            WebResponse result = null;
            WebRequest req = WebRequest.Create(requestUrl);
            result = req.GetResponse();
            Stream s = result.GetResponseStream();
            XmlDictionaryReader xmlReader = JsonReaderWriterFactory.CreateJsonReader(s, XmlDictionaryReaderQuotas.Max);
            xmlReader.Read();
            string xml = xmlReader.ReadOuterXml();
            s.Close();
            s.Dispose();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlElement rootElement = doc.DocumentElement;
            string access_token = rootElement.SelectSingleNode("access_token").InnerText.Trim();
            return access_token;
        }
        #endregion

以上代码需要引用如下dll文件

 

#region 给用户发送消息
        public void SendMessage( string userid,string strtext) 
        {
            string retString = string.Empty;
            string url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}";//string url = GetUrlString;
            url = string.Format(url, GetAccessToken());
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";
            //序列化为字符串,可以使用自己项目中封装的json方法
            string strContent = "{\"touser\" : \"" + userid + "\",\"msgtype\" : \"text\",\"agentid\" : 应用程序ID,\"text\" : {\"content\" : \"" + strtext + "\"},\"safe\":0}";
            using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
            {
                dataStream.Write(strContent);
                dataStream.Close();
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string encoding = response.ContentEncoding;
            if (encoding == null || encoding.Length < 1)
            {
                encoding = "UTF-8"; //默认编码  
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
            retString = reader.ReadToEnd();
        
        }
        #endregion

其中多个用户ID以‘|’隔开 例如  “LEIGANG|XIAOHONG|ZAHNGWU”

 

posted @ 2020-10-14 17:38  幸运(● ̄(エ) ̄●)  阅读(2069)  评论(0编辑  收藏  举报
Document