接口地址: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; }
}