コード例 #1
0
        //
        // GET: /UserInfo/

        public ActionResult Index()
        {
            #region 应用授权作用域,snsapi_base

            //授权获取到的code
            string code = "";
            //通过code获取用户信息 不需要关注公众号
            WeiXinUserSampleInfo sampleInfo = WeiXinHelper.GetUserSampleInfo(code);
            string openId = sampleInfo.OpenId;

            #endregion

            #region (思路一致,开发过程中没用到,暂时放空。。)snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)

            //授权获取到的code
            string code2 = "";
            //通过code获取用户信息 不需要关注公众号
            WeiXinUserSampleInfo sampleInfo2 = WeiXinHelper.GetUserSampleInfo(code2);
            string openId2     = sampleInfo2.OpenId;
            string accessToken = sampleInfo2.Access_Token;

            //todo:刷新accessToken 获取 refresh_token(如果需要)

            //todo:获取用户信息


            #endregion

            //这种方法获取用户信息,需要用户关注公众号
            WeiXinUserInfo info = WeiXinHelper.GetUserInfo(openId);

            return(View());
        }
コード例 #2
0
        /// <summary>
        /// 根据OpenID 获取用户基本信息(需关注公众号)
        /// </summary>
        /// <param name="openId"></param>
        public static WeiXinUserInfo GetUserInfo(string openId)
        {
            var    token = AccessToken.NewInstance();
            string url   = string.Format(WeiXinConst.WeiXin_User_GetInfoUrl, token.Access_Token, openId);

            string result = HttpClientHelper.GetResponse(url);

            if (string.IsNullOrEmpty(result))
            {
                return(null);
            }

            WeiXinUserInfo info = JsonConvert.DeserializeObject <WeiXinUserInfo>(result);

            //解析用户信息失败,判断 失败Code ,40001 为AccessToken失效,重新创建Token并获取用户信息
            if (info == null || string.IsNullOrEmpty(info.OpenId))
            {
                ErrorMessage msg = JsonConvert.DeserializeObject <ErrorMessage>(result);
                if (msg.TokenExpired)
                {
                    return(GetUserInfoByNewAccessToken(openId));
                }
            }

            return(info);
        }
コード例 #3
0
        private void DoCheck()
        {
            CheckAgent();
            if (HttpContext.Current.Session["user"] != null)
            {
                WeiXinUserInfo userinfo = HttpContext.Current.Session["user"] as WeiXinUserInfo;
                Nickname   = userinfo.nickname;
                Headimgurl = userinfo.headimgurl;
                Openid     = userinfo.openid;
            }
            else
            {
                //获取appId,appSecret的配置信息
                string          appId       = System.Configuration.ConfigurationSettings.AppSettings["appid"];
                string          appSecret   = System.Configuration.ConfigurationSettings.AppSettings["secret"];
                BLL.WeiXinOAuth weixinOAuth = new WeiXinOAuth();
                //微信第一次握手后得到的code 和state
                _code = HttpContext.Current.Request.QueryString["code"] == null ? "" : HttpContext.Current.Request.QueryString["code"].ToString();

                if (_code == "" || _code == "authdeny")
                {
                    if (_code == "")
                    {
                        //发起授权(第一次微信握手)
                        string _authUrl = weixinOAuth.GetWeiXinCode(appId, appSecret, HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.Url.ToString()));
                        HttpContext.Current.Response.Redirect(_authUrl, true);
                    }
                    else
                    { // 用户取消授权
                        GoNoFound("必须要您的授权才能进入哦!");
                    }
                }
                else
                {
                    //获取微信的Access_Token(第二次微信握手)
                    Model.WeiXinAccessTokenResult modelResult = weixinOAuth.GetWeiXinAccessToken(appId, appSecret, _code);

                    //获取微信的用户信息(第三次微信握手)
                    Model.WeiXinUserInfoResult _userInfo = weixinOAuth.GetWeiXinUserInfo(modelResult.SuccessResult.access_token, modelResult.SuccessResult.openid);

                    //用户信息(判断是否已经获取到用户的微信用户信息)
                    if (_userInfo.Result && _userInfo.UserInfo.openid != "")
                    {
                        WeiXinUserInfo UserInfo = new WeiXinUserInfo();
                        //保存获取到的用户微信用户信息,并保存到数据库中
                        Nickname            = _userInfo.UserInfo.nickname;
                        Headimgurl          = _userInfo.UserInfo.headimgurl;
                        Openid              = _userInfo.UserInfo.openid;
                        UserInfo.openid     = _userInfo.UserInfo.openid;
                        UserInfo.headimgurl = _userInfo.UserInfo.headimgurl;
                        UserInfo.nickname   = _userInfo.UserInfo.nickname;
                        HttpContext.Current.Session["user"] = UserInfo;
                    }
                    else
                    {
                        GoNoFound("获取用户OpenId失败");
                    }
                }
            }
        }
コード例 #4
0
 /// <summary>
 /// 创建新的AccessToken 并获取用户信息
 /// </summary>
 /// <param name="openId"></param>
 /// <returns></returns>
 private static WeiXinUserInfo GetUserInfoByNewAccessToken(string openId)
 {
     var token = AccessToken.CreateNewInstance();
     string url = string.Format(WeChatConstModel.WeiXinUserGetInfoUrl, token.Access_Token, openId);
     WeiXinUserInfo info = HttpClientHelper.GetResponse<WeiXinUserInfo>(url);
     return info;
 }
コード例 #5
0
        /// <summary>
        /// 创建新的AccessToken 并获取用户信息
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        private static WeiXinUserInfo GetUserInfoByNewAccessToken(string openId)
        {
            var            token = AccessToken.NewInstance();
            string         url   = string.Format(WeiXinConst.WeiXin_User_GetInfoUrl, token.Access_Token, openId);
            WeiXinUserInfo info  = HttpClientHelper.GetResponse <WeiXinUserInfo>(url);

            return(info);
        }
コード例 #6
0
        /// <summary>
        /// 授权
        /// </summary>
        /// <param name="code"></param>
        /// <param name="returnUrl"></param>
        public string Authorize(string code, string returnUrl)
        {
            OAuthAccessTokenResult oAuthAccessTokenResult = null;

            oAuthAccessTokenResult = OAuthApi.GetAccessToken(
                WechatAppSettings.AppId,
                WechatAppSettings.CorpSecret,
                code);

            if (oAuthAccessTokenResult == null)
            {
                throw new Exception("错误消息:oAuthAccessTokenResult为空");
            }

            if (oAuthAccessTokenResult != null &&
                oAuthAccessTokenResult.errcode
                != ReturnCode.请求成功)
            {
                throw new Exception("错误消息:" + oAuthAccessTokenResult.errmsg);
            }

            var userInfo = OAuthApi.GetUserInfo(
                oAuthAccessTokenResult.access_token,
                oAuthAccessTokenResult.openid
                );
            var item = _baseRepository.GetAll().FirstOrDefault(x => x
                                                               .OpenId == userInfo.openid);

            if (item == null)
            {
                var model = new WeiXinUserInfo
                {
                    City       = userInfo.city,
                    Country    = userInfo.country,
                    HeadImgUrl = userInfo.headimgurl,
                    NickName   = userInfo.nickname,
                    OpenId     = userInfo.openid,
                    Province   = userInfo.province,
                    Sex        = userInfo.sex.ToString(),
                    UnionId    = userInfo.unionid
                };
                _baseRepository.Insert(model);
            }

            if (returnUrl.Contains("?"))
            {
                returnUrl = returnUrl + "&access_token=" + oAuthAccessTokenResult.access_token + "&openid=" + oAuthAccessTokenResult.openid;
            }
            else
            {
                returnUrl = returnUrl + "?access_token=" + oAuthAccessTokenResult.access_token + "&openid=" + oAuthAccessTokenResult.openid;
            }


            return(returnUrl);
        }
コード例 #7
0
 private void FillOAuthUserInfoToWxUserInfo(OAuthUserInfo userInfo, WeiXinUserInfo wxUserInfo)
 {
     wxUserInfo.City       = userInfo.city;
     wxUserInfo.Country    = userInfo.country;
     wxUserInfo.HeadImgUrl = userInfo.headimgurl;
     wxUserInfo.NickName   = userInfo.nickname;
     wxUserInfo.OpenId     = userInfo.openid;
     wxUserInfo.Province   = userInfo.province;
     wxUserInfo.Sex        = userInfo.sex;
     wxUserInfo.UnionId    = userInfo.unionid;
 }
コード例 #8
0
ファイル: WXApi.ashx.cs プロジェクト: wwkkww1983/ice-grid
        public void responseMsg(HttpContext context, XmlDocument xmlDoc)
        {
            string result = "";
            string msgType = WeiXinXML.GetFromXML(xmlDoc, "MsgType");
            switch (msgType)
            {
                case "event":
                    switch (WeiXinXML.GetFromXML(xmlDoc, "Event"))
                    {
                        case "subscribe": //订阅
                            String retUserInfo = getUserInfo(WeiXinXML.GetFromXML(xmlDoc, "FromUserName"));
                            Util.Debuglog("getUserInfo" + retUserInfo, "wxapi.txt");
                            if (retUserInfo.Contains("errcode"))
                            {

                            }
                            else
                            {
                                WeiXinUserInfo info = JsonConvert.DeserializeObject<WeiXinUserInfo>(retUserInfo);
                                if (!string.IsNullOrEmpty(info.OpenId) && !string.IsNullOrEmpty(info.UnionId))
                                {
                                    Util.Debuglog("info=" + info.ToString(), "wxapi.txt");
                                    string sql = "select * from asm_member where unionID='" + info.UnionId + "'";
                                    Util.Debuglog("sql=" + sql, "wxapi.txt");
                                    DataTable dt = DbHelperSQL.Query(sql).Tables[0];
                                    if (dt.Rows.Count <= 0)
                                    {
                                        string insert = "insert into asm_member(name,phone,province,city,country,AvailableMoney,sumConsume,sumRecharge,createDate,companyID,headurl,nickname,sex,unionID,openID,consumeCount)"
                                            + " values(N'" + info.NickName + "','','" + info.Province + "','" + info.City + "','" + info.Conuntry + "',0,0,0,'" + DateTime.Now + "',14,'" + info.HeadImgUrl + "',N'" + info.NickName + "','" + info.Sex + "','" + info.UnionId + "','" + info.OpenId + "',0)";
                                        Util.Debuglog(insert, "wxapi.txt");
                                        DbHelperSQL.ExecuteSql(insert);
                                    }
                                    else
                                    {
                                        //更新
                                        string update = "update asm_member set openID='" + info.OpenId + "' where unionID='" + info.UnionId + "'";
                                        Util.Debuglog("更新" + update, "wxapi.txt");
                                        DbHelperSQL.ExecuteSql(update);
                                    }

                                }
                            }

                            string sqlcom = "select * from asm_company where user_name='" + WeiXinXML.GetFromXML(xmlDoc, "ToUserName") + "'";
                            Util.Debuglog("sqlcom=" + sqlcom, "wxapi.txt");
                            DataTable dtcom = DbHelperSQL.Query(sqlcom).Tables[0];
                            string txt ="";
                            if (dtcom.Rows.Count > 0){
                                txt = dtcom.Rows[0]["subscribe_info"].ToString();
                            }
                            result = WeiXinXML.CreateTextMsg(xmlDoc,txt);
                            Util.Debuglog("用户关注result="+ result, "wxapi.txt");

                            break;
                        case "unsubscribe": //取消订阅
                            Util.Debuglog("取消订阅", "wxapi.txt");
                            break;
                        case "LOCATION":
                            string Latitude = WeiXinXML.GetFromXML(xmlDoc, "Latitude");
                            string Longitude = WeiXinXML.GetFromXML(xmlDoc, "Longitude");
                            Util.Debuglog("Latitude="+ Latitude+ ";Longitude="+ Longitude, "wxapi.txt");
                            break;
                        default:

                            break;
                    }
                    break;

                default:
                    break;
            }

            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID);
            string signature = context.Request["msg_signature"];
            string timestamp = context.Request["timestamp"];
            string nonce = context.Request["nonce"];
            string stmp = "";
            int ret = wxcpt.EncryptMsg(result, timestamp, nonce, ref stmp);
            context.Response.Write(stmp);

            context.Response.Flush();
        }
コード例 #9
0
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);


            #region weixin

            //ExternalLoginInfo loginInfo = AuthManager.GetExternalLoginInfo();
            //var user =  UserManager.Find(loginInfo.Login);

            var code  = WebHelper.GetQueryString("code");
            var state = WebHelper.GetQueryString("state");
            _workContext.openId = WebUtils.GetCookie("openid");
            if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(state) && state == this.WorkContext.WeiXinMPConfig.AuthorizeState)
            {
                OAuthAccessTokenResult result = null;
                try
                {
                    result = GetOAuthAccessTokenResult(code);
                }
                catch (Exception)
                { }

                if (result != null && result.errcode == ReturnCode.请求成功)
                {
                    _workContext.openId = result.openid;
                }
                WebUtils.SetCookie("openid", _workContext.openId);

                var           access_token = GetToken();
                OAuthUserInfo userInfo     = OAuthApi.GetUserInfo(access_token, _workContext.openId);

                var wxUserInfoManager = new UserInfoManager();
                var wxUserInfo        = wxUserInfoManager.FindById(_workContext.openId);
                if (wxUserInfo == null)
                {
                    wxUserInfo = new WeiXinUserInfo()
                    {
                        OrganizationId = _workContext.UserInfo.OrganizationId,
                    };
                    FillOAuthUserInfoToWxUserInfo(userInfo, wxUserInfo);
                    wxUserInfoManager.Create(wxUserInfo);
                }
                else
                {
                    FillOAuthUserInfoToWxUserInfo(userInfo, wxUserInfo);
                    wxUserInfoManager.Update(wxUserInfo);
                }
                this._workContext.WxUserInfo = wxUserInfo;
            }

            //测试用
#if DEBUG
            //if (string.IsNullOrWhiteSpace(_workContext.openId) && Request.Url.Host.ToLower().Equals("localhost"))
            //{
            //    _workContext.openId = "ozZZ5t_VheKVfHlv03srm6ylieyU";
            //    WebUtils.SetCookie("openid", _workContext.openId);
            //}
#endif
            if (this._workContext.WxUserInfo == null && !string.IsNullOrEmpty(_workContext.openId))
            {
                var wxUserInfoManager = new UserInfoManager();
                this._workContext.WxUserInfo = wxUserInfoManager.FindById(_workContext.openId);
            }
            //UserInfo
            if (!requestContext.HttpContext.User.Identity.IsAuthenticated && !string.IsNullOrEmpty(_workContext.openId))
            {
                var bindMng = new UserBindManager();
                var userId  = bindMng.GetUserId(_workContext.openId);
                if (!string.IsNullOrEmpty(userId))
                {
                    _workContext.UserInfo = UserManager.FindById(userId);
                    SignInManager.SignInAsync(_workContext.UserInfo, isPersistent: true, rememberBrowser: true);
                }
                else
                {
                    string randomEmail = string.Format("{0}@xh2005.com", Guid.NewGuid());
                    var    user        = new ApplicationUser {
                        OrganizationId = "DebugOrganizationID", UserName = randomEmail, Email = randomEmail
                    };
                    if (this._workContext.WxUserInfo != null)
                    {
                        user.NiceName = this._workContext.WxUserInfo.NickName;
                    }
                    var result = UserManager.Create(user, Guid.NewGuid().ToString());
                    if (result.Succeeded)
                    {
                        bindMng.BindUser(user.Id, _workContext.openId);
                        SignInManager.SignIn(user, isPersistent: true, rememberBrowser: true);
                    }
                    _workContext.UserInfo = user;
                }

                //var access_token = GetToken();
                //OAuthUserInfo userInfo = OAuthApi.GetUserInfo(access_token, _workContext.openId);

                //var wxUserInfoManager = new UserInfoManager();
                //var wxUserInfo = wxUserInfoManager.FindById(_workContext.openId);
                //if (wxUserInfo == null)
                //{
                //    wxUserInfo = new WeiXinUserInfo()
                //    {
                //        OrganizationId = _workContext.UserInfo.OrganizationId,
                //    };
                //    FillOAuthUserInfoToWxUserInfo(userInfo, wxUserInfo);
                //    wxUserInfoManager.Create(wxUserInfo);
                //}
                //else {
                //    FillOAuthUserInfoToWxUserInfo(userInfo, wxUserInfo);
                //    wxUserInfoManager.Update(wxUserInfo);
                //}

                //var claims = new List<Claim>();
                //claims.Add(new Claim(ClaimTypes.NameIdentifier, userId));
                //claims.Add(new Claim(ClaimTypes.Name, _workContext.UserInfo.UserName));
                //claims.Add(new Claim(ClaimTypes.Sid, _workContext.openId));
                //var identity = new ClaimsIdentity(claims, "weixin");
                //var principal = new ClaimsPrincipal(identity);
                //requestContext.HttpContext.User = principal;
            }
            else if (requestContext.HttpContext.User.Identity.IsAuthenticated)
            {
                _workContext.UserInfo = UserManager.FindByName(requestContext.HttpContext.User.Identity.Name);
                _workContext.UserId   = requestContext.HttpContext.User.Identity.GetUserId();
                _workContext.UserName = requestContext.HttpContext.User.Identity.GetUserName();
                var bindMng = new UserBindManager();
                _workContext.openId = bindMng.GeOpenId(_workContext.UserId);
                WebUtils.SetCookie("openid", _workContext.openId);
            }


            #endregion

            #region workcontext
            //Reqeust
            _workContext.IsHttpAjax  = WebHelper.IsAjax();
            _workContext.IP          = WebHelper.GetIP();
            _workContext.Url         = WebHelper.GetUrl();
            _workContext.UrlReferrer = WebHelper.GetUrlReferrer();

            //当前控制器类名
            _workContext.Controller = requestContext.RouteData.Values["controller"].ToString().ToLower();
            //当前动作方法名
            _workContext.Action  = RouteData.Values["action"].ToString().ToLower();
            _workContext.PageKey = string.Format("/{0}/{1}", _workContext.Controller, _workContext.Action);
            #endregion
        }
コード例 #10
0
        public ActionResult Generalize(string id)
        {
            string key = HotelCloud.Common.HCRequest.GetString("key");

            string[] keys = key.Split('@');
            if (keys.Length == 2)
            {
                string weixinID     = keys[0];
                string userWeiXinID = keys[1];

                ViewData["hid"]          = id;
                ViewData["weixinID"]     = weixinID;
                ViewData["userWeiXinID"] = userWeiXinID;

                hotel3g.Repository.MemberCard CurUser = hotel3g.Repository.MemberHelper.GetFXMemberCard(userWeiXinID, weixinID);


                if (string.IsNullOrEmpty(CurUser.photo))
                {
                    AccessToken TokenItem = MemberHelper.GetAccessToken(weixinID);
                    if (TokenItem.error == 1)
                    {
                        try
                        {
                            WeiXinUserInfo UserInfo = MemberHelper.GetUserWeixinInfo(TokenItem.message, userWeiXinID);
                            CurUser.nickname = UserInfo.nickname;
                            if (!string.IsNullOrEmpty(UserInfo.headimgurl))
                            {
                                CurUser.photo = UserInfo.headimgurl;
                                string sql_ = "UPDATE dbo.Member SET photo=@photo WHERE weixinID=@weixinID AND userWeiXinNO=@userWeiXinNO";
                                Dictionary <string, DBParam> Dic = new Dictionary <string, DBParam>();
                                Dic.Add("photo", new DBParam {
                                    ParamValue = CurUser.photo
                                });
                                Dic.Add("weixinID", new DBParam {
                                    ParamValue = weixinID
                                });
                                Dic.Add("userWeiXinNO", new DBParam {
                                    ParamValue = userWeiXinID
                                });
                                int Count = SQLHelper.Run_SQL(sql_, SQLHelper.GetCon(), Dic);
                            }
                        }
                        catch { }
                    }
                }
                if (!string.IsNullOrEmpty(CurUser.photo))
                {
                    CurUser.photo = PromoterDAL.GetPromoterCoverImage(CurUser.photo, "PHOTO_" + userWeiXinID, id);
                }
                else
                {
                    CurUser.photo = "/images/member/wechat.png";
                }
                ViewData["CurUser"] = CurUser;
                //获取酒店信息
                hotel3g.Repository.HotelInfoItem HotelInfo = hotel3g.Repository.MemberHelper.GetHotelInfo(weixinID, id);
                ViewData["HotelLogo"] = PromoterDAL.GetPromoterCoverImage(HotelInfo.hotelLog, "hotelLog", id);
                ViewData["HotelInfo"] = HotelInfo;

                //获取公众号信息
                //string sql = "SELECT TOP 1 WeiXin2Img,appid,weixintype,WeiXinImg FROM dbo.WeiXinNO WITH(NOLOCK) WHERE WeiXinID=@WeiXinID";
                //DataTable dt = SQLHelper.Get_DataTable(sql, SQLHelper.GetCon(), new Dictionary<string, DBParam>() {
                //{"WeiXinID",new DBParam{ParamValue=weixinID}}
                //});

                ViewData["weixintype"] = "0";
                hotel3g.PromoterEntitys.WeiXinPublicInfoResponse WeiXinPublicInfo = PromoterDAL.GetWeiXinPublicInfo(weixinID);
                if (WeiXinPublicInfo != null && !string.IsNullOrEmpty(WeiXinPublicInfo.appid))
                {
                    string weixintype = WeiXinPublicInfo.weixintype.ToString();
                    ViewData["weixintype"] = weixintype;
                    if (int.Parse(CurUser.memberid) > 0)
                    {
                        if (weixintype.Equals("4"))
                        {
                            string logourl = QR_Code_Url(int.Parse(CurUser.memberid), weixinID);
                            string Logo    = PromoterDAL.GetPromoterCoverImage(logourl, "LOGO", id);
                            ViewData["Logo"] = Logo;
                        }
                        else
                        {
                            string logourl = "http://qr.liantu.com/api.php?text=" + HttpUtility.UrlEncode(string.Format("http://hotel.weikeniu.com/Promoter/Coupon/{0}?hid={1}", CurUser.memberid, id));
                            string Logo    = PromoterDAL.GetPromoterCoverImage(logourl, "LOGO", id);
                            //生成跳转链接
                            ViewData["Logo"] = Logo;
                        }

                        if (string.IsNullOrEmpty(HotelInfo.MainPic))
                        {
                            //生成跳转链接
                            string backgroundurl = WeiXinPublicInfo.WeiXinImg;// dt.Rows[0]["WeiXinImg"].ToString();
                            string background    = PromoterDAL.GetPromoterCoverImage(backgroundurl, "BACKGROUND", id);
                            ViewData["background"] = background;
                        }
                        else
                        {
                            //生成跳转链接
                            string backgroundurl = HotelInfo.MainPic.Split(';')[0];
                            string background    = PromoterDAL.GetPromoterCoverImage(backgroundurl, "BACKGROUND", id);
                            ViewData["background"] = background;
                        }
                    }
                    ViewData["appid"] = WeiXinPublicInfo.appid;// dt.Rows[0]["appid"].ToString();
                }

                //获取红包信息
                string sql = "SELECT moneys,Remark,s_JiFen FROM dbo.CouPon WITH(NOLOCK) WHERE weixinID=@WeiXinID AND s_huodongid>0";
                System.Data.DataTable hongbao = SQLHelper.Get_DataTable(sql, SQLHelper.GetCon(), new Dictionary <string, DBParam>()
                {
                    { "WeiXinID", new DBParam {
                          ParamValue = weixinID
                      } }
                });
                var Signature = WeiXinJsSdkDAL.JsApiSignature(weixinID, Request.Url.AbsoluteUri);
                ViewData["timespan"]  = Signature.timestamp;
                ViewData["signature"] = Signature;

                if (hongbao != null && hongbao.Rows.Count > 0)
                {
                    ViewData["Remark"] = hongbao.Rows[0]["Remark"].ToString();
                    ViewData["money"]  = hongbao.Rows[0]["moneys"].ToString();
                    ViewData["info"]   = hongbao.Rows[0]["Remark"].ToString();
                    ViewData["jifen"]  = hongbao.Rows[0]["s_JiFen"].ToString();
                }
            }

            return(View());
        }