开发日志:企业微信消息提醒和接收消息
一、接收消息
配置企业微信
API接收消息配置
标准OA:/WebChat/MessageSeting
using System;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using HDJ.DAL;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace HDJ.WEB.Controllers {
/// <summary>
/// 企业微信对接接口
/// WebChat/MessageSeting
/// </summary>
public class WebChatController : Controller {
private static IWebHostEnvironment _hostingEnvironment;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ApplicationSettings _applicationSettings;
private readonly WebChatSettings _chatSettings;
private readonly IHttpClientFactory _httpClientFactory;
public WebChatController(IWebHostEnvironment hostingEnvironment, IHttpContextAccessor httpContextAccessor, ApplicationSettings applicationSettings, WebChatSettings webChatSettings, IHttpClientFactory httpClientFactory) {
_hostingEnvironment=hostingEnvironment;
_httpContextAccessor=httpContextAccessor;
_applicationSettings=applicationSettings;
_chatSettings=webChatSettings;
_httpClientFactory=httpClientFactory;
}
#region MyRegion
[HttpGet, HttpPost]
public async Task<IActionResult> MessageSetingAsync() {
string text = "";
try {
if(Request.Method.ToLower()=="post") {
text=await ReceiveXmlAsync();
} else {
text=CheckWechat();
}
} catch(Exception ex) {
text=ex.Message;
Logger.LogError("MessageSeting["+Request.Method.ToLower()+"] :", ex);
}
Logger.LogFile("ResponseXML["+Request.Method.ToLower()+"] :"+text, "wxChat");
if(Request.Method.ToLower()=="post") {
return Content(text, "text/xml");
}
return Content(text);
}
private async Task<string> ReceiveXmlAsync() {
StreamReader stream = new StreamReader(Request.Body);
string requestStr = await stream.ReadToEndAsync();
string corpId = AppConfig.wxCorpId;
string access_token = AppConfig.wxToken;
string encodingAESKey = AppConfig.wxEncodingAESKey;
string signature = Request.Query["msg_signature"].ToString();
string timestamp = Request.Query["timestamp"].ToString();
string nonce = Request.Query["nonce"].ToString();
Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(access_token, encodingAESKey, corpId);
//解密后的requestStr
int error = wxcpt.DecryptMsg(signature, timestamp, nonce, requestStr, ref requestStr);
Logger.LogFile("ReceiveXml 收到:"+requestStr, "wxChat");
WxXmlModel WxXmlModel = new WxXmlModel();
#region 封装请求类
//封装请求类
XmlDocument requestDocXml = new XmlDocument();
requestDocXml.LoadXml(requestStr);
XmlElement rootElement = requestDocXml.DocumentElement;
WxXmlModel.ToUserName=rootElement.SelectSingleNode("ToUserName").InnerText;
WxXmlModel.FromUserName=rootElement.SelectSingleNode("FromUserName").InnerText;
WxXmlModel.CreateTime=rootElement.SelectSingleNode("CreateTime").InnerText;
WxXmlModel.MsgType=rootElement.SelectSingleNode("MsgType").InnerText;
if(rootElement.SelectSingleNode("AgentID")!=null) {
WxXmlModel.AgentId=rootElement.SelectSingleNode("AgentID").InnerText;
}
if(rootElement.SelectSingleNode("MsgId")!=null) {
WxXmlModel.MsgId=rootElement.SelectSingleNode("MsgId").InnerText;
}
switch(WxXmlModel.MsgType) {
case "text"://文本
WxXmlModel.Content=rootElement.SelectSingleNode("Content").InnerText;
break;
case "event"://事件
WxXmlModel.Event=rootElement.SelectSingleNode("Event").InnerText;
//按钮点击事件
if(WxXmlModel.Event=="taskcard_click") {
WxXmlModel.EventKey=rootElement.SelectSingleNode("EventKey").InnerText;
WxXmlModel.TaskId=rootElement.SelectSingleNode("TaskId").InnerText;
}
break;
default:
break;
}
#endregion
//返回
return ResponseXML(WxXmlModel, wxcpt, timestamp, nonce);
}
private string ResponseXML(WxXmlModel WxXmlModel, Tencent.WXBizMsgCrypt wxcpt, string timestamp, string nonce) {
string XML = "success";
string msg = GetDbSearch(WxXmlModel.Content);
//文字
var item = new {
touser = WxXmlModel.FromUserName,
msgtype = "text",
agentid = WxXmlModel.AgentId,
text = new {
content = msg
},
safe = "0"
};
var body = Newtonsoft.Json.JsonConvert.SerializeObject(item);
string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+AppConfig.wxCorpId+"&corpsecret="+AppConfig.wxSecret;
string reval = Utils.GetWebRequest(url, "", null, "GET");
dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(reval);
string tocken = temp["access_token"];
//获取token,注意有效时间,可用缓存控制
url=string.Format("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}", tocken);
string responseData = Utils.GetWebRequest(url, body);
return XML;
}
private string CheckWechat() {
if(string.IsNullOrEmpty(Request.Query["echoStr"])) {
return "消息并非来自微信";
}
string echoStr = "";
if(CheckSignature(ref echoStr)) {
return echoStr;
}
return "消息并非来自微信";
}
private bool CheckSignature(ref string echoStr) {
string corpId = AppConfig.wxCorpId;
string access_token = AppConfig.wxToken;
string encodingAESKey = AppConfig.wxEncodingAESKey;
string signature = Request.Query["msg_signature"].ToString();
string timestamp = Request.Query["timestamp"].ToString();
string nonce = Request.Query["nonce"].ToString();
string echostr = WebUtility.UrlDecode(Request.Query["echostr"].ToString());
Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(access_token, encodingAESKey, corpId);
echoStr="";
int ret = wxcpt.VerifyURL(signature, timestamp, nonce, echostr, ref echoStr);
return ret==0;
}
//DOTO:对接大模型
private string GetDbSearch(string text) {
StringBuilder builder = new StringBuilder();
string fun = DbHelperSQL.GetSingle<string>("SELECT STUFF((SELECT ','+menuname FROM SYSTEM_MENU WHERE LEN(id)=3 ORDER BY menuname FOR XML PATH('')),1,1,'')");
var news = DbHelperSQL.ExecuteTable($"SELECT id,Notice_Title FROM base_Noticemod WHERE Notice_Title LIKE '%{text}%'");
if(news!=null&&news.Rows.Count>0) {
builder.AppendLine($"通知公告:");
foreach(DataRow row in news.Rows) {
builder.AppendLine($"<a href=\"{AppConfig.wxDomin}/SystemManage/Notification/Form_ChaKan?newsId={row["id"]}/ target=\"_blank\"\">{row["Notice_Title"]}</a>");
}
}
var menus = DbHelperSQL.ExecuteTable($"SELECT menuname,menuurlmvc FROM SYSTEM_MENU WHERE menuname LIKE '%{text}%'");
if(menus!=null&menus.Rows.Count>0) {
builder.AppendLine($"菜单列表:");
foreach(DataRow row in menus.Rows) {
builder.AppendLine($"<a href=\"{AppConfig.wxDomin}{row["menuurlmvc"]}/ target=\"_blank\"\">{row["menuname"]}</a>");
}
}
var instances = DbHelperSQL.ExecuteTable($"SELECT id,CustomName FROM System_BillSystemFlowInstance WHERE CustomName LIKE '%{text}%'");
if(instances!=null&instances.Rows.Count>0) {
builder.AppendLine($"单据列表:");
foreach(DataRow row in instances.Rows) {
builder.AppendLine($"<a href=\"{AppConfig.wxDomin}/SystemManage/FlowWork/Verification?instanceId={row["id"]}/ target=\"_blank\"\">{row["CustomName"]}</a>");
}
}
var files = DbHelperSQL.ExecuteTable($" SELECT * FROM [dbo].[bzoa_FoldersPaper] WHERE OldName LIKE '%{text}%' OR [NewName] LIKE '%{text}%'");
if(files!=null&files.Rows.Count>0) {
builder.AppendLine($"文档列表:");
foreach(DataRow row in files.Rows) {
string[] strarr = row["FilePath"].ToString().Split("|");
for(int i = 0; i<strarr.Length; i++) {
builder.AppendLine($"<a href=\"{AppConfig.wxDomin}/{strarr[i]}/ target=\"_blank\"\">{row["OldName"]}</a>");
}
}
}
if(builder.Length<=1||text.Contains("oa")||text.Contains("介绍一下oa")) {
builder.AppendLine($"OA(办公自动化)系统的功能模块包含{fun}等功能模块,通过以上模块可以帮助学校(学院)提升办公效率和协作能力。");
}
return builder.ToString();
}
#endregion
}
}
二、消息提醒
/// <summary>
/// 指定用户推送消息发送News消息(标题,图片,描述)
/// </summary>
/// <returns></returns>
public static bool qySendNewMsg(string ToUsers, string title, string description, string url, string picurl) {
if(string.IsNullOrWhiteSpace(ToUsers))
return false;
string agentid = AppConfig.wxAgentId.ToString();
string strToken = GetSQLAccessToken();
string PostUrl = "";
string Post = "{ \"touser\": \""+ToUsers+"\", \"toparty\": \" \",\"totag\": \" \",\"msgtype\": \"news\",\"agentid\": \""+agentid+"\",\"news\": { \"articles\":[{\"title\": \""+title+"\",\"description\": \""+description+"\",\"url\": \""+url+"\",\"picurl\": \""+picurl+"\"}]\"},\"safe\":\"0\"}";
Post=Post.Replace(@"\", "/");
string Result = HttpRequest("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+strToken, Post);
var ms = new MemoryStream(Encoding.Unicode.GetBytes(Result));
DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(ToSendMsg));
ToSendMsg list = (ToSendMsg)deseralizer.ReadObject(ms);// //反序列化ReadObject
if(list.errcode=="40014") {
strToken=GetSQLAccessToken();
return qySendNewMsg(ToUsers, title, description, url, picurl);
}
if(list.errmsg.ToLower().Equals("ok")) {
return true;
} else {
return false;
}
}
开发日志:企业微信实现扫码登录(WEB): https://www.cnblogs.com/luomingui/p/17749840.html
开发日志:企业微信自定义工作台:https://www.cnblogs.com/luomingui/p/18985097
开发日志:企业微信消息提醒和接收消息:https://www.cnblogs.com/luomingui/p/18985125