企业微信推送消息

接口地址:https://developer.work.weixin.qq.com/document
需求每天向企业微信中的部分用户推送消息
企业微信服务接口文档:https://developer.work.weixin.qq.com/document/path/90664
步骤1:获取access_token 值
请求方式: GET(HTTPS)
请求地址: https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET
在这里插入图片描述

corpid 是企业ID 如下图
在这里插入图片描述
corpsecret是应用的凭证密钥如下图
在这里插入图片描述
代码如下`


        /// <summary>
        /// 获取凭证access_token
        /// </summary>
        /// <param name="corpid"></param>
        /// <param name="corpsecret"></param>
        /// <returns></returns>
        public static string GetAccess_Token(string corpid,string corpsecret)
        {

            string serviceAddress = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}",corpid,corpsecret);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            ResultMeg res = new ResultMeg();
            res = JsonConvert.DeserializeObject(retString, res.GetType()) as ResultMeg;


            //return Json(res, JsonRequestBehavior.AllowGet);


            if (res.errmsg=="ok")
            {
                return res.access_token;
            }
            else
            {
                return null;
            }
        }

2:推送消息 推送消息接口如下
请求方式:POST(HTTPS)
请求地址: https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN
在这里插入图片描述
推送图文消息
参数如下图
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
代码如下

 static void Main(string[] args)
        {
            string WeixinAppId = ConfigurationManager.AppSettings["WeixinAppId"];
            string WeixinAppSecret = ConfigurationManager.AppSettings["WeixinAppSecret"];
            string WeixinCorpId = ConfigurationManager.AppSettings["WeixinCorpId"];
            string PicUrl = ConfigurationManager.AppSettings["PicUrl"];
            string Touser = ConfigurationManager.AppSettings["Touser"];
            string PushUrl = ConfigurationManager.AppSettings["PushUrl"];
            string access_token = GetAccess_Token(WeixinCorpId, WeixinAppSecret);
            string Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
            if (!string.IsNullOrEmpty(access_token))
            {
                Url += access_token;
                msgBody M = new msgBody();
                List<articles> articlesList = new List<articles>();
                articles a = new articles();
                newPro n = new newPro();
                M.touser = Touser;
                M.msgtype = "news";
                M.agentid = Convert.ToInt32(WeixinAppId);
                M.enable_id_trans = 0;
                M.enable_duplicate_check = 0;
                M.duplicate_check_interval = 1800;
                string date1=DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                string date2 = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                a.title = date1+"XXXX考勤";
                a.description = "XXXXXXXXXXXXXXXXXXXX有限公司";
                a.url = PushUrl+date2;
              // a.picurl = "http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png";
               a.picurl = PicUrl;
                articlesList.Add(a);
                n.articles = articlesList.ToArray();
                M.news = n;
                //实体转换为json
                string jsonpara = JsonConvert.SerializeObject(M);
               PushMsg(Url, jsonpara);

            }
        }






  /// <summary>
        /// 推送消息
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="jsonParas"></param>
        /// <returns></returns>

        public static void PushMsg(string Url, string jsonParas)
        {
            string strURL = Url;
            //创建一个HTTP请求  
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //Post请求方式  
            request.Method = "POST";
            //内容类型
            request.ContentType = "application/json";

            //设置参数,并进行URL编码 

            string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);   

            byte[] payload;
            //将Json字符串转化为字节  
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            //设置请求的ContentLength   
            request.ContentLength = payload.Length;
            //发送请求,获得请求流 

            Stream writer;
            try
            {
                writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
            }
            catch (Exception)
            {
                writer = null;
                Console.Write("连接服务器失败!");
            }
            //将请求参数写入流
            writer.Write(payload, 0, payload.Length);
            writer.Close();//关闭请求流
                           // String strValue = "";//strValue为http响应所返回的字符流
            HttpWebResponse response;
            try
            {
                //获得响应流
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }
            Stream s = response.GetResponseStream();
            //  Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(s);
            string postContent = sRead.ReadToEnd();
            sRead.Close();
            //jeson 转换为实体
            var msg = JsonConvert.DeserializeObject<FHMsg>(postContent);
            if (!string.IsNullOrEmpty(msg.invaliduser))
            {
                ErrorLog("不合法的用户ID:"+msg.invaliduser);
            }
        }



 public class msgBody
    {
        public string touser { get; set; }

        public string msgtype { get; set; }

        public int agentid { get; set; }

        public int enable_id_trans { get; set; }

        public int enable_duplicate_check { get; set; }

        public int duplicate_check_interval { get; set; }

        public newPro news { get; set; }

    }


    public class articles
    {
        public string title { get; set; }

        public string description { get; set; }

        public string url { get; set; }

        public string picurl { get; set; }
    }


    public class newPro
    {
       public articles[] articles { get; set; }
    }

    public class ResultMeg
    {
        public int errcode { get; set; }

        public string errmsg { get; set; }

        public string access_token { get; set; }

        public string expires_in { get; set; }
    }


    public class FHMsg
    {

        /// <summary>
        /// 返回码
        /// </summary>
        public int errcode { get; set; }


        /// <summary>
        /// 对返回码的文本描述内容
        /// </summary>
        public string errmsg { get; set; }

        /// <summary>
        /// 不合法的userid,不区分大小写,统一转为小写
        /// </summary>
        public string invaliduser { get; set; }


        /// <summary>
        /// 不合法的partyid
        /// </summary>
        public string invalidparty { get; set; }


        /// <summary>
        /// 不合法的标签id
        /// </summary>
        public string invalidtag { get; set; }

        /// <summary>
        /// 没有基础接口许可(包含已过期)的userid
        /// </summary>
        public string unlicenseduser { get; set; }

        //消息id,用于撤回应用消息
        public string msgid { get; set; }



        public string response_code { get; set; }


    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!对于企业微信推送消息机器人的开发,可以使用企业微信提供的开放接口和机器人API来实现。 首先,您需要在企业微信后台创建一个机器人应用,并获取到相应的机器人API密钥。 然后,您可以使用开发语言(如Python、Java等)来编写代码,通过调用企业微信的机器人API来发送消息。具体的步骤如下: 1. 引入相关的网络请求库和JSON解析库。 2. 构造请求URL,将消息内容、接收者等参数作为请求的参数。 3. 发送HTTP POST请求到企业微信机器人API,将消息发送给指定的接收者。 4. 解析响应结果,判断消息发送是否成功。 示例代码(Python): ```python import requests import json def send_message(message, receiver): url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={机器人API密钥}" payload = { "msgtype": "text", "text": { "content": message }, "touser": receiver } headers = { "Content-Type": "application/json" } response = requests.post(url, data=json.dumps(payload), headers=headers) result = response.json() if result["errcode"] == 0: print("消息发送成功!") else: print("消息发送失败:" + result["errmsg"]) # 调用发送消息函数 send_message("这是一条测试消息", "UserID1|UserID2") ``` 以上代码仅为示例,您需要替换`{机器人API密钥}`为您的机器人API密钥,并根据实际需求修改消息内容和接收者。 希望能对您有所帮助!如有更多问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值