10 06 2025

效果图


发送消息该接口,基本只需要以下几个参数:


企业ID,应用ID,应用Secret


具体获取方式参照我的CSDN博客


本文只记录了发送文本消息,其他媒体消息格式,按照官方文档来,大同小异。


using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace job
{
  class Program
  {
    static void Main(string[] args)
    {
      SendToWeCom("");
    }
    public static string weComCId = "";//企业Id①
    public static string weComSecret = ""; //应用secret②
    public static string weComAId = ""; //应用ID③
    public static string weComTouId = "@all";//发送给谁  如果是所有人的话 这里就是@all 

    /// <summary>
    /// 发送微信通知
    /// </summary>
    /// <param name="text">消息</param>
    /// <returns></returns>
    public static string SendToWeCom(string text)
    {
      // 获取Token   后缀中 debug=1 接口可以返回具体的信息 这个官方文档上也有介绍
      string getTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + weComCId + "&corpsecret=" + weComSecret + "&debug=1";
       string str= HttpClientHelper.GetResponse(getTokenUrl);
       Dictionary<string, string> jobject = JsonConvert.DeserializeObject<Dictionary<string, string>>(str);
       if (jobject["errcode"].ToString() == "0" && jobject["errmsg"].ToString() == "ok")
       {
         string token = jobject["access_token"].ToString();
         //获取用户 此处列举了一下 通过用户在企业微信中的手机号 获取企业微信标识的方式 用处你懂的
         //string dd = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=" + token;
        // Dictionary<string, string> mobileDic = new Dictionary<string, string>();
        // mobileDic.Add("mobile", "xxx");
         //string result1 = HttpClientHelper.PostResponse(dd, JsonConvert.SerializeObject(mobileDic));


         //发送文本消息
         string postUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token;
         TextMsgModel textMsgModel = new TextMsgModel();
                 //用户在企业微信中的账号标识,可以通过手机号获取,也可以直接在企业微信具体查看,查看方式参照我的CSDN博客
         textMsgModel.touser = "";
                 //发送的消息类型 此处为文本形式
         textMsgModel.msgtype= "text";
         textMsgModel.agentid=weComAId;
         text textModel = new model.text();
                 //此处文本 支持超链接
         textModel.content = "你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。";
         textMsgModel.text =textModel ;
          string result= HttpClientHelper.PostResponse(postUrl,JsonConvert.SerializeObject(textMsgModel));

      }
      return "-1";
    } 
  }
}


这里再提供下 http请求帮助类


HttpClientHelper.cs


using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace job
{
  public class HttpClientHelper
  {
    /// <summary>
    /// get请求
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static string GetResponse(string url)
    {
      if (url.StartsWith("https"))
      {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
      }
      var httpClient = new HttpClient();
      httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
      HttpResponseMessage response = httpClient.GetAsync(url).Result;
      if (response.IsSuccessStatusCode)
      {
        string result = response.Content.ReadAsStringAsync().Result;
        return result;
      }
      return null;
    }
    public static T GetResponse<T>(string url)
     where T : class, new()
    {
      if (url.StartsWith("https"))
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
      var httpClient = new HttpClient();
      httpClient.DefaultRequestHeaders.Accept.Add(
       new MediaTypeWithQualityHeaderValue("application/json"));
      HttpResponseMessage response = httpClient.GetAsync(url).Result;
      T result = default(T);
      if (response.IsSuccessStatusCode)
      {
        Task<string> t = response.Content.ReadAsStringAsync();
        string s = t.Result;
        result = JsonConvert.DeserializeObject<T>(s);
      }
      return result;
    }
    /// <summary>
    /// post请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="postData">post数据</param>
    /// <returns></returns>
    public static string PostResponse(string url, string postData)
    {
      if (url.StartsWith("https"))
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
      HttpContent httpContent = new StringContent(postData);
      httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
      var httpClient = new HttpClient();
      HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
      if (response.IsSuccessStatusCode)
      {
        string result = response.Content.ReadAsStringAsync().Result;
        return result;
      }
      return null;
    }
    /// <summary>
    /// 发起post请求
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="url">url</param>
    /// <param name="postData">post数据</param>
    /// <returns></returns>
    public static T PostResponse<T>(string url, string postData)
     where T : class, new()
    {
      if (url.StartsWith("https"))
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
      HttpContent httpContent = new StringContent(postData);
      httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
      var httpClient = new HttpClient();
      T result = default(T);
      HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
      if (response.IsSuccessStatusCode)
      {
        Task<string> t = response.Content.ReadAsStringAsync();
        string s = t.Result;
        result = JsonConvert.DeserializeObject<T>(s);
      }
      return result;
    }

    /// <summary>
    /// V3接口全部为Xml形式,故有此方法
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="url"></param>
    /// <param name="xmlString"></param>
    /// <returns></returns>
    public static T PostXmlResponse<T>(string url, string xmlString)
     where T : class, new()
    {
      if (url.StartsWith("https"))
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
      HttpContent httpContent = new StringContent(xmlString);
      httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
      var httpClient = new HttpClient();
      T result = default(T);
      HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
      if (response.IsSuccessStatusCode)
      {
        Task<string> t = response.Content.ReadAsStringAsync();
        string s = t.Result;
        result = XmlDeserialize<T>(s);
      }
      return result;
    }
    /// <summary>
    /// 反序列化Xml
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="xmlString"></param>
    /// <returns></returns>
    public static T XmlDeserialize<T>(string xmlString)
     where T : class, new()
    {
      try
      {
        var ser = new XmlSerializer(typeof(T));
        using (var reader = new StringReader(xmlString))
        {
          return (T)ser.Deserialize(reader);
        }
      }
      catch (Exception ex)
      {
        throw new Exception("XmlDeserialize发生异常:xmlString:" + xmlString + "异常信息:" + ex.Message);
      }
    }
  }
}