예제 #1
0
        /// <summary>
        /// 获取经销商信息
        /// </summary>
        /// <param name="openid">用户openid</param>
        /// <returns></returns>
        public WechatUser GetPartnerInfo(string openid)
        {
            WechatUser wuser = WechatHelper.CheckOpenid(openid);

            wuser = WechatHelper.CheckPartner(wuser);
            return(wuser);
        }
예제 #2
0
        public WechatUser GetWeChatUserList()
        {
            WechatUser userList = new WechatUser();

            try
            {
                string result = HttpGet(string.Format(URL_FORMAT_SQTOKEN, this.appId, this.appSecret, this.code));
                Dictionary <string, object> jsonObj = result.FromJson <Dictionary <string, object> >();
                var token  = "";
                var openid = "";
                if (jsonObj.ContainsKey("access_token"))
                {
                    token = jsonObj["access_token"].ToString();
                }
                if (jsonObj.ContainsKey("openid"))
                {
                    openid = jsonObj["openid"].ToString();
                }
                result  = HttpGet(string.Format(URL_FORMAT_USERLIST, token, openid));
                jsonObj = result.FromJson <Dictionary <string, object> >();
                if (jsonObj.ContainsKey("nickname"))
                {
                    userList.Openid     = jsonObj["openid"].ToString();
                    userList.Nickname   = jsonObj["nickname"].ToString();
                    userList.Headimgurl = jsonObj["headimgurl"].ToString();
                    this._cache.SetCache(CACHE_OPENID, userList.Openid);
                    this._cache.SetCache(CACHE_NICKNAME, userList.Nickname);
                    this._cache.SetCache(CACHE_HEADIMGURL, userList.Headimgurl);
                }
            }
            catch (Exception ex)
            {
            }
            return(userList);
        }
예제 #3
0
        /// <summary>
        /// 检查用户是否注册为经销商
        /// </summary>
        /// <param name="wuser">微信用户信息</param>
        /// <returns></returns>
        public static WechatUser CheckPartner(WechatUser wuser)
        {
            var db = new ModelContext();

            wuser = db.WechatUserSet.Include("PartnerInfo").Include("UserInfo").FirstOrDefault(item => item.WechatUserId == wuser.WechatUserId);
            if (wuser == null || wuser.PartnerInfo == null || wuser.UserInfo == null)
            {
                return(null);
            }
            return(wuser);
        }
예제 #4
0
        /// <summary>
        /// 获取成员信息
        /// </summary>
        /// <param name="userId">成员UserID</param>
        /// <returns></returns>
        public static WechatUser GetUserInfo(string userId)
        {
            string     url  = string.Format("{0}?access_token={1}&userid={2}", ServiceUrl.GetUserInfo, AccessToken.Value, userId);
            WechatUser user = HttpHelper.Get <WechatUser>(url); //Create().Get<WechatUser>(url);

            if (user.ErrorCode != 0)
            {
                throw new Exception("获取微信用户信息错误,ErrorCode:" + user.ErrorCode.ToString() + "; ErrorMessage:" + user.ErrorMessage);
            }
            return(user);
        }
예제 #5
0
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="wechatUserRequest">wechatUserRequest</param>
        /// <param name="config">config</param>
        /// <returns>关注的openid</returns>
        public static WechatUser GetWechatUser(WechatUserRequest wechatUserRequest, Config config)
        {
            string     url        = TenpayUtil.GetUserUrl(wechatUserRequest, config, false);
            var        strSendRes = HttpHelp.GetUrl(url);
            WechatUser wechatUser = JsonConvert.DeserializeObject <WechatUser>(strSendRes);

            if (wechatUser.Errcode == "40001")
            {
                string url1        = TenpayUtil.GetUserUrl(wechatUserRequest, config, true);
                var    strSendRes1 = HttpHelp.GetUrl(url1);
                wechatUser = JsonConvert.DeserializeObject <WechatUser>(strSendRes1);
            }
            return(wechatUser);
        }
        /// <summary>
        /// 关注公众号
        /// </summary>
        private void MessageHandler_OnSubscribe(object sender, RequestMessageEvent_Subscribe e)
        {
            AsyncHelper.RunSync(async() =>
            {
                try
                {
                    var user   = await _wechatUserRepository.GetAll().Where(w => w.OpenId == e.FromUserName).FirstOrDefaultAsync();
                    var wxuser = await UserApi.InfoAsync(appId, e.FromUserName);//获取微信用户信息
                    if (user == null && !string.IsNullOrEmpty(wxuser.unionid))
                    {
                        //如果小程序先授权
                        user = await _wechatUserRepository.GetAll().Where(w => w.UnionId == wxuser.unionid).FirstOrDefaultAsync();
                    }
                    if (user == null)//新增
                    {
                        WechatUser wechatUser = new WechatUser();
                        wechatUser.BindStatus = BindStatus.已关注;
                        wechatUser.BindTime   = DateTime.Now;
                        wechatUser.HeadImgUrl = wxuser.headimgurl;
                        wechatUser.Integral   = 0;//首次关注获取10积分
                        wechatUser.NickName   = wxuser.nickname;
                        wechatUser.OpenId     = wxuser.openid;
                        wechatUser.UnionId    = wxuser.unionid;
                        wechatUser.UserType   = UserType.普通会员;
                        var uid = await _wechatUserRepository.InsertAndGetIdAsync(wechatUser);
                        await CurrentUnitOfWork.SaveChangesAsync();
                    }
                    else//更新
                    {
                        user.BindStatus = BindStatus.已关注;
                        user.HeadImgUrl = wxuser.headimgurl;
                        user.NickName   = wxuser.nickname;
                        user.BindTime   = DateTime.Now;
                        user.UnionId    = wxuser.unionid;
                        if (string.IsNullOrEmpty(user.OpenId))
                        {
                            user.OpenId = wxuser.openid;
                        }

                        await _wechatUserRepository.UpdateAsync(user);
                        await CurrentUnitOfWork.SaveChangesAsync();
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("关注公众号绑定用户异常:{0}", ex);
                }
            });
        }
예제 #7
0
        /// <summary>
        /// 获取用户信息(确保数据库中以及存在包含openid的user记录!)
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        static public WechatUser GetUserInfo(WechatUser user)
        {
            var db = new ModelContext();

            var    nUser  = db.WechatUserSet.Find(user.WechatUserId);
            string url    = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN";
            var    access = GetToken(AccountType.Service);

            url = string.Format(url, access, user.OpenId);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);

            req.Timeout = 2000;
            req.Method  = "GET";

            var res       = (HttpWebResponse)req.GetResponse();
            var s         = res.GetResponseStream();
            var sr        = new StreamReader(s);
            var resString = sr.ReadToEnd();

            JavaScriptSerializer js = new JavaScriptSerializer();
            var dic = js.Deserialize <Dictionary <string, string> >(resString);

            if (dic.Keys.Contains("errcode"))
            {
                return(null);
            }

            user.subscribe     = (dic["subscribe"] == "1");
            user.NickName      = dic["nickname"];
            user.Sex           = dic["sex"] == "1" ? Sex.Man : dic["sex"] == "2" ? Sex.Female : Sex.Unknown;
            user.City          = dic["city"];
            user.Country       = dic["country"];
            user.Province      = dic["province"];
            user.Language      = dic["language"];
            user.Headimgurl    = dic["headimgurl"];
            user.SubscribeTime = UnixTimestampToDateTime(long.Parse(dic["subscribe_time"]));

            nUser.NickName      = dic["nickname"];
            nUser.Sex           = dic["sex"] == "1" ? Sex.Man : dic["sex"] == "2" ? Sex.Female : Sex.Unknown;
            nUser.City          = dic["city"];
            nUser.Country       = dic["country"];
            nUser.Province      = dic["province"];
            nUser.Language      = dic["language"];
            nUser.Headimgurl    = dic["headimgurl"];
            nUser.SubscribeTime = UnixTimestampToDateTime(long.Parse(dic["subscribe_time"]));
            db.SaveChanges();

            return(user);
        }
예제 #8
0
        /// <summary>
        /// 检查用户的openid,若不存在则添加并获取用户信息。
        /// </summary>
        /// <param name="openid"></param>
        /// <returns>111</returns>
        public static WechatUser CheckOpenid(string openid)
        {
            var db   = new ModelContext();
            var user = db.WechatUserSet.Include("UserInfo").FirstOrDefault(item => item.OpenId == openid);

            if (user == null || string.IsNullOrEmpty(user.OpenId))
            {
                user = new WechatUser {
                    OpenId = openid
                };
                db.WechatUserSet.Add(user);
                db.SaveChanges();
                WechatHelper.GetUserInfo(user);
            }

            return(user);
        }
예제 #9
0
        public void ProcessRequest(HttpContext context)
        {
            WechatUser wachatuser = new WechatUser();

            wachatuser.Name       = "test";
            wachatuser.UserID     = "test001";
            wachatuser.Mobile     = "13800138001";
            wachatuser.Email      = "*****@*****.**";
            wachatuser.Department = new List <int> {
                1
            };
            wachatuser.Gender   = "0";
            wachatuser.Position = "测试账号";
            wachatuser.WeixinID = "";

            var ret = Wechat4net.QY.ContactManager.CreateUser(wachatuser);

            context.Response.ContentType = "text/plain";
            context.Response.Write(ret.ErrorCode + " || " + ret.ErrorMessage);
        }
예제 #10
0
        public void getUserInfo(string code, string appId)
        {
            /*
             * 此接口通常用于从微信企业号跳转至WebApp后获取当前用户身份。
             * code:通过微信重定向跳转后获取到的身份标识
             * appId:应用id
             *
             * code参数获取方法可参考下面链接:
             * http://qydev.weixin.qq.com/wiki/index.php?title=%E4%BC%81%E4%B8%9A%E8%8E%B7%E5%8F%96code
             */

            try
            {
                WechatUser user = UserProvider.GetUserInfo(code);
            }
            catch (Exception ex)//ex.Message 异常信息
            {
                //todo...
                //...
            }
        }
예제 #11
0
        public static Wechat4net.MP.Define.WechatUser GetUserInfo(string code)
        {
            WebAccessTokenReturnValue ret = GetWebAccessToken(code);
            //var data = new
            //{
            //    access_token = ret.WebAccessToken,
            //    openid = ret.OpenID,
            //    lang = WechatConfig.Language.ToString() //Wechat4net.MP.Wechat.Options.Language.ToString()
            //};

            Dictionary <string, object> data = new Dictionary <string, object>();

            data.Add("access_token", ret.WebAccessToken);
            data.Add("openid", ret.OpenID);
            data.Add("lang", WechatConfig.Language.ToString());

            WechatUser user = HttpHelper.Get <WechatUser>(ServiceUrl.GetWebUserInfo, data);

            if (user.ErrorCode != 0)
            {
                throw new Exception("获取微信用户信息错误,ErrorCode:" + user.ErrorCode.ToString() + "; ErrorMessage:" + user.ErrorMessage);
            }
            return(user);
        }
예제 #12
0
        /// <summary>
        /// 更新成员信息
        /// </summary>
        /// <param name="user">成员对象</param>
        /// <returns></returns>
        public static ReturnValue UpdateUserInfo(WechatUser user)
        {
            string url = string.Format("{0}?access_token={1}", ServiceUrl.UpdateUserInfo, AccessToken.Value);

            //{
            //   "userid": "zhangsan",
            //   "name": "李四",
            //   "department": [1],
            //   "position": "后台工程师",
            //   "mobile": "15913215421",
            //   "gender": "1",
            //   "email": "*****@*****.**",
            //   "weixinid": "lisifordev",
            //   "enable": 1,
            //   "avatar_mediaid": "2-G6nrLmr5EC3MNb_-zL1dDdzkd0p7cNliYu9V5w7o8K0",
            //   "extattr": {"attrs":[{"name":"爱好","value":"旅游"},{"name":"卡号","value":"1234567234"}]}
            //}

            List <Dictionary <string, string> > attrs = new List <Dictionary <string, string> >();

            if (user.ExtAttr != null && user.ExtAttr.Attrs != null)
            {
                foreach (var item in user.ExtAttr.Attrs)
                {
                    Dictionary <string, string> attrsItem = new Dictionary <string, string>();
                    attrsItem.Add("name", item.Name);
                    attrsItem.Add("value", item.Value);
                    attrs.Add(attrsItem);
                }
            }

            var data = new
            {
                userid         = user.UserID,
                name           = user.Name,
                department     = user.Department.ToArray(),
                position       = user.Position,
                mobile         = user.Mobile,
                gender         = user.Gender,
                email          = user.Email,
                weixinid       = user.WeixinID,
                avatar_mediaid = user.AvatarMediaID,
                extattr        = new
                {
                    attrs = attrs
                }
            };

            string json = JsonConvert.SerializeObject(data);

            if (AppSettings.IsDebug)
            {
                //DebugLog
                Logger.Info("[UpdateUserInfo] Json = " + json);
            }

            //var Post = CreatePost(url);
            //Post.AddText(json);

            //byte[] rs = Post.Send();
            //string result = System.Text.Encoding.UTF8.GetString(rs);

            string result = HttpHelper.Post(url, json);

            if (AppSettings.IsDebug)
            {
                //DebugLog
                Logger.Info("[UpdateUserInfo] result = " + result);
            }

            return(JsonConvert.DeserializeObject <ReturnValue>(result));
        }