Example #1
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string accesstoken = WeiXinUtil.Factory(this).getAccessToken();//HttpUtil.getAccessToken("wx69c300b3e390be5b", "3c06a3f6eb8a562b278583dff8b9da1c");
        string str         = HttpUtil.HtmlFromUrl("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accesstoken, "POST", userBase2.Curraid);

        ScriptManager.RegisterStartupScript(Page, this.GetType(), "goto", "console.log(" + str + ");", true);
    }
Example #2
0
        private void Digest(ReceiveMsg msg)
        {
            SendTextMsg textMsg = null;

            switch (msg.MsgType)
            {
            case ReceiveMsg.TYPE_TEXT:
                textMsg = new SendTextMsg()
                {
                    touser = msg.FromUserName
                };
                textMsg.text.content = ((ReceiveTextMsg)msg).Content;

                WeiXinUtil.PostSendMsgJson(CustomSendUrl, weiXinPublic.AccessToken.access_token, textMsg);
                //WeiXinMsgSend.PostMsgJson(weiXinPublic.AccessToken.access_token, tmj);
                break;

            case ReceiveMsg.TYPE_EVENT:
                textMsg = new SendTextMsg()
                {
                    touser = msg.FromUserName
                };
                textMsg.text.content = ((ReceiveEventMsg)msg).Event;

                WeiXinUtil.PostSendMsgJson(CustomSendUrl, weiXinPublic.AccessToken.access_token, textMsg);
                break;
            }
        }
Example #3
0
        private void GetAccessToken()
        {
            DateTime refDateTime = DateTime.Now.AddSeconds(-GetAccessTokenSecond);

            while (true)
            {
                try
                {
                    TimeSpan span = (TimeSpan)(DateTime.Now - refDateTime);
                    //如果大于6000秒
                    if (span.TotalSeconds >= GetAccessTokenSecond)
                    {
                        //获取Token
                        AccessToken = WeiXinUtil.GetAccessToken(AccessTokenUrl);

                        if (AccessToken.access_token != null)
                        {
                            JsApiTicket = WeiXinUtil.GetJsApiTicket(JsApiTicketUrl, AccessToken.access_token);
                            if (JsApiTicket.ticket != null)
                            {
                                refDateTime = DateTime.Now;
                            }
                            if (isCreateMenu == false)
                            {
                                CreateMenu();
                            }
                        }
                    }
                    Thread.Sleep(2000);
                }
                catch (Exception e)
                {
                }
            }
        }
Example #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string type = HttpUtil.GetReqStrValue("type");
        //string isSaveFile = HttpUtil.GetReqStrValue("isSaveFile");
        WEC_XX_MESSAGE conf = new WEC_XX_MESSAGE();

        conf.OPENID = HttpUtil.GetReqStrValue("openid");
        conf.OrderBy("ADDTIME DESC");
        WEC_XX_MESSAGE xx_message = BLLTable <WEC_XX_MESSAGE> .GetRowData(new WEC_XX_MESSAGE(), conf);


        if ("0".Equals(type))//Îı¾»Ø¸´
        {
            string          message     = HttpUtil.GetReqStrValue("message");
            WEC_HF_RESPONSE hf_response = new WEC_HF_RESPONSE();
            hf_response.R_CONTENT  = message;
            hf_response.OPENID     = HttpUtil.GetReqStrValue("openid");
            hf_response.ADDTIME    = DateTime.Now;
            hf_response.REQUEST_ID = xx_message.ID;
            hf_response.TYPE       = 0;
            BLLTable <WEC_HF_RESPONSE> .Insert(hf_response, WEC_HF_RESPONSE.Attribute.ID);

            string responseText = "<div class='res right'>" + hf_response.ADDTIME + "<br/>" + hf_response.R_CONTENT + "</div><br/>";
            //  Response.Write("{\"res\":\""+responseText+"\"}");
            responseText = responseText.Replace("\n", "<br/>");
            Response.Write("{\"res\":\"" + responseText + "\"}");

            WeiXinUtil.Factory(this).actificialResponseText(hf_response.OPENID, hf_response.R_CONTENT);
        }
        else if ("1".Equals(type))//ͼƬ»Ø¸´
        {
            HttpFileCollection postedFile = Request.Files;
            string             path       = Request.PhysicalApplicationPath + "UploadFiles\\Res_Pic\\" + userBase2.Curraid;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
            postedFile[0].SaveAs(path + "\\" + filename);

            // WEC_HF_RESPONSE hf_response = new WEC_HF_RESPONSE();
            WEC_HF_RESPONSE hf_response = new WEC_HF_RESPONSE();
            hf_response.R_CONTENT  = "UploadFiles/Res_Pic/" + userBase2.Curraid + "/" + filename;
            hf_response.OPENID     = HttpUtil.GetReqStrValue("openid");
            hf_response.ADDTIME    = DateTime.Now;
            hf_response.REQUEST_ID = xx_message.ID;
            hf_response.TYPE       = 1;
            BLLTable <WEC_HF_RESPONSE> .Insert(hf_response, WEC_HF_RESPONSE.Attribute.ID);

            string responseText = "<div class='res right'>" + hf_response.ADDTIME + "<br/>" + "<img class=\"img\" src='" + WebHelper.GetAppPath() + hf_response.R_CONTENT + "'/>" + "</div><br/>";
            //  Response.Write("{\"res\":\""+responseText+"\"}");
            Response.Write(responseText);
            WeiXinUtil.Factory(this).actificialResponseImg(hf_response.OPENID, path + "\\" + filename);
        }
    }
Example #5
0
        private void CreateMenu()
        {
            string baseUrl = "http://myhelloworld.vicp.net/";

            //删除菜单
            WeiXinUtil.GetSendMsgJson(
                MenuDelUrl,
                AccessToken.access_token,
                "");

            //创建菜单
            SendMenuMsg menuBar = new SendMenuMsg();

            SendMenuMsg.ViewMenu viewMenu = null;
            SendMenuMsg.MainMenu mainMenu = null;

            viewMenu      = new SendMenuMsg.ViewMenu();
            viewMenu.name = "订单";
            viewMenu.url  = GetOauth2Url(baseUrl + "EasyJob/RepairOrder?id=123", Scope.snsapi_base, "test");
            menuBar.button.Add(viewMenu);

            mainMenu            = new SendMenuMsg.MainMenu();
            mainMenu.name       = "我的Easy";
            mainMenu.sub_button = new List <Object>();
            menuBar.button.Add(mainMenu);

            viewMenu      = new SendMenuMsg.ViewMenu();
            viewMenu.name = "我的资料";
            viewMenu.url  = GetOauth2Url(baseUrl + "EasyJob/RepairOrder?id=123", Scope.snsapi_userinfo, "test");
            mainMenu.sub_button.Add(viewMenu);

            viewMenu      = new SendMenuMsg.ViewMenu();
            viewMenu.name = "师傅登录";
            viewMenu.url  = baseUrl + "WeiXin/Order";
            mainMenu.sub_button.Add(viewMenu);

            viewMenu      = new SendMenuMsg.ViewMenu();
            viewMenu.name = "推荐码";
            viewMenu.url  = baseUrl + "WeiXin/Order";
            mainMenu.sub_button.Add(viewMenu);

            viewMenu      = new SendMenuMsg.ViewMenu();
            viewMenu.name = "订单记录";
            viewMenu.url  = baseUrl + "WeiXin/Order";
            mainMenu.sub_button.Add(viewMenu);

            string json        = menuBar.ToJson();
            string retMenuInfo = WeiXinUtil.PostSendMsgJson(
                MenuCreateUrl,
                AccessToken.access_token,
                menuBar
                );

            isCreateMenu = true;
        }
Example #6
0
        public ApiMessage <object> CkeckWxData(OutPayModel pm, CurrentUser user)
        {
            var res = new ApiMessage <object>();

            res.Success = false;
            res.Msg     = "数据有误";
            var requestXml = WeiXinUtil.BuildRequest(pm.OutTradeNo, pm.Subject, pm.TotalAmount, pm.IP);

            var resultXml = WeiXinUtil.Post("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXml);

            var dic = WeiXinUtil.FromXml(resultXml);

            string returnCode;

            dic.TryGetValue("return_code", out returnCode);

            if (returnCode == "SUCCESS")
            {
                var prepay_id = WeiXinUtil.GetValueFromDic <string>(dic, "prepay_id");
                if (!string.IsNullOrEmpty(prepay_id))
                {
                    var payInfo   = JsonConvert.DeserializeObject <WeiXinUtil.WxPayModel>(WeiXinUtil.BuildAppPay(prepay_id));
                    var orderinfo = new
                    {
                        payInfo.appid,
                        payInfo.partnerid,
                        payInfo.prepayid,
                        payInfo.package,
                        payInfo.noncestr,
                        payInfo.timestamp,
                        payInfo.sign,
                        code = 0,
                        msg  = "成功"
                    };
                    res.Success = true;
                    res.Data    = orderinfo;
                    res.Msg     = "";
                }
                else
                {
                    res.Msg = "支付错误:" + WeiXinUtil.GetValueFromDic <string>(dic, "err_code_des");

                    return(res);
                }
            }
            else
            {
                res.Msg = "配置错误";
                return(res);
            }
            return(res);
        }
Example #7
0
        public ActionResult Index()
        {
            Stream requestStream = System.Web.HttpContext.Current.Request.InputStream;
            string requestStr    = StreamUtil.StreamToStr(requestStream);

            //由POST过来的字符串转成微信消息对象
            ReceiveMsg msg = WeiXinUtil.XmlToReceiveMsg(requestStr);

            //处理消息
            Digest(msg);

            return(Content("success"));
        }
Example #8
0
 public ActionResult Index(string signature, string timestamp, string nonce, string echostr)
 {
     if (signature == null)
     {
         signature = "";
     }
     //验证微信签名
     if (signature.Equals(WeiXinUtil.Signature(Token, timestamp, nonce)))
     {
         return(Content(echostr));
     }
     else
     {
         return(Content(""));
     }
 }
Example #9
0
    public static WeiXinUtil Factory(string APPID_APPSECRET)
    {
        WeiXinUtil wx;

        if (!WeiXinUtilDic.TryGetValue(APPID_APPSECRET, out wx))
        {
            string APPID     = null;
            string APPSECRET = null;
            if (APPID_APPSECRET.Contains("_"))
            {
                string[] strs1 = APPID_APPSECRET.Split('_');
                APPID     = strs1[0];
                APPSECRET = strs1[1];
                wx        = new WeiXinUtil(APPID, APPSECRET);
            }
        }
        return(wx);
    }
Example #10
0
        public virtual string ToXml()
        {
            string retVal = "";

            try
            {
                retVal += "<xml>";

                retVal += "<ToUserName><![CDATA[" + ToUserName + "]]></ToUserName>";
                retVal += "<FromUserName><![CDATA[" + FromUserName + "]]></FromUserName>";
                retVal += "<CreateTime>" + WeiXinUtil.DateTimeToSecond(CreateTime) + "</CreateTime>";
                retVal += "<MsgType><![CDATA[" + MsgType + "]]></MsgType>";
            }
            finally
            {
                retVal += "</xml>";
            }

            return(retVal);
        }
Example #11
0
        public JsApiValidInfo GetJsApiValidInfo(string url)
        {
            JsApiValidInfo retVal = null;

            if (JsApiTicket != null && JsApiTicket.ticket != null)
            {
                string timestamp    = WeiXinUtil.DateTimeToSecond(DateTime.Now).ToString();
                string jsapi_ticket = JsApiTicket.ticket;
                string noncestr     = "Wm3WZYTPz0wzccnW";

                string str       = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
                string signature = FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1").ToLower();

                retVal           = new JsApiValidInfo();
                retVal.Signature = signature;
                retVal.Timestamp = timestamp;
                retVal.Nonce     = noncestr;
            }
            return(retVal);
        }
Example #12
0
    protected void btnOK_Click(object sender, EventArgs e)
    {
        try
        {
            WEC_C_CHANNELlIST valObj = new WEC_C_CHANNELlIST();


            if (txtID.Value != "")
            {
                valObj.ID = Convert.ToDecimal(txtID.Value);
            }


            if (txtAID.Value != "")
            {
                valObj.AID = Convert.ToDecimal(txtAID.Value);
            }


            if (txtSTATUS.Value != "")
            {
                valObj.STATUS = Convert.ToInt32(txtSTATUS.Value);
            }


            if (txtADDTIME.Value != "")
            {
                valObj.ADDTIME = Convert.ToDateTime(txtADDTIME.Value);
            }


            if (txtNAME.Value != "")
            {
                valObj.NAME = Convert.ToString(txtNAME.Value);
            }


            if (txtURL.Value != "")
            {
                valObj.URL = Convert.ToString(txtURL.Value);
            }


            if (txtREMARK.Value != "")
            {
                valObj.REMARK = Convert.ToString(txtREMARK.Value);
            }


            if (txtCATEGORY_ID.Value != "")
            {
                valObj.CATEGORY_ID = Convert.ToInt32(txtCATEGORY_ID.Value);
            }



            if (txtNOTE.Value != "")
            {
                valObj.NOTE = Convert.ToString(txtNOTE.Value);
            }


            if (txtADDRESS.Value != "")
            {
                valObj.ADDRESS = Convert.ToString(txtADDRESS.Value);
            }


            if (txtTYPE.Value != "")
            {
                valObj.TYPE = Convert.ToInt32(txtTYPE.Value);
            }



            string path     = WebHelper.GetAppPath() + "UploadFiles/Code/" + userBase2.Curraid + "/";
            string fullPath = System.Web.HttpContext.Current.Server.MapPath(path);
            if (!Directory.Exists(fullPath))
            {
                Directory.CreateDirectory(fullPath);
            }

            string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg.重命名";


            valObj.FILEPATH = path + filename;

            if (keyid != "")
            {
                valObj.ID = Convert.ToDecimal(keyid);
                count     = BLLTable <WEC_C_CHANNELlIST> .Update(valObj, WEC_C_CHANNELlIST.Attribute.ID);
            }
            else
            {
                count = BLLTable <WEC_C_CHANNELlIST> .Insert(valObj, WEC_C_CHANNELlIST.Attribute.ID);

                keyid = valObj.ID.ToString();
            }

            bool isSuccess = WeiXinUtil.Factory(this).getCode(fullPath + filename, Convert.ToInt32(valObj.ID));

            if (count > 0)
            {
                StringBuilder        sbData = new StringBuilder("{valObj:''");
                List <AttributeItem> lstCol = valObj.af_AttributeItemList;
                for (int i = 0; i < lstCol.Count; i++)
                {
                    object val = valObj.GetValue(lstCol[i]);
                    if (val != null)
                    {
                        sbData.Append(",").Append(lstCol[i].FieldName).Append(":'").Append(val.ToString()).Append("'");
                    }
                }
                sbData.Append("}");
                if (ViewState["sbData"] == null)
                {
                    ViewState["sbData"] = sbData.ToString();
                }
                else
                {
                    ViewState["sbData"] += "," + sbData.ToString();
                }
                Button btn = (Button)sender;
                if (btn.ID.IndexOf("btnOK") != -1)
                {
                    if (ViewState["sbData"] == null)
                    {
                        string dataStr = "[" + ViewState["sbData"].ToString() + "]";
                        // ScriptManager.RegisterStartupScript(Page, this.GetType(), "goto", "alert(\"aaa\")", true);
                        ScriptManager.RegisterStartupScript(Page, this.GetType(), "goto", "if (window.opener){window.opener.returnValue = '" + dataStr + "';}else{window.returnValue = '" + dataStr + "';}window.close();", true);
                    }
                    else
                    {
                        //ScriptManager.RegisterStartupScript(Page, this.GetType(), "goto", "alert(\"bbb\")", true);
                        ScriptManager.RegisterStartupScript(Page, this.GetType(), "goto", "if (window.opener){window.opener.returnValue = 're';}else{window.returnValue = 're';}window.close();", true);
                    }
                }
                else
                {
                    txtID.Value = "";


                    txtAID.Value = "";


                    txtSTATUS.Value = "";


                    txtADDTIME.Value = "";


                    txtNAME.Value = "";


                    txtURL.Value = "";


                    txtREMARK.Value = "";


                    txtCATEGORY_ID.Value = "";



                    txtNOTE.Value = "";


                    txtADDRESS.Value = "";


                    txtTYPE.Value = "";
                }
            }
        }
        catch (Exception ex)
        {
            litWarn.Text = ex.Message;
        }
    }
Example #13
0
        public string UpdateOrder(string id)
        {
            LogHelper.WriteLog("支付返回:" + id, LogHelper.LogType.Debug);
            if (id != "wxpay")
            {
                NameValueCollection          collection  = HttpContext.Current.Request.Form;
                String[]                     requestItem = HttpContext.Current.Request.Form.AllKeys;
                IDictionary <string, string> sArray      = new Dictionary <string, string>();

                for (int i = 0; i < requestItem.Length; i++)
                {
                    sArray.Add(requestItem[i], collection[requestItem[i]]);
                }

                LogHelper.WriteLog("支付返回:" + JsonConvert.SerializeObject(sArray), LogHelper.LogType.Debug);

                var success = AlipaySignature.RSACheckV1(sArray, Ali_PUBLIC_KEY, CHARSET, "RSA2", false);
                if (!success)
                {
                    return("fail");
                }

                var orderno  = sArray["out_trade_no"];
                var trade_no = sArray["trade_no"];
                var sign     = bll.UpdateOrder(orderno, trade_no);

                return(sign.Success ? "success" : "fail");
            }
            else
            {
                HttpContextBase context      = (HttpContextBase)Request.Properties["MS_HttpContext"]; //获取传统context
                HttpRequestBase request      = context.Request;                                       //定义传统request对象
                var             verifyResult = "false";
                var             requestXml   = WeiXinUtil.GetRequestXmlData(request);
                var             dic          = WeiXinUtil.FromXml(requestXml);

                LogHelper.WriteLog("支付返回:" + JsonConvert.SerializeObject(dic), LogHelper.LogType.Debug);

                var returnCode = WeiXinUtil.GetValueFromDic <string>(dic, "return_code");

                if (!string.IsNullOrEmpty(returnCode) && returnCode == "SUCCESS")//通讯成功
                {
                    var result = WeiXinUtil.WePayNotifyValidation(dic);
                    if (result)
                    {
                        var transactionid = WeiXinUtil.GetValueFromDic <string>(dic, "transaction_id");

                        if (!string.IsNullOrEmpty(transactionid))
                        {
                            var queryXml       = WeiXinUtil.BuildQueryRequest(transactionid, dic);
                            var queryResult    = WeiXinUtil.Post("https://api.mch.weixin.qq.com/pay/orderquery", queryXml);
                            var queryReturnDic = WeiXinUtil.FromXml(queryResult);

                            if (WeiXinUtil.ValidatonQueryResult(queryReturnDic))//查询成功
                            {
                                verifyResult = "true";
                                var status = WeiXinUtil.GetValueFromDic <string>(dic, "result_code");

                                if (!string.IsNullOrEmpty(status) && status == "SUCCESS")
                                {
                                    //var order = new Order()
                                    //{
                                    //    OrderNumber = WeiXinUtil.GetValueFromDic<string>(dic, "out_trade_no"),
                                    //    TransactionId = transactionid,
                                    //    ProductPrice = WeiXinUtil.GetValueFromDic<decimal>(dic, "total_fee") / 100,
                                    //    TradeType = WeiXinUtil.GetValueFromDic<string>(dic, "trade_type"),
                                    //    BankType = WeiXinUtil.GetValueFromDic<string>(dic, "bank_type"),
                                    //    PayDate = DateTime.Parse(WeiXinUtil.GetValueFromDic<string>(dic, "time_end")),
                                    //    StatusId = 1,
                                    //    IsPresent = false,
                                    //    AddDate = DateTime.Now,
                                    //    IsDelete = false
                                    //};
                                    //CURD.Add(order, ConfigHelper.WriteDB);
                                    var orderNo = WeiXinUtil.GetValueFromDic <string>(dic, "out_trade_no");
                                    var sign    = bll.UpdateOrder(orderNo, transactionid);

                                    return(WeiXinUtil.BuildReturnXml("SUCCESS", "成功"));
                                }
                            }
                            else
                            {
                                return(WeiXinUtil.BuildReturnXml("FAIL", "订单查询失败"));
                            }
                        }
                        else
                        {
                            return(WeiXinUtil.BuildReturnXml("FAIL", "支付结果中微信订单号不存在"));
                        }
                    }
                    else
                    {
                        return(WeiXinUtil.BuildReturnXml("FAIL", "签名失败"));
                    }
                }
                else
                {
                    string returnmsg;
                    dic.TryGetValue("return_msg", out returnmsg);
                    throw new Exception("异步通知错误:" + returnmsg);
                }

                return(WeiXinUtil.BuildReturnXml("FAIL", "签名失败"));;
            }
        }
Example #14
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string echostr = "", signature = "", timestamp = "", nonce = "", ToUserName = "";

        echostr = GetReqStrValue("echostr");

        signature = GetReqStrValue("signature");

        timestamp = GetReqStrValue("timestamp");

        nonce = GetReqStrValue("nonce");

        ToUserName = GetReqStrValue("ToUserName");

        string sha = SHA1("123456" + timestamp + nonce);

        try
        {
            //收到的消息
            StreamReader reader  = new StreamReader(Request.InputStream);
            String       xmlData = reader.ReadToEnd();

            XmlDocument userData = new XmlDocument();
            userData.LoadXml(xmlData);

            XmlNode    msgType           = userData.SelectSingleNode("//MsgType");
            String     msgType_str       = msgType.InnerText;
            XmlNode    toUserName_node   = userData.SelectSingleNode("//ToUserName");
            String     toUserName        = toUserName_node.InnerText;
            XmlNode    fromUserName_node = userData.SelectSingleNode("//FromUserName");
            String     fromUserName      = fromUserName_node.InnerText;
            WeiXinUtil wx = new WeiXinUtil(toUserName);
            //测试信息
            string       file1 = Path.Combine(CorePath.ExecutingPath, "1.txt");
            StreamWriter sw    = new StreamWriter(file1);
            sw.WriteLine("echostr=" + echostr);
            sw.WriteLine("signature=" + signature);
            sw.WriteLine("timestamp=" + timestamp);
            sw.WriteLine("nonce=" + nonce);
            sw.WriteLine("sha=" + sha);
            sw.WriteLine("url=" + Request.Url.ToString());
            sw.WriteLine("xmlData=" + xmlData);
            sw.WriteLine("txt=" + msgType_str);
            sw.Close();

            //用户发送文本信息
            if (msgType_str.Equals("text"))
            {
                wx.responseTextRequest(userData, fromUserName, toUserName, Response);
            }
            else if (msgType_str.Equals("image"))
            {
                wx.responseImageRequest(userData, fromUserName, toUserName, Response);
            }
            //事件
            else if (msgType_str.Equals("event"))
            {
                XmlNode event_node = userData.SelectSingleNode("//Event");
                String  event_str  = event_node.InnerText;
                if (event_str.Equals("subscribe"))
                {
                    wx.responseSubscribe(userData, fromUserName, toUserName, Response);
                }
                else if (event_str.Equals("unsubscribe"))//取消订阅消息,用于解绑用户,用户不在接受发送的消息
                {
                    //取消关注时 向表WEC_XX_MESSAGE存入取消关注信息
                    wx.saveUserMessage(fromUserName, 1, "", 0, toUserName);

                    wx.responseText("欢迎下次订阅", fromUserName, toUserName, Response);
                }
                else if (event_str.Equals("CLICK"))
                {
                    XmlNode     key         = userData.SelectSingleNode("//EventKey");
                    String      key_str     = key.InnerText;
                    WEC_REQUEST wec_request = wx.getWECREQUEST(key_str);
                    //StreamWriter sw2 = new StreamWriter("c:\\3.txt");
                    ////sw2.WriteLine("aaaa=" + key_str + "   " );
                    //sw2.WriteLine("aaaa=" + wec_request.KIND + "   " + wec_request);
                    //sw2.Close();

                    if (wec_request != null)
                    {
                        wx.responseByWecRequest(wec_request, fromUserName, toUserName, Response);
                    }
                }
                else if (event_str.Equals("LOCATION"))
                {
                    XmlNode latitude      = userData.SelectSingleNode("//Latitude");
                    String  latitude_str  = latitude.InnerText;
                    XmlNode longitude     = userData.SelectSingleNode("//Longitude");
                    String  longitude_str = longitude.InnerText;
                    XmlNode precision     = userData.SelectSingleNode("//Precision");
                    String  precision_str = precision.InnerText;
                    LocationUtil.setLocation(fromUserName, "{Latitude:\"" + latitude_str + "\",Longitude:\"" + longitude_str + "\",Precision:\"" + precision_str + "\"}");
                }
                else if (event_str.Equals("SCAN"))
                {
                    XmlNode key        = userData.SelectSingleNode("//EventKey");
                    string  channel_id = key.InnerText;
                    wx.saveUserMessage(fromUserName, 2, "", Convert.ToInt32(channel_id), toUserName);
                }
            }
            else if (msgType_str.Equals("location"))
            {
                wx.saveLocationMessage(userData, fromUserName);
            }
        }
        catch (Exception ex)
        {
            string       file1 = Path.Combine(CorePath.ExecutingPath, "2.txt");
            StreamWriter sw    = new StreamWriter(file1);
            sw.WriteLine("ex=" + ex.Message);
            sw.Close();
            Response.Write(echostr);
            return;
        }
    }
Example #15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string echostr = "", signature = "", timestamp = "", nonce = "", ToUserName = "";

        echostr = GetReqStrValue("echostr");

        signature = GetReqStrValue("signature");

        timestamp = GetReqStrValue("timestamp");

        nonce = GetReqStrValue("nonce");

        ToUserName = GetReqStrValue("ToUserName");

        string sha = SHA1("123456" + timestamp + nonce);

        try
        {

            //收到的消息
            StreamReader reader = new StreamReader(Request.InputStream);
            String xmlData = reader.ReadToEnd();

            XmlDocument userData = new XmlDocument();
            userData.LoadXml(xmlData);

            XmlNode msgType = userData.SelectSingleNode("//MsgType");
            String msgType_str = msgType.InnerText;
            XmlNode toUserName_node = userData.SelectSingleNode("//ToUserName");
            String toUserName = toUserName_node.InnerText;
            XmlNode fromUserName_node = userData.SelectSingleNode("//FromUserName");
            String fromUserName = fromUserName_node.InnerText;
            WeiXinUtil wx = new WeiXinUtil(toUserName);
            //测试信息
            string file1 = Path.Combine(CorePath.ExecutingPath, "1.txt");
            StreamWriter sw = new StreamWriter(file1);
            sw.WriteLine("echostr=" + echostr);
            sw.WriteLine("signature=" + signature);
            sw.WriteLine("timestamp=" + timestamp);
            sw.WriteLine("nonce=" + nonce);
            sw.WriteLine("sha=" + sha);
            sw.WriteLine("url=" + Request.Url.ToString());
            sw.WriteLine("xmlData=" + xmlData);
            sw.WriteLine("txt=" + msgType_str);
            sw.Close();

            //用户发送文本信息
            if (msgType_str.Equals("text"))
            {

                wx.responseTextRequest(userData, fromUserName, toUserName, Response);
            }
            else if (msgType_str.Equals("image"))
            {
                wx.responseImageRequest(userData, fromUserName, toUserName, Response);
            }
            //事件
            else if (msgType_str.Equals("event"))
            {
                XmlNode event_node = userData.SelectSingleNode("//Event");
                String event_str = event_node.InnerText;
                if (event_str.Equals("subscribe"))
                {
                    wx.responseSubscribe(userData, fromUserName, toUserName, Response);
                }
                else if (event_str.Equals("unsubscribe"))//取消订阅消息,用于解绑用户,用户不在接受发送的消息
                {
                    //取消关注时 向表WEC_XX_MESSAGE存入取消关注信息
                    wx.saveUserMessage(fromUserName, 1, "", 0, toUserName);

                    wx.responseText("欢迎下次订阅", fromUserName, toUserName, Response);
                }
                else if (event_str.Equals("CLICK"))
                {

                    XmlNode key = userData.SelectSingleNode("//EventKey");
                    String key_str = key.InnerText;
                    WEC_REQUEST wec_request = wx.getWECREQUEST(key_str);
                    //StreamWriter sw2 = new StreamWriter("c:\\3.txt");
                    ////sw2.WriteLine("aaaa=" + key_str + "   " );
                    //sw2.WriteLine("aaaa=" + wec_request.KIND + "   " + wec_request);
                    //sw2.Close();

                    if (wec_request != null)
                    {

                        wx.responseByWecRequest(wec_request, fromUserName, toUserName, Response);
                    }
                }
                else if (event_str.Equals("LOCATION"))
                {

                    XmlNode latitude = userData.SelectSingleNode("//Latitude");
                    String latitude_str = latitude.InnerText;
                    XmlNode longitude = userData.SelectSingleNode("//Longitude");
                    String longitude_str = longitude.InnerText;
                    XmlNode precision = userData.SelectSingleNode("//Precision");
                    String precision_str = precision.InnerText;
                    LocationUtil.setLocation(fromUserName, "{Latitude:\"" + latitude_str + "\",Longitude:\"" + longitude_str + "\",Precision:\"" + precision_str + "\"}");
                }
                else if (event_str.Equals("SCAN"))
                {
                    XmlNode key = userData.SelectSingleNode("//EventKey");
                    string channel_id = key.InnerText;
                    wx.saveUserMessage(fromUserName, 2, "", Convert.ToInt32(channel_id), toUserName);
                }
            }
            else if (msgType_str.Equals("location"))
            {
                wx.saveLocationMessage(userData, fromUserName);
            }

        }
        catch (Exception ex)
        {
            string file1 = Path.Combine(CorePath.ExecutingPath, "2.txt");
            StreamWriter sw = new StreamWriter(file1);
            sw.WriteLine("ex=" + ex.Message);
            sw.Close();
            Response.Write(echostr);
            return;
        }
    }