微信企业号接收消息并自动响应

来源:互联网 发布:新手自学加工中心编程 编辑:程序博客网 时间:2024/04/29 07:53

花了2天时间做了企业号接收消息功能测试,微信官方的文档给了我很大的帮助,但是恰恰卡时间最长的,也是官方文档上的一段有误导性的说明。带我细细道来

首先把微信发送信息到企业号服务器,然后企业号自动响应的过程图示下,网上找的,感觉描述的很好:


这里有几个地方很重要,在开发过程中不能搞错,不然会浪费很多测试时间:

1、消息的回调url就是每个应用模式选择中,回调模式里面设置的url。要使用一般处理程序要接收数据,*.ashx

2、完整的回调url是:url?msg_signature=ASDFQWEXZCVAQFASDFASDFSS&timestamp=13500001234&nonce=123412323,比回调模式验证开启操作时少了个echostr

3、根据消息的不同类型(文本、图片、声音...),post数据的xml格式不同,下面均是以text演示

4、整个过程概括起来就是:微信发消息含xml的post数据到回调url》》企业号服务器接收post数据(用stream接收转换)》》解密post,获取text类xml的数据,如下:》》写入数据库》》如果需要自动响应,那么根据解密的xml数据,做操作判断,执行不同操作,返回不同的加密xml返回给微信服务器,微信服务器再转发给微信客户端

<xml>    <ToUserName>        <![CDATA[wx6ce30be442e8cf9c]]>    </ToUserName>    <FromUserName>        <![CDATA[wzwl005]]>    </FromUserName>    <CreateTime>1485134274</CreateTime>    <MsgType>        <![CDATA[text]]>    </MsgType>    <Content>        <![CDATA[哦无聊]]>    </Content>    <MsgId>2792547595104851615</MsgId>    <AgentID>5</AgentID></xml>

实际操作:

应用后台设置的网址加入为:www.aaa.com/weixin/auth.ashx

那么我在服务器上要有对应这个网址的响应文件auth.ashx,文件代码如下:

下面代码实现,对发送过来的数据做了解密,但是并没有写入数据库,然后不管发过来什么数据,统一回复了“你好!!”

    public class auth : IHttpHandler    {        const string sToken = "***";             //应用配置中随机生成的Token        const string sCorpID = "***";      //企业号的CorpID        const string sEncodingAESKey = "******";     //应用配置中随机生成的EncodingAESKey        pub.WXBizMsgCrypt wxcpt = new pub.WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);        public void ProcessRequest(HttpContext context)        {            if (HttpContext.Current.Request.HttpMethod.ToUpper() == "GET")            {                //HttpContext.Current.Response.Write(pub.DataCache.GetCache("yuanwen"));                //HttpContext.Current.Response.Write(pub.DataCache.GetCache("jiemihou"));                //HttpContext.Current.Response.Write(pub.DataCache.GetCache("fasong"));                UrlAuth();            }            else            {                string postString = "";                using (Stream stream = HttpContext.Current.Request.InputStream)                {                    Byte[] postBytes = new Byte[stream.Length];                    stream.Read(postBytes, 0, (Int32)stream.Length);                    postString = Encoding.UTF8.GetString(postBytes);                }                if (!string.IsNullOrEmpty(postString))                {                    Execute(postString);                }            }        }        private void Execute(string postStr) {            //接收企业号回调信息            string sVerifyMsgSig = pub.DNTRequest.GetQueryString("msg_signature");            string sVerifyTimeStamp = pub.DNTRequest.GetQueryString("timestamp");            string sVerifyNonce = pub.DNTRequest.GetQueryString("nonce");            //对收到的密文进行解析处理            string sMsg = "";  // 解析之后的明文            int flag = wxcpt.DecryptMsg(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, postStr, ref sMsg);            if (flag != 0)            {                //解密失败                return;            }            //加密后并发送            string encryptResponse = "";            sVerifyTimeStamp = pub.DataConverter.timetoint(DateTime.Now).ToString();            //组装xml响应消息            wxcpt.EncryptMsg(ToXmlString("你好!!"), sVerifyTimeStamp, sVerifyNonce, ref encryptResponse);            HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;            HttpContext.Current.Response.Write(encryptResponse);        }        private string ToXmlString(string content)        {            string timestamp = pub.DataConverter.timetoint(DateTime.Now).ToString();            string s = "<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[{3}]]></MsgType><Content><![CDATA[{4}]]></Content></xml>";            s = string.Format(s,"wzwl005", "wx6ce30be442e8cf9c", timestamp, "text", content);            return s;        }        private void UrlAuth()        {            //接收企业号回调信息            string sVerifyMsgSig = pub.DNTRequest.GetQueryString("msg_signature");            string sVerifyTimeStamp = pub.DNTRequest.GetQueryString("timestamp");            string sVerifyNonce = pub.DNTRequest.GetQueryString("nonce");            string sVerifyEchoStr = pub.DNTRequest.GetQueryString("echostr");            sVerifyEchoStr = sVerifyEchoStr.Replace(" ", "+");            int ret = 0;            string sEchoStr = "";            ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr);            if (ret != 0)            {                return;            }            HttpContext.Current.Response.Write(sEchoStr);            HttpContext.Current.Response.End();        }        public bool IsReusable        {            get            {                return false;            }        }    }



0 0
原创粉丝点击