public static AccountSession UpdateAccountAndSession(UserInfoJson u, bool?isAttend = null)
        {
            using (BaseDBContext db = new BaseDBContext())
            {
                var wa = db.WxAccount.FirstOrDefault(d => d.openid == u.openid);
                if (wa != null)
                {
                    if (isAttend == null)
                    {
                        isAttend = false;
                    }
                }
                else
                {
                    if (isAttend == null)
                    {
                        isAttend = wa.subscribe;
                    }
                }
                wa = WxDBUpdateAccount(u, db, isAttend.Value);

                wa.lastDate = DateTime.Now;
                db.SaveChanges();

                Student s = db.Student.Find(wa.studentId);

                var a = AccountHelper.CreateAccountSession(wa, s);
                AccountHelper.SetSession(a);

                //debug.log("UpdateAccountAndSession_最终AccountSession", a);
                return(a);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// 订阅(关注)事件
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            var accessToken = AccessTokenContainer.TryGetAccessToken(AppId, AppSecret);


            var responseMessage = ResponseMessageBase.CreateFromRequestMessage <ResponseMessageText>(requestMessage);

            string result = string.Format("欢迎关注唐门年华公众号!");


            //            string redirectUrl = AgentUrl + "/WeiXin/OAuth";
            //            string oAuthUrl = OAuthApi.GetAuthorizeUrl(AppId,
            //                     redirectUrl,
            //                      "123", OAuthScope.snsapi_base);


            UserInfoJson userInfo = UserApi.Info(accessToken, requestMessage.FromUserName);

            int isOk = SaveUser(userInfo);

            Log.Debug("订阅事件,保存用户", isOk > 0 ? requestMessage.FromUserName + "保存成功" : "保存失败", null);

            responseMessage.Content = result;

            if (!string.IsNullOrEmpty(requestMessage.EventKey))
            {
                responseMessage.Content += "\r\n============\r\n场景值:" + requestMessage.EventKey;
            }

            return(responseMessage);
        }
Esempio n. 3
0
        public Account CreateOrUpdateByUserInfo(UserInfoJson userInfo, Account account = null)
        {
            var    time     = DateTime.Now;
            string userName = GetNewUserName();

            if (account == null)
            {
                account = CreateAccount(userName, "", "", "", userInfo.openid);
            }

            account.NickName = userInfo.nickname;

            var defaultHeadimgUrl = "/{0}/Content/Images/userinfonopic.png".With(SiteConfig.DomainName);

            if (userInfo.headimgurl.IsNullOrEmpty())
            {
                account.HeadImgUrl = defaultHeadimgUrl;
                account.PicUrl     = defaultHeadimgUrl;
            }
            else
            {
                account.HeadImgUrl = userInfo.headimgurl;

                var fileName = @"/Upload/Account/headimgurl.{0}.jpg".With(DateTime.Now.Ticks + Guid.NewGuid().ToString("n").Substring(0, 8));

                //下载图片
                DownLoadPic(userInfo.headimgurl, fileName);

                account.PicUrl = fileName;
            }

            SaveObject(account);
            return(account);
        }
        public static void CreateUserInfo(string openid)
        {
            var          result   = WeiXinApi.GetToken();
            UserInfoJson userinfo = UserApi.Info(result, openid);

            if (DbSession.Default.Count <tb_User>(tb_User._.OpenId == userinfo.openid) == 0)
            {
                tb_User userEntity = new tb_User()
                {
                    OpenId     = userinfo.openid,
                    NickName   = userinfo.nickname,
                    HeadImgUrl = userinfo.headimgurl,
                    Name       = "",
                    Sex        = userinfo.sex,
                    Moblie     = "",
                    State      = 1,
                    Integral   = 0,
                    IsDealer   = false,
                    CreateTime = DateTime.Now,
                    ExpDate    = null
                };
                DbSession.Default.Insert <tb_User>(userEntity);
            }
            else
            {
                tb_User userEntity = DbSession.Default.From <tb_User>().Where(tb_User._.OpenId == userinfo.openid).ToFirst();
                userEntity.Attach();
                userEntity.NickName   = userinfo.nickname;
                userEntity.HeadImgUrl = userinfo.headimgurl;
                DbSession.Default.Update <tb_User>(userEntity);
            }
        }
Esempio n. 5
0
        public static int SaveUser(UserInfoJson userInfoJson)
        {
            using (weixin_gzhEntities db = new weixin_gzhEntities())
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < userInfoJson.tagid_list.Length; i++)
                {
                    sb.Append(userInfoJson.tagid_list[i] + ",");
                }

                UserInfoJson    userInfo = userInfoJson;
                weixin_userinfo user     = new weixin_userinfo();
                user.subscribe       = userInfo.subscribe;
                user.openid          = userInfo.openid;
                user.nickname        = userInfo.nickname;
                user.sex             = userInfo.sex;
                user.language        = userInfo.language;
                user.city            = userInfo.city;
                user.province        = userInfo.province;
                user.country         = userInfo.country;
                user.headimgurl      = userInfo.headimgurl;
                user.subscribe_time  = DateTime.Now;
                user.unionid         = userInfo.unionid;
                user.remark          = userInfo.remark;
                user.groupid         = userInfo.groupid;
                user.tagid_list      = sb.ToString();
                user.subscribe_scene = userInfo.subscribe_scene;
                user.qr_scene        = userInfo.qr_scene;
                user.qr_scene_str    = userInfo.qr_scene_str;
                db.weixin_userinfo.Add(user);
                int isOk = db.SaveChanges();
                return(isOk);
            }
        }
Esempio n. 6
0
        private UserInfoJson GetWXUserHead(string openid)
        {
            SiteSettingsInfo siteSettings = Instance <ISiteSettingService> .Create.GetSiteSettings();

            if (string.IsNullOrEmpty(siteSettings.WeixinAppId) && string.IsNullOrEmpty(siteSettings.WeixinAppSecret))
            {
                throw new Exception("未配置公众号");
            }
            //string str = AccessTokenContainer.TryGetToken(siteSettings.WeixinAppId, siteSettings.WeixinAppSecret, false);
            string str = CommonApi.GetToken(siteSettings.WeixinAppId, siteSettings.WeixinAppSecret).access_token;
            //
            //UserInfoJson userInfoJson = UserApi.Info(str, openid, Language.zh_CN);
            var userInfoJson = CommonApi.GetUserInfo(str, openid);

            if (userInfoJson.errcode != ReturnCode.请求成功)
            {
                throw new HimallException(userInfoJson.errmsg);
            }

            UserInfoJson json = new UserInfoJson();

            json.FillEntityWithXml(userInfoJson.ConvertEntityToXml <Senparc.Weixin.MP.Entities.WeixinUserInfoResult>());

            return(json);
        }
Esempio n. 7
0
        public MpUser UpdateUserInfo(string OpenId, string token)
        {
            MpUser currUser = this.GetByOpenID(OpenId);

            if (currUser != null && currUser.IsSubscribe)
            {
                if (!string.IsNullOrEmpty(token))
                {
                    try
                    {
                        UserInfoJson info = Senparc.Weixin.MP.AdvancedAPIs.User.Info(token, OpenId);
                        if (info != null)
                        {
                            currUser.City       = info.city;
                            currUser.Country    = info.country;
                            currUser.HeadImgUrl = info.headimgurl;
                            currUser.Language   = info.language;
                            currUser.NickName   = info.nickname;
                            currUser.Province   = info.province;
                            currUser.Sex        = info.sex;
                            this.Update(currUser);
                        }
                    }
                    catch (Exception e)
                    {
                        Log4NetImpl.Write("UpdateUserInfo失败:" + e.Message);
                    }
                }
            }
            return(currUser);
        }
Esempio n. 8
0
        /// <summary>
        ///通知设置
        /// </summary>
        /// <param name="aId"></param>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public ActionResult NoticeSetting(int aId = 0, int storeId = 0)
        {
            if (aId <= 0 || storeId <= 0)
            {
                return(Content("参数错误"));
            }
            string   appId    = Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppId;//公众号appid
            PinStore pinStore = (PinStore)Request.RequestContext.RouteData.Values["pinStore"];

            if (pinStore == null)
            {
                return(Content("信息错误,请重新登录"));
            }
            UserInfoJson userInfo = null;

            if (!string.IsNullOrEmpty(pinStore.wxOpenId))
            {
                userInfo = UserApi.Info(appId, pinStore.wxOpenId, Language.zh_CN);
            }
            string sessonid = new Random().Next(1, 3) + DateTime.Now.ToString("mmssfffff");

            Session["wxbindqrcodekey"] = sessonid;
            if (null == RedisUtil.Get <ScanModel>("wxbindSessionID:" + sessonid))
            {
                ScanModel model = new ScanModel();
                RedisUtil.Set <ScanModel>("wxbindSessionID:" + sessonid, model, TimeSpan.FromDays(1));
            }
            ViewBag.StoreId = storeId;
            return(View(userInfo));
        }
 /// <summary>
 /// Initializes a <see cref="WeChatAuthenticatedContext"/>
 /// </summary>
 /// <param name="context">The OWIN environment</param>
 /// <param name="user">The JSON-serialized user</param>
 /// <param name="accessToken">WeChat Access token</param>
 /// <param name="expires">Seconds until expiration</param>
 public WeChatAuthenticatedContext(IOwinContext context, UserInfoJson userInfo,
                                   OAuthUserInfo oauthUserInfo, string accessToken, int expiresIn)
     : base(context)
 {
     UserInfo      = userInfo;
     OAuthUserInfo = oauthUserInfo;
     AccessToken   = accessToken;
     ExpiresIn     = TimeSpan.FromSeconds(expiresIn);
 }
Esempio n. 10
0
        public async Task <User> CreateUserWhenSubscribeAsync(int tenantId, UserInfoJson UserInfoJson)
        {
            string userName = UserInfoJson.openid;

            userName = User.PreProcessUserName(userName);
            var user = new User
            {
                UserName = userName,
                TenantId = tenantId,
                Name     = "Weixin",
                Surname  = UserInfoJson.openid,
                NickName = UserInfoJson.nickname,
                Avatar   = UserInfoJson.headimgurl,
                Source   = UserSource.WeixinInteraction,
                IsActive = true
            };

            user.Logins = new List <UserLogin>
            {
                new UserLogin
                {
                    TenantId      = tenantId,
                    LoginProvider = "Weixin",
                    ProviderKey   = UserInfoJson.openid
                }
            };
            string password = User.DefaultPassword;

            user.Password = new Microsoft.AspNet.Identity.PasswordHasher().HashPassword(password);

            //Switch to the tenant
            CurrentUnitOfWork.SetTenantId(tenantId);

            //Add default roles
            user.Roles = new List <UserRole>();

            foreach (var defaultRole in RoleManager.Roles.Where(r => r.IsDefault).ToList())
            {
                user.Roles.Add(new UserRole {
                    RoleId = defaultRole.Id
                });
            }

            //Save user
            await _userManager.CreateAsync(user);

            unitOfWorkManager.Current.SaveChanges();

            //Notifications
            await _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(user.ToUserIdentifier());

            await _appNotifier.WelcomeToTheApplicationAsync(user);

            await _appNotifier.NewUserRegisteredAsync(user);

            return(user);
        }
Esempio n. 11
0
        public async Task <User> UpdateUser(int tenantId, UserInfoJson userInfoJson)
        {
            using (CurrentUnitOfWork.SetTenantId(tenantId))
            {
                User user = GetUserFromOpenId(tenantId, userInfoJson.openid);
                user.Avatar   = userInfoJson.headimgurl;
                user.NickName = userInfoJson.nickname;
                await UserRepository.UpdateAsync(user);

                return(user);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// 直接更新本地数据库中账号
        /// </summary>
        public static WX_User GetUserInfoByOpenidWithUpdateLocal(string openid, OAuthAccessTokenResult _accresstoken, string _code)
        {
            UserInfoJson u      = GetUserInfoByOpenid(openid);
            WX_User      wxuser = new WX_User();

            if (u != null && u.errmsg == null)//有用户信息返回
            {
                wxuser = new WX_UserB().GetEntity(d => d.Openid == u.openid);
                return(UpdateLocalUserInfo(u, _accresstoken, _code));
            }
            return(wxuser);
        }
        /// <summary>
        /// 添加粉丝到数据库
        /// </summary>
        /// <param name="mpid"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        private async Task <MpFanDto> AddFan(int mpid, string openid)
        {
            var account = await _mpAccountAppService.GetCache(mpid);

            if (account == null)
            {
                return(null);
            }
            try
            {
                UserInfoJson wxinfo = null;
                try
                {
                    wxinfo = UserApi.Info(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret), openid);
                }
                catch
                {
                    Logger.Error(string.Format("获取MpID为{0},openid为{1}的用户信息报错", mpid, openid));
                    wxinfo = UserApi.Info(await _accessTokenContainer.TryGetAccessTokenAsync(account.AppId, account.AppSecret, true), openid);
                }
                if (wxinfo.errcode != ReturnCode.请求成功)
                {
                    throw new Exception(string.Format("获取MpID为{0},openid为{1}的用户信息报错,错误编号:{2},错误消息:{3}", mpid, openid, wxinfo.errcode, wxinfo.errmsg));
                }

                var entityfans = new MpFanDto();
                entityfans.City               = wxinfo.city;
                entityfans.Country            = wxinfo.country;
                entityfans.HeadImgUrl         = wxinfo.headimgurl;
                entityfans.IsFans             = true;
                entityfans.Language           = wxinfo.language;
                entityfans.MpID               = mpid;
                entityfans.NickName           = wxinfo.nickname;
                entityfans.OpenID             = wxinfo.openid;
                entityfans.Province           = wxinfo.province;
                entityfans.Remark             = wxinfo.remark;
                entityfans.Sex                = wxinfo.sex.ToString();
                entityfans.SubscribeTime      = DateTimeHelper.GetDateTimeFromXml(wxinfo.subscribe_time);
                entityfans.UnionID            = wxinfo.unionid;
                entityfans.WxGroupID          = wxinfo.groupid;
                entityfans.UpdateTime         = DateTime.Now;
                entityfans.FirstSubscribeTime = DateTime.Now;
                entityfans.ChannelID          = 0;
                entityfans.ChannelName        = "公众号";
                return(await _mpFanAppService.Create(entityfans));
            }
            catch (Exception ex)
            {
                Logger.Error(string.Format("粉丝订阅更新数据库失败,原因:{0}", ex.Message));
            }
            return(null);
        }
Esempio n. 14
0
        public async Task RefreshWeixinUserInfo(long userId)
        {
            User   user   = UserRepository.Get(userId);
            string openid = GetOpenid(user.ToUserIdentifier());

            string accessToken = await WechatCommonManager.GetAccessTokenAsync();

            UserInfoJson userInfoJson = UserApi.Info(accessToken, openid);

            user.Avatar   = userInfoJson.headimgurl;
            user.NickName = userInfoJson.nickname;
            UserRepository.Update(user);
        }
Esempio n. 15
0
        private bool IsAttentionByRPC(string openId)
        {
            UserInfoJson userInfoJson = UserApi.Info(_accessToken, openId, Language.zh_CN);

            if (userInfoJson.errcode == ReturnCode.合法的OpenID || userInfoJson.subscribe == 0)
            {
                return(false);
            }
            if (userInfoJson.errcode != ReturnCode.请求成功)
            {
                throw new Exception(userInfoJson.errmsg);
            }
            return(userInfoJson.subscribe == 1);
        }
        public static BoolAny <WxAccount> WxDBUpdateAccount(UserInfoJson userinfo, BaseDBContext wdb, bool isAttend)
        {
            try
            {
                WxAccount newWa = wdb.WxAccount.Find(userinfo.openid);

                if (newWa == null)
                {
                    newWa = new WxAccount()
                    {
                        subscribe = isAttend,
                        regDate   = DateTime.Now,
                        //subscribe_time = LIB.DateTimeEx.TimeStampToDateTime(userinfo.subscribe_time),
                        subscribe_time = DateTime.Now,
                        openid         = userinfo.openid,
                        lastDate       = DateTime.Now,
                        headimgurl     = userinfo.headimgurl,
                        nickname       = userinfo.nickname,
                        sex            = userinfo.sex.ToString(),
                        groupid        = userinfo.groupid.ToString(),
                        remark         = userinfo.remark,
                        unionid        = userinfo.unionid,
                        studentId      = 0
                    };
                    wdb.WxAccount.Add(newWa);
                }
                else
                {
                    newWa.subscribe = isAttend;

                    newWa.headimgurl = userinfo.headimgurl;
                    newWa.nickname   = userinfo.nickname;
                    newWa.sex        = userinfo.sex.ToString();
                    newWa.groupid    = userinfo.groupid.ToString();
                    newWa.remark     = userinfo.remark;
                }


                wdb.SaveChanges();
                //debug.log("WxDBUpdateAccount_DBSave", newWa);
                return(BoolAny <WxAccount> .succeed(newWa));
            }
            catch (DbEntityValidationException dbEx)
            {
                debug.log("WxDBUpdateAccount_DBSave_异常", dbEx.Message);
                //debug.print("addAccount_error", e.Message);
                return(BoolAny <WxAccount> .fail(dbEx.Message));
            }
        }
Esempio n. 17
0
        public long SaveUserInfo(OAuthUserInfo weixinUser, UserInfoJson fensi = null)
        {
            wp_user userModel = new wp_user();

            int useId = 0;

            if (weixinUser != null)
            {
                useId = GetUserIdByOpenId(weixinUser.openid);
            }
            if (useId == 0 && fensi != null)
            {
                useId = GetUserIdByOpenId(fensi.openid);
            }
            if (useId == 0)
            {
                if (fensi == null)
                {
                    userModel.city       = weixinUser.city;
                    userModel.country    = weixinUser.country;
                    userModel.headimgurl = weixinUser.headimgurl;
                    userModel.nickname   = weixinUser.nickname;
                    userModel.openid     = weixinUser.openid;
                    userModel.province   = weixinUser.province;
                    userModel.sex        = (sbyte)weixinUser.sex;
                    userModel.unionid    = weixinUser.unionid;
                    userModel.status     = 0;
                }
                else
                {
                    userModel.city       = fensi.city;
                    userModel.country    = fensi.country;
                    userModel.headimgurl = fensi.headimgurl;
                    userModel.nickname   = fensi.nickname;
                    userModel.openid     = fensi.openid;
                    userModel.province   = fensi.province;
                    userModel.sex        = (sbyte)fensi.sex;
                    userModel.unionid    = fensi.unionid;
                    userModel.status     = (sbyte)fensi.subscribe;
                }
                return(InsertItem(userModel));
            }
            else
            {
                return((long)useId);
            }
        }
Esempio n. 18
0
        public ActionResult GetUserJsonP(string mpid, string openid)
        {
            #region 校验公众号
            var account = GetAccount(mpid);
            if (account == null)
            {
                LogWriter.Info(string.Format("mpid为“{0}”的GetUser获取失败,原因:公众号不存在", mpid));
                return(Content("公众号不存在"));
            }
            var callback = Request.QueryString["callback"] ?? "";
            #endregion

            #region 获取用户信息
            var wxFO = Formula.FormulaHelper.CreateFO <WxFO>();

            UserInfoJson userinfo = null;

            try
            {
                userinfo = wxFO.GetFans(mpid, openid);
            }
            catch
            {
                try
                {
                    userinfo = wxFO.GetFans(mpid, openid, true);
                }
                catch (Exception ex)
                {
                    return(Content(string.IsNullOrEmpty(callback) ? "" : string.Format("{0}({1})", callback, new JavaScriptSerializer().Serialize(
                                                                                           new
                    {
                        errorcode = "500",
                        errormsg = ex.Message,
                    }))));
                }
            }
            #endregion

            return(Content(string.IsNullOrEmpty(callback) ? "" : string.Format("{0}({1})", callback, new JavaScriptSerializer().Serialize(
                                                                                   new
            {
                errorcode = "200",
                errormsg = "",
                result = userinfo,
            }))));
        }
        private UserInfoJson GetWXUserHead(string openid)
        {
            SiteSettingsInfo siteSettings = Instance <ISiteSettingService> .Create.GetSiteSettings();

            if (string.IsNullOrEmpty(siteSettings.WeixinAppId) && string.IsNullOrEmpty(siteSettings.WeixinAppSecret))
            {
                throw new Exception("未配置公众号");
            }
            string       str          = AccessTokenContainer.TryGetToken(siteSettings.WeixinAppId, siteSettings.WeixinAppSecret, false);
            UserInfoJson userInfoJson = UserApi.Info(str, openid, Language.zh_CN);

            if (userInfoJson.errcode != ReturnCode.请求成功)
            {
                throw new HimallException(userInfoJson.errmsg);
            }
            return(userInfoJson);
        }
 public static UserInfoJson WxGetAttendUserInfoByWxServer(string openid)
 {
     //debug.log("WxGetAttendUserInfoByWxService_开始", openid);
     try
     {
         string atc = AccessTokenContainer.TryGetAccessToken(Config.WX_AppId, Config.WX_AppSecret);
         //已关注,可以得到详细信息
         UserInfoJson userInfoJson = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(atc, openid);
         //userInfo = Senparc.Weixin.MP.AdvancedAPIs.OAuthApi.GetUserInfo(, openid);
         //debug.log("WxGetAttendUserInfoByWxServer", userInfoJson);
         return(userInfoJson);
     }
     catch (Exception e)
     {
         debug.log("WxGetAttendUserInfoByWxService_异常", e.Message);
         return(null);
     }
 }
Esempio n. 21
0
        public ActionResult GetUser(string mpid, string openid)
        {
            #region 校验公众号
            var account = GetAccount(mpid);
            if (account == null)
            {
                LogWriter.Info(string.Format("mpid为“{0}”的GetUser获取失败,原因:公众号不存在", mpid));
                return(Content("公众号不存在"));
            }
            #endregion

            #region 获取用户信息
            var wxFO = Formula.FormulaHelper.CreateFO <WxFO>();

            UserInfoJson userinfo = null;

            try
            {
                userinfo = wxFO.GetFans(mpid, openid);
            }
            catch
            {
                try
                {
                    userinfo = wxFO.GetFans(mpid, openid, true);
                }
                catch (Exception ex)
                {
                    return(Json(new
                    {
                        errorcode = "500",
                        errormsg = ex.Message,
                    }, JsonRequestBehavior.AllowGet));
                }
            }
            #endregion

            return(Json(new
            {
                errorcode = "200",
                errormsg = "",
                result = userinfo,
            }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 22
0
        private UserInfoJson GetWXUserHead(string openid)
        {
            var siteSetting = this._siteSetting;

            if (!string.IsNullOrEmpty(siteSetting.WeixinAppId) || !string.IsNullOrEmpty(siteSetting.WeixinAppSecret))
            {
                string       accessToken = AccessTokenContainer.TryGetToken(siteSetting.WeixinAppId, siteSetting.WeixinAppSecret);
                UserInfoJson user        = UserApi.Info(accessToken, openid);
                if (user.errcode == Senparc.Weixin.ReturnCode.请求成功)
                {
                    return(user);
                }
                else
                {
                    throw new HimallException(user.errmsg);
                }
            }
            throw new Exception("未配置公众号");
        }
Esempio n. 23
0
 public Rbac_User WeopenRegist(Wx_App app, UserInfoJson userInfo, string mobile = null)
 {
     return(Session.QueryFirst <Rbac_User>(
                new RequestContext("wx", "exec_wx_regist")
                .SetParam(new
     {
         newid = App.IdWorker.NextId(),
         mobile = mobile,
         nickname = userInfo.nickname,
         photo = userInfo.headimgurl,
         province = userInfo.province,
         city = userInfo.city,
         country = userInfo.country,
         appid = app.Id,
         authtype = "wechat",
         authid = userInfo.openid,
         unionid = userInfo.unionid
     })
                ));
 }
Esempio n. 24
0
 public static WechatMPUser ConvertWeChatUserToMpUser(UserInfoJson model, int AccountManageId, int iAPPID)
 {
     return(new WechatMPUser
     {
         City = model.city,
         Country = model.country,
         Province = model.province,
         GroupId = model.groupid,
         HeadImgUrl = model.headimgurl,
         Language = model.language,
         NickName = model.nickname,
         OpenId = model.openid,
         Remark = model.remark,
         Sex = model.sex,
         SubScribe = model.subscribe,
         SubScribeTime = model.subscribe_time,
         TagIdList = model.tagid_list != null?string.Join(",", model.tagid_list) : "",
                         UnionId = model.unionid,
                         AccountManageId = AccountManageId,
     });
 }
Esempio n. 25
0
        /// <summary>
        /// 订阅(关注)事件
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            AsyncHelper.RunSync(async() =>
            {
                _accessToken = await _wechatCommonManager.GetAccessTokenAsync(_tenant.Id);

                if (_user == null)
                {
                    UserInfoJson userInfo = UserApi.Info(_accessToken, RequestMessage.FromUserName);
                    _user = await _wechatUserManager.CreateUserWhenSubscribeAsync(_tenant.Id, userInfo);
                }

                if (requestMessage.EventKey.Contains("qrscene_"))
                {
                    int sceneId = int.Parse(requestMessage.EventKey.Substring(8));
                    await _wechatUserManager.ProcessSceneId(sceneId, _user.Id, _tenant.Id);
                }
            });
            SendAutoReplyMessages(RequestType.Event_SubscribeRequest);
            return(ResponseMessage);
        }
Esempio n. 26
0
        public HttpResponseMessage GetPlayerInfo(String name = "", String token = "", String rand = "")
        {
            try
            {
                // TODO - Handle token to check if lookup player is friend and/or ignored.

                Account acc = this.dataAccess.GetAccountByUsername(name);
                if (acc == null)
                {
                    return(HttpResponseFactory.Response200Json(new ErrorJson {
                        Error = ErrorMessages.ERR_NO_USER_WITH_SUCH_NAME
                    }));
                }

                return(HttpResponseFactory.Response200Json(UserInfoJson.ToUserInfoJson(acc)));
            }
            catch (Exception ex)
            {
                return(HttpResponseFactory.Response500Plain(ex.Message));
            }
        }
Esempio n. 27
0
        public ActionResult UpdateUserInfo(string ids)
        {
            string[] idsArr = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (idsArr != null && idsArr.Length > 0)
            {
                Guid[]         gids    = TypeConverter.StrsToGuids(idsArr);
                IList <MpUser> mpusers = MpUserService.GetALL(p => gids.Contains(p.Id));
                string         token   = GetAccessToken();

                if (mpusers != null && mpusers.Count > 0 && !string.IsNullOrEmpty(token))
                {
                    foreach (MpUser currUser in mpusers)
                    {
                        try
                        {
                            UserInfoJson info = Senparc.Weixin.MP.AdvancedAPIs.User.Info(token, currUser.OpenID);
                            if (info != null)
                            {
                                currUser.City          = info.city;
                                currUser.Country       = info.country;
                                currUser.HeadImgUrl    = info.headimgurl;
                                currUser.Language      = info.language;
                                currUser.NickName      = info.nickname;
                                currUser.Province      = info.province;
                                currUser.Sex           = info.sex;
                                currUser.SubscribeDate = DateTimeHelper.GetDateTimeFromXml(info.subscribe_time);
                                MpUserService.Update(currUser);
                            }
                        }
                        catch (Exception e)
                        {
                            Log4NetImpl.Write("AysnUser失败:" + e.Message);
                        }
                    }
                }
            }
            return(JsonMessage(true, "同步资料成功"));
        }
Esempio n. 28
0
 private static WxUser GetWxUser(UserInfoJson json)
 {
     return(new WxUser
     {
         Subscribe = json.subscribe,
         OpenId = json.openid,
         Nickname = json.nickname,
         Sex = json.sex,
         Language = json.language,
         City = json.city,
         Province = json.province,
         Country = json.country,
         HeadImgUrl = json.headimgurl,
         SubscribeTime = GetDateTimeWithTimeStamp(json.subscribe_time),
         UnionId = json.unionid,
         Remark = json.remark,
         GroupId = json.groupid,
         TagIdList = ListUtils.GetIntList(json.tagid_list),
         SubscribeScene = json.subscribe_scene,
         QrScene = json.qr_scene,
         QrSceneStr = json.qr_scene_str
     });
 }
        /// <summary>
        /// 获取某人信息
        /// </summary>
        /// <param name="nickname"></param>
        public static void GetUserInfo(string nickname = "棒哥")
        {
            string url = $"http://172.81.250.91:82/userInfo";
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic["nickname"] = nickname;

            string result = string.Empty;

            try
            {
                result = Common.PostPocketApi(url, JsonConvert.SerializeObject(dic));
            }
            catch (Exception ex)
            {
                File.AppendAllLines("WebClientError.log", new List <string> {
                    result, ex.StackTrace
                }, Encoding.UTF8);
            }

            if (result != string.Empty)
            {
                File.AppendAllLines("GetUserInfo.log", new List <string> {
                    result
                }, Encoding.UTF8);
                UserInfoJson json = JsonConvert.DeserializeObject <UserInfoJson>(result);
                if (json.code == 200)
                {
                    GameData.UserPickedDic[nickname] = json.data;

                    if (nickname == "棒哥")
                    {
                        GameData.SelfInfo = json.data;
                    }
                }
            }
        }
Esempio n. 30
0
        /// <summary>
        /// 更新本地数据库中微信用户信息
        /// </summary>
        public static WX_User UpdateLocalUserInfo(UserInfoJson u, OAuthAccessTokenResult _accresstoken, string _code)
        {
            string _accesstokenstr  = "";
            int    _expires_in      = 0;
            string _refreshtokenstr = "";
            string _scopestr        = "";

            if (_accresstoken != null && _accresstoken.errmsg == null)
            {
                _accesstokenstr  = _accresstoken.access_token;
                _expires_in      = _accresstoken.expires_in;
                _refreshtokenstr = _accresstoken.refresh_token;
                _scopestr        = _accresstoken.scope;
            }
            WX_User wxuser = new WX_UserB().GetEntity(d => d.Openid == u.openid);

            if (wxuser == null)
            {
                wxuser               = new WX_User();
                wxuser.Openid        = u.openid;
                wxuser.Nickname      = u.nickname;
                wxuser.Sex           = u.sex == 1 ? "男" : (u.sex == 2 ? "女" : "未知");
                wxuser.Province      = u.province;
                wxuser.City          = u.city;
                wxuser.Country       = u.country;
                wxuser.HeadImgUrl    = u.headimgurl;
                wxuser.Code          = _code;
                wxuser.Access_token  = _accesstokenstr;
                wxuser.Expires_in    = _expires_in;
                wxuser.Refresh_token = _refreshtokenstr;
                wxuser.Scope         = _scopestr;
                wxuser.CRDate        = DateTime.Now;
                wxuser.LastLoginDate = DateTime.Now;
                wxuser.AuthUserID    = 0;
                new WX_UserB().Insert(wxuser);
            }
            else
            {
                wxuser.Nickname      = u.nickname;
                wxuser.Sex           = u.sex == 1 ? "男" : (u.sex == 2 ? "女" : "未知");
                wxuser.Province      = u.province;
                wxuser.City          = u.city;
                wxuser.Country       = u.country;
                wxuser.HeadImgUrl    = u.headimgurl;
                wxuser.Code          = _code;
                wxuser.Access_token  = _accesstokenstr;
                wxuser.Expires_in    = _expires_in;
                wxuser.Refresh_token = _refreshtokenstr;
                wxuser.Scope         = _scopestr;
                wxuser.LastLoginDate = DateTime.Now;
                new WX_UserB().Update(wxuser);
            }
            return(wxuser);
            //JH_Auth_User localuser = new JH_Auth_UserB().GetEntity(d => d.WXopenid == u.openid && d.IsWX == 1);
            //if (localuser == null)
            //{
            //    localuser = new JH_Auth_User();

            //    localuser.UserName = "******" + Guid.NewGuid().ToString().Replace("-", "").Substring(0, 16);
            //    //新用户名随机生成
            //    localuser.UserRealName = u.nickname;
            //    localuser.UserPass = CommonHelp.GetMD5("a123456");
            //    localuser.pccode= EncrpytHelper.Encrypt(localuser.UserName + "@" + localuser.UserPass + "@" + DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
            //    localuser.ComId = 10334;
            //    localuser.Sex = u.sex == 1 ? "男" : (u.sex == 2 ? "女" : "未知");
            //    localuser.BranchCode = 0;
            //    localuser.CRDate = DateTime.Now;
            //    localuser.CRUser = "******";
            //    localuser.logindate = DateTime.Now;
            //    localuser.IsUse = "Y";
            //    localuser.IsWX = 1;
            //    localuser.WXopenid = u.openid;
            //    new JH_Auth_UserB().Insert(localuser);
            //}
            //else
            //{
            //    //localuser.pccode = EncrpytHelper.Encrypt(localuser.UserName + "@" + localuser.UserPass + "@" + DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
            //    localuser.logindate = DateTime.Now;
            //    new JH_Auth_UserB().Update(localuser);//更新logindate  pccode不能更新
            //}
        }