예제 #1
0
        /// <summary>
        /// 获取openId对应的用户信息并存入数据库
        /// </summary>
        /// <param name="openId">微信用户openId</param>
        /// <param name="execute">修改、删除或插入操作</param>
        /// <param name="failList">未成功获取到用户信息的openId列表</param>
        private static void ExecuteWeixinUser(string openId, GetExecute execute, List <string> failList)
        {
            string accessToken = AccessTokenContainer.TryGetToken(ConfigurationManager.AppSettings["appID"], ConfigurationManager.AppSettings["appsecret"]);
            var    userInfo    = User.Info(accessToken, openId);

            if (userInfo.errcode != ReturnCode.请求成功)
            {
                failList.Add(openId);
            }
            else
            {
                WeixinUserInfo entity = new WeixinUserInfo()
                {
                    City           = userInfo.city,
                    Province       = userInfo.province,
                    Country        = userInfo.country,
                    HeadImgUrl     = userInfo.headimgurl,
                    Language       = userInfo.language,
                    Subscribe_time = userInfo.subscribe_time,
                    Sex            = (Int16)userInfo.sex,
                    NickName       = userInfo.nickname,
                    OpenId         = userInfo.openid
                };
                execute(entity);
            }
        }
예제 #2
0
        //获取用户相关信息
        public ActionResult WeixinPayAttention(string json)
        {
            UniversalResponse resp = new UniversalResponse();
            DbDataController  mDbDataController = new DbDataController();
            DataTable         mDataTable;
            int status;

            resp.obj = null;
            try
            {
                WeixinUserInfo info = new WeixinUserInfo();

                info = (WeixinUserInfo)StaticJson.JsonToObject(json, info);
                if (info == null || info.openid == null)
                {
                    resp.rel = 0;
                    resp.msg = "无效的数据";
                }
                else
                {
                    mDataTable = mDbDataController.GetWeixinUser(info.openid);
                    if (mDataTable != null && mDataTable.Rows.Count > 0) //已经存在
                    {
                        status = mDbDataController.UpdateWeixinUser(info);
                    }
                    else
                    {
                        status = mDbDataController.AddWeixinUser(info);
                    }
                    if (status <= 0)
                    {
                        resp.rel = 0;
                        resp.msg = "添加数据到数据库失败";
                    }
                    else
                    {
                        resp.rel = 1;
                        resp.msg = "添加/修改成功";
                    }
                }

                return(Json(resp));
            }
            catch (Exception e)
            {
                SystemLog.Write(e.StackTrace + e.Message);  //日志

                resp.rel = 0;
                resp.msg = "发生了异常," + e.Message;
                return(Json(resp));
            }
        }
예제 #3
0
        // GET: WX
        public ActionResult OAuthCallback()
        {
            string code  = Request["code"];
            string appId = Request["appid"]; //授权给开放平台时返回此参数 默认授权无此参数
            string state = Request["state"]; //state 原样返回

            string pageUrl           = HttpUtility.UrlDecode(state);
            string appSecret         = "";
            string getAccessTokenUrl = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",
                                                     appId,
                                                     appSecret,
                                                     code);
            string             accessTokenSource = RequestUtil.Get(getAccessTokenUrl);
            WXOAuthAccessToken accessTokenModel  = JsonConvert.DeserializeObject <WXOAuthAccessToken>(accessTokenSource);

            ht_user user = BLLUser.GetUserByOpenid(accessTokenModel.openid);

            if (user != null)
            {
                BLLAuthentication.LoginAuthenticationTicket(user);
                return(Redirect(pageUrl));
            }
            else
            {
                user             = new ht_user();
                user.addtime     = DateTime.Now;
                user.parent_id   = 0;
                user.points      = 0;
                user.money       = 0;
                user.issubscribe = 0;
                user.salt        = Utils.GetCheckCode(6); //获得6位的salt加密字符串
                user.password    = EncryptUtil.DesEncrypt("123456", user.salt);
            }
            string wxUserInfoSourceJson = RequestUtil.Get(string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}",
                                                                        accessTokenModel.access_token,
                                                                        accessTokenModel.openid
                                                                        ));
            WeixinUserInfo wxUserInfo = JsonConvert.DeserializeObject <WeixinUserInfo>(wxUserInfoSourceJson);

            user.username = user.openid;
            user.openid   = wxUserInfo.openid;
            user.nickname = wxUserInfo.nickname;
            user.avatar   = wxUserInfo.headimgurl;
            if (BLLUser.AddUser(user) > 0)
            {
                BLLAuthentication.LoginAuthenticationTicket(user);
            }
            return(Redirect(pageUrl));
        }
예제 #4
0
        /// <summary>
        /// 用户授权回调
        /// </summary>
        /// <returns></returns>
        public ActionResult OAuthCallback()
        {
            string code  = Request["code"];
            string appId = Request["appid"]; //授权给开放平台时返回此参数 默认授权无此参数
            string state = Request["state"]; //state 原样返回

            string pageUrl = HttpUtility.UrlDecode(state);

            string appSecret         = "";
            string getAccessTokenUrl = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",
                                                     appId,
                                                     appSecret,
                                                     code);
            string             accessTokenSource = RequestUtil.Get(getAccessTokenUrl);
            WXOAuthAccessToken accessTokenModel  = JsonConvert.DeserializeObject <WXOAuthAccessToken>(accessTokenSource);

            ht_user user = BLLUser.GetUserByOpenid(accessTokenModel.openid);

            if (user != null)
            {
                BLLAuthentication.LoginAuthenticationTicket(user);
                return(Redirect(pageUrl));
            }
            string wxUserInfoSourceJson = RequestUtil.Get(string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}",
                                                                        accessTokenModel.access_token,
                                                                        accessTokenModel.openid
                                                                        ));
            WeixinUserInfo wxUserInfo = JsonConvert.DeserializeObject <WeixinUserInfo>(wxUserInfoSourceJson);

            user          = new ht_user();
            user.nickname = wxUserInfo.nickname;
            user.avatar   = wxUserInfo.headimgurl;
            user.username = accessTokenModel.openid;
            user.openid   = accessTokenModel.openid;
            string prms  = pageUrl.Substring(pageUrl.IndexOf("?") + 1);
            var    qList = HttpUtility.ParseQueryString(prms);
            var    pid   = qList.Get("pid");

            if (pid != null)
            {
                user.parent_id = Convert.ToInt32(pid);
            }
            BLLAuthentication.LoginAuthenticationTicket(user);
            return(Redirect(pageUrl));
        }
예제 #5
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string         openid      = context.Request["newweixinOpenID"];
            WeixinUserInfo model       = RedisManage.Int.GetUserInfo(openid);
            string         handurl     = string.Format("/Photo/{0}.jpg", openid);
            string         handurlPaht = context.Server.MapPath("~" + handurl);

            if (model != null && !model.headimgurl.IsNull())
            {
                if (File.Exists(handurlPaht))
                {
                    context.Response.Write(handurl);
                    return;
                }
                Image _image = HttpUtils.Ins.DownPic(model.headimgurl);
                _image.Save(handurlPaht);
                return;
            }
            context.Response.Write(handurl);
        }
예제 #6
0
        public async Task <WeixinUserInfo> GetUserInfoAsync(string code)
        {
            var userInfo = new WeixinUserInfo();

            var pair = await GetAccessTokenAndOpenIdAsync(code);

            var url    = $"https://api.weixin.qq.com/sns/userinfo?access_token={pair.Key}&openid={pair.Value}";
            var result = await LoginManager.GetStringAsync(url);

            if (result.Contains("errmsg"))
            {
                throw new Exception(result);
            }

            var data = JObject.Parse(result);

            userInfo.Nickname   = data["nickname"].Value <string>();
            userInfo.HeadImgUrl = data["headimgurl"].Value <string>();
            userInfo.UnionId    = data["unionid"].Value <string>();

            return(userInfo);
        }
        /// <summary>
        /// 微信授权回调
        /// add by fruitchan
        /// 2017-2-16 09:33:02
        /// </summary>
        /// <param name="code">Code</param>
        /// <returns>Redirect</returns>
        public ActionResult RedirectUri(string code)
        {
            if (!String.IsNullOrEmpty(code))
            {
                //APPID&secret=SECRET&code=CODE&grant_type=authorization_code");

                StringBuilder strUrl = new StringBuilder();
                strUrl.Append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
                strUrl.Append(appid);
                strUrl.Append("&secret=");
                strUrl.Append(appSecret);
                strUrl.Append("&code=");
                strUrl.Append(code);
                strUrl.Append("&grant_type=authorization_code");

                string jsonAccessToken = HttpHelper.RequestURL(strUrl.ToString(), null, "GET");

                if (!String.IsNullOrEmpty(jsonAccessToken))
                {
                    AccessToken token = JsonConvert.DeserializeObject <AccessToken>(jsonAccessToken);

                    if (token != null && !String.IsNullOrEmpty(token.access_token) && !String.IsNullOrEmpty(token.openid))
                    {
                        // 通过Token获取用户信息
                        string url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token.access_token + "&openid=" + token.openid;

                        string jsonUserInfo = HttpHelper.RequestURL(url, null, "GET");

                        if (!String.IsNullOrEmpty(jsonUserInfo))
                        {
                            WeixinUserInfo weixinUserInfo = JsonConvert.DeserializeObject <WeixinUserInfo>(jsonUserInfo);

                            if (weixinUserInfo != null && !String.IsNullOrEmpty(weixinUserInfo.unionid))
                            {
                                Session["OpenID"] = weixinUserInfo.openid;
                                OperateContext.Current.UserLogin(new UserInfoView()
                                {
                                    Gender        = weixinUserInfo.sex,
                                    Img           = weixinUserInfo.headimgurl,
                                    Nikename      = weixinUserInfo.nickname,
                                    Username      = weixinUserInfo.nickname,
                                    WeixinUnionid = weixinUserInfo.unionid
                                }, 2, true);
                            }
                            else
                            {
                                return(Content("登录失败:解析微信用户信息失败!" + jsonUserInfo));
                            }
                        }
                        else
                        {
                            return(Content("登录失败:获取微信用户信息失败!"));
                        }
                    }
                    else
                    {
                        return(Content("登录失败:解析Token失败!" + jsonAccessToken));
                    }
                }
                else
                {
                    return(Content("登录失败:获取微信Token失败!"));
                }

                return(Redirect("/weixin/wemain"));
            }

            return(Content("微信授权失败,请重新授权登录!"));
        }
예제 #8
0
        /// <summary>
        /// 微信登录
        /// add by fruitchan
        /// 2017-1-4 20:33:56
        /// </summary>
        /// <param name="code">code</param>
        /// <param name="code">state</param>
        /// <returns>Redirect</returns>
        public ActionResult DoWeixinLogin(string code, string state)
        {
            string appId = ConfigurationHelper.AppSetting("WeixinAppID");

            if (!String.IsNullOrEmpty(code) && !String.IsNullOrEmpty(state))
            {
                // 校验state
                if (Session["State"] == null || Session["State"].ToString() != state)
                {
                    return(Content("登录失败!"));
                }

                Session["State"] = null;

                // 通过code获取access_token
                string appSecret = ConfigurationHelper.AppSetting("WeixinAppSecret");

                StringBuilder strUrl = new StringBuilder();
                strUrl.Append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
                strUrl.Append(appId);
                strUrl.Append("&secret=");
                strUrl.Append(appSecret);
                strUrl.Append("&code=");
                strUrl.Append(code);
                strUrl.Append("&grant_type=authorization_code");

                string jsonAccessToken = HttpHelper.RequestURL(strUrl.ToString(), null, "GET");

                if (!String.IsNullOrEmpty(jsonAccessToken))
                {
                    AccessToken token = JsonConvert.DeserializeObject <AccessToken>(jsonAccessToken);

                    if (token != null && !String.IsNullOrEmpty(token.access_token) && !String.IsNullOrEmpty(token.openid))
                    {
                        // 通过Token获取用户信息
                        string url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token.access_token + "&openid=" + token.openid;

                        string jsonUserInfo = HttpHelper.RequestURL(url, null, "GET");

                        if (!String.IsNullOrEmpty(jsonUserInfo))
                        {
                            WeixinUserInfo weixinUserInfo = JsonConvert.DeserializeObject <WeixinUserInfo>(jsonUserInfo);

                            if (weixinUserInfo != null && !String.IsNullOrEmpty(weixinUserInfo.unionid))
                            {
                                OperateContext.Current.UserLogin(new UserInfoView()
                                {
                                    Gender        = weixinUserInfo.sex,
                                    Img           = weixinUserInfo.headimgurl,
                                    Nikename      = weixinUserInfo.nickname,
                                    Username      = weixinUserInfo.nickname,
                                    WeixinUnionid = weixinUserInfo.unionid
                                }, 2, true);
                            }
                            else
                            {
                                return(Content("登录失败:解析微信用户信息失败!" + jsonUserInfo));
                            }
                        }
                        else
                        {
                            return(Content("登录失败:获取微信用户信息失败!"));
                        }
                    }
                    else
                    {
                        return(Content("登录失败:解析Token失败!" + jsonAccessToken));
                    }
                }
                else
                {
                    return(Content("登录失败:获取微信Token失败!"));
                }

                return(Redirect("/Home/Index"));
            }
            else
            {
                // https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

                string redirectUri = HttpUtility.UrlEncode(ConfigurationHelper.AppSetting("RedirectUri"));
                string strState    = Guid.NewGuid().ToString().Replace("-", "");
                Session["State"] = strState;

                StringBuilder sbUrl = new StringBuilder();
                sbUrl.Append("https://open.weixin.qq.com/connect/qrconnect?appid=");
                sbUrl.Append(appId);
                sbUrl.Append("&redirect_uri=");
                sbUrl.Append(redirectUri);
                sbUrl.Append("&response_type=code&scope=snsapi_login");
                sbUrl.Append("&state=");
                sbUrl.Append(strState);
                sbUrl.Append("#wechat_redirect");

                return(Redirect(sbUrl.ToString()));
            }
        }