ASP.NETwebService通过企业微信API向用户推送消息

     最近在做项目的时候,发现需要将某些消息自动发送到用户的企业微信中。研究一整天写出来webservice的方法去给企业微信发送消息。

/// 
        /// 
        /// 
        /// 公司id
        /// 企业微信应用Secret值
        /// 传达人全选@all
        /// 企业微信应用编号
        /// 传输内容
        /// 
[WebMethod(Description = "发送推送信息")]
        public string Unnamed_Click(string corpid,string corpsecret, string touser,string agentid,string content)
        {
            string strReturn = "";
            string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+ corpid + "&corpsecret="+ corpsecret;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            Encoding encoding = Encoding.UTF8;
            request.Method = "GET";
            string responseData = String.Empty;
            request.ContentType = "application/json; charset=UTF-8";
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd();
                }
                将返回的结果将access_token切割起来
                string[] a = responseData.Split(',');
                string[] b = a[2].Split('"');
                string sendMsgUrl = string.Format("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}", b[3]);
                string temp = "{\"touser\": \""+ touser + "\"," +
                "\"template_id\": \"f3kRRjJeyLDf4tndtg-OJeRvgEdgjjDxCy4T9kuwM70\", " +
                "\"topcolor\": \"#FF0000\", " +
                "\"msgtype\" :\"text\"," +
                "\"agentid\" :\""+ agentid + "\"," +
                "\"text\": {\"content\": \""+ content + "\"}";
                strReturn = GetResponseData(temp, sendMsgUrl);
                return strReturn;
            }


        }
        public string GetResponseData(string JSONData, string Url)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(JSONData);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentLength = bytes.Length;
            request.ContentType = "json";
            Stream reqstream = request.GetRequestStream();
            reqstream.Write(bytes, 0, bytes.Length);
            //声明一个HttpWebRequest请求
            request.Timeout = 90000;
            //设置连接超时时间
            request.Headers.Set("Pragma", "no-cache");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamReceive = response.GetResponseStream();
            Encoding encoding = Encoding.UTF8;
            StreamReader streamReader = new StreamReader(streamReceive, encoding);
            string strResult = streamReader.ReadToEnd();
            streamReceive.Dispose();
            streamReader.Dispose();
            return strResult;
        }

 

你可能感兴趣的:(C#)