Beispiel #1
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            //WXApi.DownloadMedia("http://localhost:2454/UploadFile/aa.png");
            //Response.Write(WXApi.UploadMedia(Session["token"].ToString(), "image", "d:\\_临时文件\\aa.png"));
            //获取天气预报
            //string result = HttpRequestUtil.RequestUrl("http://www.weather.com.cn/data/sk/101220101.html", "GET");
            //Response.Write(result);
            //result = Weixin.Mp.Util.Tools.GetJosnValue(result, "WSE");
            //Response.Write(result);
            //Response.Write(AdminUtil.GetRootUrl());
            //string result = WXApi.CreateMenu(AdminUtil.GetAccessToken(this), AdminUtil.GetLoginUser(this).OrgID);
            //Response.Write(AdminUtil.GetRootUrl());

            //string path = MapPath("UploadFile/aa.png");
            //string id = WXApi.UploadMedia(AdminUtil.GetAccessToken(this), "image", path);
            //Response.Write(id);

            Response.Write(WXMsgUtil.CreateTextJson("abc", WXApi.GetOpenIDs(AdminUtil.GetAccessToken(this))));
        }
Beispiel #2
0
        /// <summary>
        /// 群发
        /// </summary>
        public string Send()
        {
            string type = Request["type"];
            string data = Request["data"];

            string        access_token = AdminUtil.GetAccessToken(this); //获取access_token
            List <string> openidList   = WXApi.GetOpenIDs(access_token); //获取关注者OpenID列表
            UserInfo      loginUser    = AdminUtil.GetLoginUser(this);   //当前登录用户

            string resultMsg = null;

            //发送文本
            if (type == "1")
            {
                resultMsg = WXApi.Send(access_token, WXMsgUtil.CreateTextJson(data, openidList));
            }

            //发送图片
            if (type == "2")
            {
                string path = MapPath(data);
                if (!File.Exists(path))
                {
                    return("{\"code\":0,\"msg\":\"要发送的图片不存在\"}");
                }
                string msg      = WXApi.UploadMedia(access_token, "image", path);
                string media_id = Tools.GetJsonValue(msg, "media_id");
                resultMsg = WXApi.Send(access_token, WXMsgUtil.CreateImageJson(media_id, openidList));
            }

            //发送图文消息
            if (type == "3")
            {
                DataTable dt           = ImgItemDal.GetImgItemTable(loginUser.OrgID, data);
                string    articlesJson = ImgItemDal.GetArticlesJsonStr(this, access_token, dt);
                string    newsMsg      = WXApi.UploadNews(access_token, articlesJson);
                string    newsid       = Tools.GetJsonValue(newsMsg, "media_id");
                resultMsg = WXApi.Send(access_token, WXMsgUtil.CreateNewsJson(newsid, openidList));
            }

            //结果处理
            if (!string.IsNullOrWhiteSpace(resultMsg))
            {
                string errcode = Tools.GetJsonValue(resultMsg, "errcode");
                string errmsg  = Tools.GetJsonValue(resultMsg, "errmsg");
                if (errcode == "0")
                {
                    return("{\"code\":1,\"msg\":\"\"}");
                }
                else
                {
                    return("{\"code\":0,\"msg\":\"errcode:"
                           + errcode + ", errmsg:"
                           + errmsg + "\"}");
                }
            }
            else
            {
                return("{\"code\":0,\"msg\":\"type参数错误\"}");
            }
        }
Beispiel #3
0
        public HttpResponseMessage WetChatVerify(HttpRequestMessage content)      //HttpRequestMessage 和HttpResponseMessage,分别用于封装Requset和Response
        {
            string echostr = (from kvp in content.GetQueryNameValuePairs()
                              where kvp.Key == "echostr"
                              select kvp.Value).FirstOrDefault();

            string signature = (from kvp in content.GetQueryNameValuePairs()
                                where kvp.Key == "signature"
                                select kvp.Value).FirstOrDefault();

            string timestamp = (from kvp in content.GetQueryNameValuePairs()
                                where kvp.Key == "timestamp"
                                select kvp.Value).FirstOrDefault();

            string nonce = (from kvp in content.GetQueryNameValuePairs()
                            where kvp.Key == "nonce"
                            select kvp.Value).FirstOrDefault();

            log.Info("echostr:" + echostr + " signature:" + signature + " nonce:" + nonce);
            string xmlContent = content.Content.ReadAsStringAsync().Result;
            string response   = string.Empty;

            log.Info("xml3:" + xmlContent);

            if (!string.IsNullOrEmpty(xmlContent))
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xmlContent);
                WeChatMessage msg = WeChatHelper.GetWxMessage(xmlContent);

                if (msg.MsgType.Trim() == "text")//用户发送一些文字信息
                {
                    string text = WXMsgUtil.GetFromXML(doc, "Content") + "";

                    response = WXMsgUtil.GetTulingMsg(text != ""?text:"你是谁?") + "";
                    log.Info("text:" + text + " tuling:" + response);
                }
                if (msg.MsgType.Trim() == "event")//点击菜单或者新增/取消关注
                {
                    switch (msg.EventName.Trim().ToLower())
                    {
                    case "click":          //点击菜单
                        response = "haha";
                        break;

                    case "subscribe":        //用户新增关注(可以返回一些欢迎信息之类)                                  
                        response = "wawa";
                        break;

                    case "unsubscribe":       //用户取消关注(一般不需要去返回什么信息)
                    default:
                        break;
                    }
                }

                HttpResponseMessage xmlResult = new HttpResponseMessage();
                xmlResult.Content = new StringContent(WXMsgUtil.CreateTextMsg(doc, response != "" ? response : "返回不能为空值!"));
                return(xmlResult);
            }
            string returnStr = "";

            if (string.IsNullOrEmpty(echostr) | string.IsNullOrEmpty(signature) | string.IsNullOrEmpty(timestamp) | string.IsNullOrEmpty(nonce))
            {
                returnStr = "error";
            }

            //if (CheckSignature(signature, timestamp, nonce))
            //{
            //    log.Info("验证成功,返回:" + echostr);
            returnStr = echostr;
            //}

            HttpResponseMessage result = new HttpResponseMessage();

            result.Content = new StringContent(returnStr != ""?returnStr:"返回不能为空值!");
            return(result);
        }
Beispiel #4
0
        public void ProcessRequest(HttpContext context)
        {
            Log.WriteDebug("ProcessRequest start");
            try
            {
                Stream stream    = context.Request.InputStream;
                byte[] byteArray = new byte[stream.Length];
                stream.Read(byteArray, 0, (int)stream.Length);
                string postXmlStr = System.Text.Encoding.UTF8.GetString(byteArray);
                Log.WriteDebug("1");
                if (!string.IsNullOrEmpty(postXmlStr))
                {
                    Log.WriteDebug("IsNullOrEmpty");
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(postXmlStr);
                    if (string.IsNullOrWhiteSpace(sToken))
                    {
                        Log.WriteDebug("string.IsNullOrWhiteSpace(sToken)");
                        DataTable dt = ConfigDal.GetConfig(WXMsgUtil.GetFromXML(doc, "ToUserName"));
                        DataRow   dr = dt.Rows[0];
                        sToken          = dr["Token"].ToString();
                        sAppID          = dr["AppID"].ToString();
                        sEncodingAESKey = dr["EncodingAESKey"].ToString();
                        Log.WriteDebug(sToken + "\r\n" + sAppID + "\r\n" + sEncodingAESKey + "\r\n");
                    }
                    Log.WriteDebug("2");
                    if (!string.IsNullOrWhiteSpace(sAppID))  //没有AppID则不解密(订阅号没有AppID)
                    {
                        Log.WriteDebug("!string.IsNullOrWhiteSpace(sAppID)");
                        //解密
                        WXBizMsgCrypt wxcpt     = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID);
                        string        signature = context.Request["msg_signature"];
                        string        timestamp = context.Request["timestamp"];
                        string        nonce     = context.Request["nonce"];
                        Log.WriteDebug(signature + "\r\n" + timestamp + "\r\n" + nonce + "\r\n");
                        string stmp = "";
                        int    ret  = wxcpt.DecryptMsg(signature, timestamp, nonce, postXmlStr, ref stmp);
                        if (ret == 0)
                        {
                            doc = new XmlDocument();
                            doc.LoadXml(stmp);

                            try
                            {
                                Log.WriteDebug("3");
                                responseMsg(context, doc);
                            }
                            catch (Exception ex)
                            {
                                //FileLogger.WriteErrorLog(context, ex.Message);
                                Log.WriteError(ex.Message);
                            }
                        }
                        else
                        {
                            //FileLogger.WriteErrorLog(context, "解密失败,错误码:" + ret);
                            Log.WriteError("解密失败,错误码:" + ret);
                        }
                    }
                    else
                    {
                        Log.WriteDebug("responseMsg(context, doc);");
                        responseMsg(context, doc);
                    }
                }
                else
                {
                    Log.WriteError("valid(context);");
                    valid(context);
                }
            }
            catch (Exception ex)
            {
                //FileLogger.WriteErrorLog(context, ex.Message);
                Log.WriteError("ProcessRequest" + context.ToString() + ex.Message);
            }
        }
Beispiel #5
0
        public void responseMsg(HttpContext context, XmlDocument xmlDoc)
        {
            string result  = "";
            string msgType = WXMsgUtil.GetFromXML(xmlDoc, "MsgType");

            switch (msgType)
            {
            case "event":
                switch (WXMsgUtil.GetFromXML(xmlDoc, "Event"))
                {
                case "subscribe":         //订阅
                    break;

                case "unsubscribe":         //取消订阅
                    break;

                case "CLICK":
                    DataTable dtMenuMsg = MenuMsgDal.GetMenuMsg(WXMsgUtil.GetFromXML(xmlDoc, "EventKey"));
                    if (dtMenuMsg.Rows.Count > 0)
                    {
                        List <Dictionary <string, string> > dictList = new List <Dictionary <string, string> >();
                        foreach (DataRow dr in dtMenuMsg.Rows)
                        {
                            Dictionary <string, string> dict = new Dictionary <string, string>();
                            dict["Title"]       = dr["Title"].ToString();
                            dict["Description"] = dr["Description"].ToString();
                            dict["PicUrl"]      = dr["PicUrl"].ToString();
                            dict["Url"]         = dr["Url"].ToString();
                            dictList.Add(dict);
                        }
                        result = WXMsgUtil.CreateNewsMsg(xmlDoc, dictList);
                    }
                    else
                    {
                        result = WXMsgUtil.CreateTextMsg(xmlDoc, "无此消息哦");
                    }
                    break;

                default:
                    break;
                }
                break;

            case "text":
                string text = WXMsgUtil.GetFromXML(xmlDoc, "Content");
                //if (text == "合肥" || text == "合肥天气" || text == "合肥天气预报"
                //    || text.ToLower() == "hf" || text.ToLower() == "hefei")
                //{
                //    result = WXMsgUtil.CreateNewsMsg(xmlDoc, WeatherUtil.GetWeatherInfo());
                //}
                //else
                {
                    result = WXMsgUtil.CreateNewsMsg(xmlDoc, Weather.GetForecastInfo(text));
                    //result = WXMsgUtil.CreateTextMsg(xmlDoc, WXMsgUtil.GetTulingMsg(text));
                }
                break;

            default:
                break;
            }

            if (!string.IsNullOrWhiteSpace(sAppID)) //没有AppID则不加密(订阅号没有AppID)
            {
                //加密
                WXBizMsgCrypt wxcpt       = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID);
                string        sEncryptMsg = ""; //xml格式的密文
                string        timestamp   = context.Request["timestamp"];
                string        nonce       = context.Request["nonce"];
                int           ret         = wxcpt.EncryptMsg(result, timestamp, nonce, ref sEncryptMsg);
                if (ret != 0)
                {
                    //FileLogger.WriteErrorLog(context, "加密失败,错误码:" + ret);
                    Log.WriteDebug("加密失败,错误码:" + ret);
                    return;
                }

                context.Response.Write(sEncryptMsg);
                context.Response.Flush();
            }
            else
            {
                context.Response.Write(result);
                context.Response.Flush();
            }
        }