Exemplo n.º 1
0
        /// <summary>
        ///【强制刷新】access_token值
        /// access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。正常情况下access_token有效期为7200秒,
        /// 重复获取将导致上次获取的access_token失效。
        /// 每日限额获取access_token.我们将access_token保存到数据库里,间隔时间为20分钟,从微信公众平台获得一次。
        /// </summary>
        /// <returns></returns>
        public static string FlushAccessToken(int wid, out string error)
        {
            string token = "";

            error = "";
            try
            {
                wx_property_info  pBll = new wx_property_info();
                BLL.wx_userweixin wBll = new wx_userweixin();

                Model.wx_userweixin weixininfo = wBll.GetModel(wid);
                if (weixininfo.AppId == null || weixininfo.AppSecret == null || weixininfo.AppId.Trim().Length <= 0 || weixininfo.AppSecret.Trim().Length <= 0)
                {
                    error = "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息!";
                    return("");
                }

                var result = CommonApi.GetToken(weixininfo.AppId, weixininfo.AppSecret);
                token = result.access_token;


                //第一次插入微信属性表
                if (!pBll.ExistsWid(wid, "access_token"))
                {
                    //插入
                    pBll.AddAccess_Token(wid, token, result.expires_in);
                }
                else
                {
                    WeiXinPF.Model.wx_property_info wxProperty = new WeiXinPF.Model.wx_property_info();
                    wxProperty = pBll.GetModelList("iName='access_token' and wid=" + wid)[0];
                    //更新到数据库里
                    wxProperty.iContent   = token;
                    wxProperty.createDate = DateTime.Now;
                    wxProperty.expires_in = result.expires_in;
                    pBll.Update(wxProperty);
                }
            }
            catch (Exception ex)
            {
                error = "获得access_token出错:" + ex.Message;
                WXLogs.AddLog(wid, "access_token", "获得access_token(FlushAccessToken)", error);
            }

            return(token);
        }
Exemplo n.º 2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string Token = "";//与微信公众账号后台的Token设置保持一致,区分大小写。
            int    wid   = 0;

            wid = MyCommFun.RequestInt("apiid");

            if (wid <= 0)
            {
                WriteContent("参数非法");
                return;
            }
            wx_userweixin wbll = new wx_userweixin();

            Token = wbll.GetWeiXinToken(wid);
            if (Token == null || string.IsNullOrEmpty(Token))
            {
                WriteContent("不存在该微信号或账号已过期或已被禁用!");
                return;
            }


            // Token = "uweixin";
            string signature = Request["signature"];
            string timestamp = Request["timestamp"];
            string nonce     = Request["nonce"];
            string echostr   = Request["echostr"];

            if (Request.HttpMethod == "GET")
            {
                //get method - 仅在微信后台填写URL验证时触发
                if (CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent(echostr); //返回随机字符串则表示验证通过
                }
                else
                {
                    WriteContent("failed:" + signature + ",token:" + Token + " " + CheckSignature.GetSignature(timestamp, nonce, Token) + "。" +
                                 "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。");
                }
                Response.End();
            }
            else
            {
                //本地测试的时候注释掉 ----start -----

                if (!CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent("参数错误!");
                    return;
                }
                //本地测试的时候注释掉 ----end -----

                //post method - 当有用户想公众账号发送消息时触发
                Model.wx_userweixin uweixin = wbll.GetModel(wid);
                var postModel = new PostModel()
                {
                    Signature     = Request.QueryString["signature"],
                    Msg_Signature = Request.QueryString["msg_signature"],
                    Timestamp     = Request.QueryString["timestamp"],
                    Nonce         = Request.QueryString["nonce"],
                    //以下保密信息不会(不应该)在网络上传播,请注意
                    Token          = Token,
                    EncodingAESKey = uweixin.extStr, //根据自己后台的设置保持一致
                    AppId          = uweixin.AppId   //根据自己后台的设置保持一致
                };


                //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制
                var maxRecordCount = 10;

                //自定义MessageHandler,对微信请求的详细判断操作都在这里面。
                var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount);

                try
                {
                    //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。
                    messageHandler.RequestDocument.Save(
                        Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" +
                                       messageHandler.RequestMessage.FromUserName + ".txt"));
                    //执行微信处理过程
                    messageHandler.Execute();
                    //测试时可开启,帮助跟踪数据
                    messageHandler.ResponseDocument.Save(
                        Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" +
                                       messageHandler.ResponseMessage.ToUserName + ".txt"));


                    //为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 begin
                    string lastStr = "";
                    if (messageHandler != null && messageHandler.ResponseDocument != null && messageHandler.ResponseDocument.ToString().Trim() != "")
                    {
                        lastStr = messageHandler.ResponseDocument.ToString().Replace("\r\n", "\n");
                    }
                    else
                    {
                        lastStr = messageHandler.ResponseDocument.ToString();
                    }
                    // WriteContent( messageHandler.ResponseDocument.ToString());
                    //为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 end

                    //如果自动回复已经关闭,则不返回内容,start 1220

                    WeiXCommFun wxcomm = new WeiXCommFun();
                    int         apiid  = wxcomm.getApiid();
                    if (!wxcomm.wxCloseKW(apiid))
                    {
                        lastStr = "";
                    }
                    //如果自动回复已经关闭,则不返回内容,end 1220

                    WriteContent(lastStr);
                    return;
                }
                catch (Exception ex)
                {
                    using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".txt")))
                    {
                        tw.WriteLine(ex.Message);
                        tw.WriteLine(ex.InnerException.Message);
                        if (messageHandler.ResponseDocument != null)
                        {
                            tw.WriteLine(messageHandler.ResponseDocument.ToString());
                        }
                        tw.Flush();
                        tw.Close();
                    }
                    WriteContent("");
                }
                finally
                {
                    Response.End();
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 及时获得access_token值
        /// access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。正常情况下access_token有效期为7200秒,
        /// 重复获取将导致上次获取的access_token失效。
        /// 每日限额获取access_token.我们将access_token保存到数据库里,间隔时间为20分钟,从微信公众平台获得一次。
        /// </summary>
        /// <returns></returns>
        public static string getAccessToken(int wid, out string error)
        {
            string token = "";

            error = "";
            try
            {
                wx_property_info  pBll = new wx_property_info();
                BLL.wx_userweixin wBll = new wx_userweixin();

                Model.wx_userweixin weixininfo = wBll.GetModel(wid);
                if (weixininfo.AppId == null || weixininfo.AppSecret == null ||
                    weixininfo.AppId.Trim().Length <= 0 || weixininfo.AppSecret.Trim().Length <= 0)
                {
                    error = "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息!";
                    WXLogs.AddLog(wid, "access_token", "获得access_token", error);
                    return("");
                }
                WeiXinPF.Model.wx_property_info wxProperty = new WeiXinPF.Model.wx_property_info();
                //第一次插入微信属性表
                if (!pBll.ExistsWid(wid, "access_token"))
                {
                    AccessTokenResult result = CommonApi.GetToken(weixininfo.AppId, weixininfo.AppSecret);
                    token = result.access_token;
                    pBll.AddAccess_Token(wid, token, result.expires_in);
                    return(token);

                    //WeChatAccountManager manager = WeChatAccountManager.CreateInstance(weixininfo.AppId, weixininfo.AppSecret);
                    //Credential credential = new Credential(manager);
                    //token = credential.AccessToken;
                    //pBll.AddAccess_Token(wid, token, 7000);
                    //return token;
                }

                wxProperty = pBll.GetModelList("iName='access_token' and wid=" + wid)[0];
                double chajunSecond = (DateTime.Now - wxProperty.createDate.Value).TotalSeconds;

                if (chajunSecond >= wxProperty.expires_in)
                {
                    //从微信平台重新获得access_token
                    AccessTokenResult result = CommonApi.GetToken(weixininfo.AppId, weixininfo.AppSecret);
                    token = result.access_token;
                    //更新到数据库里
                    wxProperty.iContent   = token;
                    wxProperty.createDate = DateTime.Now;
                    wxProperty.expires_in = result.expires_in;

                    //WeChatAccountManager manager = WeChatAccountManager.CreateInstance(weixininfo.AppId, weixininfo.AppSecret);
                    //Credential credential = new Credential(manager);
                    //token = credential.AccessToken;
                    ////更新到数据库里
                    //wxProperty.iContent = token;
                    //wxProperty.createDate = DateTime.Now;
                    //wxProperty.expires_in = 7000;
                    //pBll.Update(wxProperty);
                }
                else
                {
                    token = wxProperty.iContent;
                }
            }
            catch (Exception ex)
            {
                error = "获得access_token出错:" + ex.Message;
                WXLogs.AddLog(wid, "access_token", "获得access_token", error);
            }
            return(token);
        }
Exemplo n.º 4
0
        /// <summary>
        /// 获取jssdk 里的临时票据
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static string getJsApiTicket(int wid, out string error)
        {
            string atErr       = "";
            string accessToken = getAccessToken(wid, out atErr);

            if (atErr != "")
            {
                accessToken = FlushAccessToken(wid, out atErr);
            }
            if (accessToken == "")
            {
                error = "取accessToken值出现异常";
                WXLogs.AddLog(wid, "getJsApiTicket", "获得getJsApiTicket", "WeiXinPF.WeiXinComm.getJsApiTicket" + error);
                return("");
            }

            string token = "";

            error = "";
            try
            {
                wx_property_info  pBll = new wx_property_info();
                BLL.wx_userweixin wBll = new wx_userweixin();

                Model.wx_userweixin weixininfo = wBll.GetModel(wid);
                if (weixininfo.AppId == null || weixininfo.AppSecret == null || weixininfo.AppId.Trim().Length <= 0 || weixininfo.AppSecret.Trim().Length <= 0)
                {
                    error = "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息!";
                    return("");
                }
                WeiXinPF.Model.wx_property_info wxProperty = new WeiXinPF.Model.wx_property_info();
                //第一次插入微信属性表
                if (!pBll.ExistsWid(wid, "JsApiTicket"))
                {
                    string type = "jsapi";
                    var    url  = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type={1}",
                                                accessToken, type);

                    JsApiTicketResult result = OneGulp.WeChat.HttpUtility.Get.GetJson <JsApiTicketResult>(url);
                    token = result.ticket;
                    //存入属性表
                    wxProperty.wid        = wid;
                    wxProperty.iName      = "JsApiTicket";
                    wxProperty.iContent   = token;
                    wxProperty.createDate = DateTime.Now;
                    wxProperty.expires_in = result.expires_in;
                    wxProperty.count      = 1;
                    pBll.Add(wxProperty);

                    return(token);
                }

                wxProperty = pBll.GetModelList("iName='JsApiTicket' and wid=" + wid)[0];
                double chajunSecond = (DateTime.Now - wxProperty.createDate.Value).TotalSeconds;

                if (chajunSecond >= wxProperty.expires_in)
                {  //从微信平台重新获得access_token
                    string type = "jsapi";
                    var    url  = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type={1}",
                                                accessToken, type);

                    JsApiTicketResult result = OneGulp.WeChat.HttpUtility.Get.GetJson <JsApiTicketResult>(url);
                    token = result.ticket;

                    //更新到数据库里
                    wxProperty.iContent   = token;
                    wxProperty.createDate = DateTime.Now;
                    wxProperty.expires_in = result.expires_in;
                    pBll.Update(wxProperty);
                }
                else
                {
                    token = wxProperty.iContent;
                }
            }
            catch (Exception ex)
            {
                error = "获得getJsApiTicket出错:" + ex.Message;
                WXLogs.AddLog(wid, "getJsApiTicket", "获得getJsApiTicket", "WeiXinPF.WeiXinComm.getJsApiTicket" + error);
            }
            return(token);
        }