企业微信开发:接受消息和发送消息

简介: 本篇博文是针对本人在开发企业微信消息交互的一些经验分享,介绍一下自己开发过程中遇到的问题和解决方法,如果问题或异议,欢迎讨论,技术大佬请忽略

用户在企业微信中有2种用户操作可以发送给我们服务器

1、点菜微信企业应用的菜单

2、给企业微信发送文字或者图片等信息

企业微信要接受到用户行为(比如对企业号发消息或者点击企业号中的菜单)需要再对应的企业微信应用中配置接受消息模块:

1、首先进入企业微信配置接受消息

2、配置对应的URL,Token以及EncodingAESKey:

在后台编写程序解析用户行为操作并回复用户不同消息

1、接受微信发过来的加密报文解析用户行为操作

 public void ProcessRequest(HttpContext context)
        {

            var Request = context.Request;
            var Response = context.Response;
            context.Response.ContentType = "text/plain";
            //context.Response.ContentType = "text/xml";
            //公众平台上开发者设置的token, corpID, EncodingAESKey
            string sCorpID = System.Configuration.ConfigurationManager.AppSettings["sCorpID"];

            string sToken = "";
            string sEncodingAESKey =  "";
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);

            string sVerifyMsgSig = Request.QueryString["msg_signature"];
            string sVerifyTimeStamp = Request.QueryString["timestamp"];
            string sVerifyNonce = Request.QueryString["nonce"];
            string sVerifyEchoStr = Request.QueryString["echostr"] ?? "";
            int ret = 0;
            string sEchoStr = "";
            //获取表单提交内容
            string postStr = string.Empty;
            using (System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream))
            {
                postStr = sr.ReadToEnd();
            }
            if (!string.IsNullOrEmpty(postStr))
            {
                var xmldoc = new XmlDocument();
                xmldoc.LoadXml(postStr);
                XmlNode root = xmldoc.FirstChild;
                string sPostData = root["Encrypt"].InnerText;
                ret = wxcpt.DecryptMsg(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, postStr, ref sEchoStr);
                if (ret != 0)
                {
                    SH.Utilities.Base.Log.LogHelper.Info("WeChat", "ERR: VerifyURL fail, ret: " + ret);
                    return;
                }

                //封装请求类
                XmlDocument requestDocXml = new XmlDocument();
                requestDocXml.LoadXml(sEchoStr);
                XmlElement rootElement = requestDocXml.DocumentElement;
                WxXmlModel WxXmlModel = new WxXmlModel();
                WxXmlModel.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;
                WxXmlModel.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;
                WxXmlModel.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;
                WxXmlModel.MsgType = rootElement.SelectSingleNode("MsgType").InnerText;
                WxXmlModel.AgentID = rootElement.SelectSingleNode("AgentID").InnerText;
                WxXmlModel.CompanyId = companyid;

                switch (WxXmlModel.MsgType)
                {
                    case "text"://文本
                        WxXmlModel.Content = rootElement.SelectSingleNode("Content").InnerText;
                        break;
                    case "image"://图片
                        WxXmlModel.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText;
                        break;
                    case "event"://事件
                        WxXmlModel.Event = rootElement.SelectSingleNode("Event").InnerText;
                        if (WxXmlModel.Event == "click")//菜单点击
                        {
                            WxXmlModel.EventKey = rootElement.SelectSingleNode("EventKey").InnerText;
                            SH.WebApp.WeChatHelper.Report.sendMsg(WxXmlModel);
                        }
                        break;
                    default:
                        break;
                }

                string sReplyMsg = ResponseXML(WxXmlModel);//回复消息
                ret = wxcpt.EncryptMsg(sReplyMsg, sVerifyTimeStamp, sVerifyNonce, ref sEchoStr);
                if (ret != 0)
                {
                    return;
                }
                Response.Write(sEchoStr);
                Response.End();
                return;
            }
            else
            {
                string sEncryptMsg = "";
                ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEncryptMsg);
                if (ret != 0)
                {
                    SH.Utilities.Base.Log.LogHelper.Info("", "ERR: VerifyURL fail, ret: " + ret);
                    Response.Write("");
                    Response.End();
                    return;
                }
                Response.Write(sEncryptMsg);
                Response.End();
                return;
            }
        }

2、根据不同用户行为操作做不同的消息类型回复

private string ResponseXML(WxXmlModel WxXmlModel)
{
	string XML = "";
	switch (WxXmlModel.MsgType)
	{
		case "text"://文本回复
			//批号查询
			if (SH.WebApp.Extension.Utilities.IsBatchNumber(WxXmlModel))
			{
				WxXmlModel.EventKey = "BatchNumber_Search";
				XML = SH.WebApp.WeChatHelper.Report.sendMsg(WxXmlModel);
			}
			//流转卡查询
			else if (SH.WebApp.Extension.Utilities.IsTransferCard(WxXmlModel))
			{
				WxXmlModel.EventKey = "TransferCard_Search";
				XML = SH.WebApp.WeChatHelper.Report.sendMsg(WxXmlModel);
			}
			//默认自动回复
			else
			{
				XML = ResponseMessage.GetText(WxXmlModel.FromUserName, WxXmlModel.ToUserName, WxXmlModel.Content);
			}
			break;
		case "event":
			switch (WxXmlModel.Event)
			{
				//点击菜单
				case "click":
					if (string.IsNullOrEmpty(WxXmlModel.EventKey))
					{
						XML = SH.WebApp.WeChatHelper.Report.sendMsg(WxXmlModel);
					}
					break;
				case "SCAN":
					XML = ResponseMessage.ScanQrcode(WxXmlModel.FromUserName, WxXmlModel.ToUserName, WxXmlModel.EventKey);//扫描带参数二维码已关注 直接推送事件
					break;
			}
			break;
		default://默认回复
			break;
	}
	return XML;
}

3、图文消息发送,更多格式请查阅企业微信开发API:https://work.weixin.qq.com/api/doc#90000/90135/90236

SH.Business.ReportModule.Financial FinancialBLL = new Business.ReportModule.Financial();
var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}", Access_Token.GetAccessToken(WxXmlModel.AgentID));
Hashtable ht = new Hashtable();
ht["touser"] = WxXmlModel.FromUserName;
ht["toparty"] = "";
ht["totag"] = "";
ht["msgtype"] = "news";
ht["agentid"] = WxXmlModel.AgentID;

Hashtable news = new Hashtable();
List<Hashtable> articles = new List<Hashtable>();
Hashtable mianArticle = new Hashtable();
mianArticle["title"] = "财务对账";
mianArticle["url"] = "";
mianArticle["picurl"] = WebURL + "/Content/image/Financial_Reconciliation.jpg";
articles.Add(mianArticle);
string sSalesNo = SH.Business.Utilities.GetSalespower(WxXmlModel.FromUserName);
var list = FinancialBLL.Financial_Reconciliation(WxXmlModel.CompanyId, sSalesNo);
foreach (var items in list)
{
	Hashtable article = new Hashtable();
	article["title"] = string.Format("对账期间:{0}\r应收开票:{1}万米 {2}万元", SH.Business.Utilities.DateFormat(items["dReceivableDate"].ToString()), items["nQty"], items["nAmount"]);
	article["description"] = "";
	article["url"] = WebURL + "/Query/Financial/InvoiceByCompany?iCompanyId=" + WxXmlModel.CompanyId + "&date=" + items["dReceivableDate"] + "&AgentId=" + WxXmlModel.AgentID;
	articles.Add(article);
}
news["articles"] = articles;
ht["news"] = news;

string responseText = HttpHelper.Instance.post(url, ht.ToJson());

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页