コード例 #1
0
        public void MsgCryptTest()
        {
            //公众平台上开发者设置的token, appID, EncodingAESKey
            string sToken          = "QDG6eK";
            string sAppID          = "wx5823bf96d3bd56c7";
            string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C";

            WeChat.Helpers.Crypto.WXBizMsgCrypt wxcpt = new WeChat.Helpers.Crypto.WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID);

            /* 1. 对用户回复的数据进行解密。
             * 用户回复消息或者点击事件响应时,企业会收到回调消息,假设企业收到的推送消息:
             *  POST /cgi-bin/wxpush? msg_signature=477715d11cdb4164915debcba66cb864d751f3e6&timestamp=1409659813&nonce=1372623149 HTTP/1.1
             * Host: qy.weixin.qq.com
             * Content-Length: 613
             *
             *  <xml>
             *     <ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName>
             *     <Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt>
             * </xml>
             */
            string sReqMsgSig    = "477715d11cdb4164915debcba66cb864d751f3e6";
            string sReqTimeStamp = "1409659813";
            string sReqNonce     = "1372623149";
            string sReqData      = "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt></xml>";
            string sMsg          = ""; //解析之后的明文
            int    ret           = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg);

            if (ret != 0)
            {
                System.Console.WriteLine("ERR: Decrypt fail, ret: " + ret);
                return;
            }
            System.Console.WriteLine(sMsg);


            /*
             * 2. 企业回复用户消息也需要加密和拼接xml字符串。
             * 假设企业需要回复用户的消息为:
             *      <xml>
             *      <ToUserName><![CDATA[mycreate]]></ToUserName>
             *      <FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName>
             *      <CreateTime>1348831860</CreateTime>
             *      <MsgType><![CDATA[text]]></MsgType>
             *      <Content><![CDATA[this is a test]]></Content>
             *      <MsgId>1234567890123456</MsgId>
             *      </xml>
             * 生成xml格式的加密消息过程为:
             */
            string sRespData   = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx582测试一下中文的情况,消息长度是按字节来算的396d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId></xml>";
            string sEncryptMsg = ""; //xml格式的密文

            ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg);
            System.Console.WriteLine("sEncryptMsg");
            System.Console.WriteLine(ret);

            /*测试:
             * 将sEncryptMsg解密看看是否是原文
             * */
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(sEncryptMsg);
            XmlNode root      = doc.FirstChild;
            string  sig       = root["MsgSignature"].InnerText;
            string  timestamp = root["TimeStamp"].InnerText;
            string  nonce     = root["Nonce"].InnerText;
            string  stmp      = "";

            ret = wxcpt.DecryptMsg(sig, timestamp, nonce, sEncryptMsg, ref stmp);
            System.Console.WriteLine("stemp");
            System.Console.WriteLine(stmp + ret);
            return;
        }
コード例 #2
0
        /// <summary>
        /// 开发者接管
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <param name="encrypt_type"></param>
        /// <param name="msg_signature"></param>
        public async void WeChat(string signature, string timestamp, string nonce, string echostr, string encrypt_type, string msg_signature)
        {
            string result = string.Empty;

            //微信后台验证地址(使用Get),微信后台的“接口配置信息”的Url
            if (Request.Method.ToLower() == "get")
            {
                var Token = GlobalTo.GetValue("ApiKey:WeChatMP:Token");

                if (Netnr.WeChat.Helpers.Util.CheckSignature(signature, timestamp, nonce, Token))
                {
                    //返回随机字符串则表示验证通过
                    result = echostr;
                }
                else
                {
                    result = "参数错误!";
                }
            }
            //处理请求
            else
            {
                WeChatMessage message  = null;
                var           safeMode = encrypt_type == "aes";

                var Token          = string.Empty;
                var EncodingAESKey = string.Empty;
                var AppID          = string.Empty;

                if (safeMode)
                {
                    Token          = GlobalTo.GetValue("ApiKey:WeChatMP:Token");
                    EncodingAESKey = GlobalTo.GetValue("ApiKey:WeChatMP:EncodingAESKey");
                    AppID          = GlobalTo.GetValue("ApiKey:WeChatMP:AppID");
                }

                using (var ms = new MemoryStream())
                {
                    await Request.Body.CopyToAsync(ms);

                    var myByteArray = ms.ToArray();

                    var    decryptMsg = string.Empty;
                    string postStr    = System.Text.Encoding.UTF8.GetString(myByteArray);

                    #region 解密
                    if (safeMode)
                    {
                        var wxBizMsgCrypt = new WeChat.Helpers.Crypto.WXBizMsgCrypt(Token, EncodingAESKey, AppID);
                        var ret           = wxBizMsgCrypt.DecryptMsg(msg_signature, timestamp, nonce, postStr, ref decryptMsg);
                        //解密失败
                        if (ret != 0)
                        {
                            FilterConfigs.WriteLog(HttpContext, new Exception("微信解密失败"));
                        }
                    }
                    else
                    {
                        decryptMsg = postStr;
                    }
                    #endregion

                    message = WeChatMessage.Parse(decryptMsg);
                }
                var response = new WeChatExecutor().Execute(message);

                #region 加密
                if (safeMode)
                {
                    var wxBizMsgCrypt = new WeChat.Helpers.Crypto.WXBizMsgCrypt(Token, EncodingAESKey, AppID);
                    var ret           = wxBizMsgCrypt.EncryptMsg(response, timestamp, nonce, ref result);
                    if (ret != 0)//加密失败
                    {
                        FilterConfigs.WriteLog(HttpContext, new Exception("微信加密失败"));
                    }
                }
                else
                {
                    result = response;
                }
                #endregion
            }

            //输出
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(result);
            await Response.Body.WriteAsync(buffer, 0, buffer.Length);

            await Response.Body.FlushAsync();
        }
コード例 #3
0
        /// <summary>
        /// 开发者接管
        /// </summary>
        public void Index(string signature, string timestamp, string nonce, string echostr, string encrypt_type, string msg_signature)
        {
            string result = string.Empty;

            //微信后台验证地址(使用Get),微信后台的“接口配置信息”的Url
            if (Request.Method.ToLower() != "post")
            {
                var Token = Configuration.GetValue <string>("WeChat:MP:Token");
                if (WeChat.Helpers.Util.CheckSignature(signature, timestamp, nonce, Token))
                {
                    //返回随机字符串则表示验证通过
                    result = echostr;
                }
                else
                {
                    result = "参数错误!";
                }
            }
            //处理请求
            else
            {
                WeChatMessage message  = null;
                var           safeMode = encrypt_type == "aes";

                var Token          = string.Empty;
                var EncodingAESKey = string.Empty;
                var AppID          = string.Empty;

                if (safeMode)
                {
                    Token          = Configuration.GetValue <string>("WeChat:MP:Token");
                    EncodingAESKey = Configuration.GetValue <string>("WeChat:MP:EncodingAESKey");
                    AppID          = Configuration.GetValue <string>("WeChat:MP:AppID");
                }

                using (var ms = new MemoryStream())
                {
                    Request.Body.CopyTo(ms);
                    var myByteArray = ms.ToArray();

                    var    decryptMsg = string.Empty;
                    string postStr    = System.Text.Encoding.UTF8.GetString(myByteArray);

                    #region 解密
                    if (safeMode)
                    {
                        var wxBizMsgCrypt = new WeChat.Helpers.Crypto.WXBizMsgCrypt(Token, EncodingAESKey, AppID);
                        var ret           = wxBizMsgCrypt.DecryptMsg(msg_signature, timestamp, nonce, postStr, ref decryptMsg);
                        //解密失败
                        if (ret != 0)
                        {
                            //TODO:开发者解密失败的业务处理逻辑
                        }
                    }
                    else
                    {
                        decryptMsg = postStr;
                    }
                    #endregion

                    message = WeChatMessage.Parse(decryptMsg);
                }
                var response   = new WeChatExecutor().Execute(message);
                var encryptMsg = string.Empty;

                #region 加密
                if (safeMode)
                {
                    var wxBizMsgCrypt = new WeChat.Helpers.Crypto.WXBizMsgCrypt(Token, EncodingAESKey, AppID);
                    var ret           = wxBizMsgCrypt.EncryptMsg(response, timestamp, nonce, ref encryptMsg);
                    if (ret != 0)//加密失败
                    {
                        //TODO:开发者加密失败的业务处理逻辑
                    }
                }
                else
                {
                    encryptMsg = response;
                }
                #endregion
            }

            //输出
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(result);
            Response.Body.Write(buffer, 0, buffer.Length);
            Response.Body.Flush();
        }