C#给企业微信中的成员发送消息

先去企业微信门户网站获得密钥和应用ID

创建一个静态工具类

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public static class SendWeChatMessage
    {
        private const string getTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}";
        private const string sendMessageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}";
        private static readonly HttpClient httpClient = new HttpClient();

        public async static Task<string> Send(WeChatParameter parameter)
        {
            string tokenUrl = string.Format(getTokenUrl, parameter.CorpId, parameter.CorpSecret);
            var reponse = await httpClient.GetAsync(tokenUrl);
            var str = await reponse.Content.ReadAsStringAsync();
            var jObject = JObject.Parse(str);
            var getTokenResult = jObject["errmsg"].ToString().ToLower();
            var token = jObject["access_token"].ToString();
            // jObject["errmsg"].ToString();
            if (!getTokenResult.Equals("ok") || string.IsNullOrEmpty(token))
                return "获取token失败";
            string sendMsgUrl = string.Format(sendMessageUrl, token);
            var sendContentModel = new
            {
                touser = parameter.Touser,
                msgtype = parameter.MsgType,
                agentid = parameter.AgentId,
                text = new
                {
                    content = parameter.Content
                }
            };
            var sendContentStr = JsonConvert.SerializeObject(sendContentModel);
            HttpContent content = new StringContent(sendContentStr, Encoding.UTF8);
            var response = await httpClient.PostAsync(sendMsgUrl, content);
            return await response.Content.ReadAsStringAsync();
        }

    }

    public class WeChatParameter
    {
        public string CorpId { get; set; }
        public string CorpSecret { get; set; }
        public string Content { get; set; }
        public string Touser { get; set; }
        public string MsgType { get; set; } = "text";
        public string AgentId { get; set; }
    }
}

返回结果是json字符串,需要不同结果的同学可以自己修改一下返回类型。(当返回的结果中是“errmsg”:"ok",代表成功了)

posted @ 2019-10-12 17:37  an_blog  阅读(1470)  评论(0编辑  收藏