public void Test_BatchAddUser() { var usernames = new[] { "yehong116", "zhangwei178", "xiezhaqin321", "xujianming325", "jiangfeng552", "gewenjun598", "luozhenhua631", "xieshendong635" }; IRepository repo = new Repository(); foreach (var name in usernames) { var userWeChat = new UserWeChat { UserName = name, LastAuthorizeDate = DateTime.Now, Gender = 1, Avatar = string.Empty, DeviceId = string.Empty }; object uid; repo.Insert(userWeChat, out uid); if (uid != null) { var user = new User { ID = (Guid)uid, UserName = name, Password = Encrypt.GetMd5Hash("shsict"), WeChatOpenId = string.Empty, WeChatNickName = string.Empty, EmployeeName = string.Empty, EmployeeNo = string.Empty, Department = string.Empty, Team = string.Empty, Position = string.Empty, Email = string.Empty, Mobile = string.Empty, // important: role Role = UserRoleEnum.Manager, IsApproved = true, LastLoginDate = DateTime.Now, CreateDate = DateTime.Now, IsActive = true, Remark = string.Empty }; repo.Insert(user); } } }
public static UserWeChat Authorize(Guid userGuid, string accessToken, double expiresIn, string refreshToken, string openId, ScopeType scope, bool anonymous = false) { using (var conn = new SqlConnection(DataAccess.ConnectString)) { conn.Open(); var trans = conn.BeginTransaction(); try { IRepository repo = new Repository(); // 保存微信用户 var user = anonymous ? repo.Single<User>(userGuid) : UserDto.GetSession(); if (user != null && user.ID == userGuid) { var u = new UserWeChat(); if (repo.Any<UserWeChat>(userGuid)) { u = repo.Single<UserWeChat>(userGuid); } u.ID = userGuid; u.UserName = user.UserName; u.LastAuthorizeDate = DateTime.Now; u.AccessToken = accessToken; u.AccessTokenExpiredDate = DateTime.Now.AddSeconds(expiresIn); u.RefreshToken = refreshToken; u.RefreshTokenExpiredDate = DateTime.Now.AddDays(30); u.Gender = 0; if (u.Province == null) u.Province = string.Empty; if (u.City == null) u.City = string.Empty; if (u.Country == null) u.Country = string.Empty; if (u.HeadImgUrl == null) u.HeadImgUrl = string.Empty; if (u.Privilege == null) u.Privilege = string.Empty; if (u.UnionID == null) u.UnionID = string.Empty; repo.Save(u, trans); // 更新普通用户 user.WeChatOpenID = openId; // 按scope,获取微信用户详情 if (scope.Equals(ScopeType.snsapi_userinfo)) { var result = new WeChatSnsClient().GetUserInfo(accessToken, openId); if (!string.IsNullOrEmpty(result)) { var json = JToken.Parse(result); user.WeChatNickName = json["nickname"].Value<string>(); u.Gender = json["sex"].Value<short>(); u.Province = json["province"].Value<string>(); u.City = json["city"].Value<string>(); u.Country = json["country"].Value<string>(); u.HeadImgUrl = json["headimgurl"].Value<string>(); u.Privilege = json["privilege"].Value<JArray>().ToString(); u.UnionID = json["unionid"] != null ? json["unionid"].Value<string>() : string.Empty; repo.Update(u, trans); } } // 更新user的openId, nickname repo.Update(user, trans); trans.Commit(); return u; } return null; } catch { trans.Rollback(); throw; } } }
private static void SyncUserWeChatInfo() { IRepository repo = new Repository(); // 7天来未更新的微信会员 或 微信昵称为空的会员 var usersWeChat = repo.Query <UserWeChat>(x => x.LastAuthorizeDate < DateTime.Now.AddDays(-7)); var users = repo.Query <User>(x => x.WeChatOpenID != "") .FindAll(x => string.IsNullOrEmpty(x.WeChatNickName) || usersWeChat.Exists(y => y.ID == x.ID)); if (users.Count > 0 && ConfigGlobal_Arsenal.WeChatActive) { // 根据users,生成输入参数 //{"user_list": [ // { "openid": "otvxTs4dckWG7imySrJd6jSi0CWE", "lang": "zh-CN"}, // { "openid": "otvxTs_JZ6SEiP0imdhpi50fuSZg", "lang": "zh-CN" } // ] //} var mapper = UserWeChatRequestDto.ConfigMapper().CreateMapper(); var userList = new { user_list = mapper.Map <IEnumerable <UserWeChatRequestDto> >(users.DistinctBy(x => x.WeChatOpenID)).ToList() }; var openIds = JsonConvert.SerializeObject(userList); var client = new WeChatApiClient(); var result = client.BatchGetUserInfo(openIds); var json = JToken.Parse(result); if (!string.IsNullOrEmpty(json["user_info_list"].ToString())) { var list = JsonConvert.DeserializeObject <List <UserWeChatResponseDto> >(json["user_info_list"].ToString()); if (list.Count > 0) { foreach (var u in users) { var uResp = list.Find(x => x.openid == u.WeChatOpenID); var uWeChat = repo.Single <UserWeChat>(u.ID); if (uResp != null) { u.WeChatOpenID = uResp.openid; u.WeChatNickName = uResp.nickname; repo.Update(u); if (uWeChat != null) { uWeChat.Gender = uResp.sex; uWeChat.LastAuthorizeDate = DateTime.Now; uWeChat.City = uResp.city ?? string.Empty; uWeChat.Province = uResp.province ?? string.Empty; uWeChat.Country = uResp.country ?? string.Empty; uWeChat.HeadImgUrl = uResp.headimgurl ?? string.Empty; uWeChat.UnionID = uResp.unionid ?? string.Empty; repo.Update(uWeChat); } else { var instance = new UserWeChat { ID = u.ID, UserName = u.UserName, LastAuthorizeDate = DateTime.Now, AccessToken = string.Empty, AccessTokenExpiredDate = DateTime.Now, RefreshToken = string.Empty, RefreshTokenExpiredDate = DateTime.Now, Gender = uResp.sex, Province = uResp.province ?? string.Empty, City = uResp.city ?? string.Empty, Country = uResp.country ?? string.Empty, HeadImgUrl = uResp.headimgurl ?? string.Empty, Privilege = string.Empty, UnionID = uResp.unionid ?? string.Empty }; repo.Insert(instance); } } } } } } }
public static UserWeChat Authorize(Guid userGuid, string accessToken, double expiresIn, string refreshToken, string openId, ScopeType scope, bool anonymous = false) { using (var conn = new SqlConnection(DataAccess.ConnectString)) { conn.Open(); var trans = conn.BeginTransaction(); try { IRepository repo = new Repository(); // 保存微信用户 var user = anonymous ? repo.Single <User>(userGuid) : UserDto.GetSession(); if (user != null && user.ID == userGuid) { var u = new UserWeChat(); if (repo.Any <UserWeChat>(userGuid)) { u = repo.Single <UserWeChat>(userGuid); } u.ID = userGuid; u.UserName = user.UserName; u.LastAuthorizeDate = DateTime.Now; u.AccessToken = accessToken; u.AccessTokenExpiredDate = DateTime.Now.AddSeconds(expiresIn); u.RefreshToken = refreshToken; u.RefreshTokenExpiredDate = DateTime.Now.AddDays(30); u.Gender = 0; if (u.Province == null) { u.Province = string.Empty; } if (u.City == null) { u.City = string.Empty; } if (u.Country == null) { u.Country = string.Empty; } if (u.HeadImgUrl == null) { u.HeadImgUrl = string.Empty; } if (u.Privilege == null) { u.Privilege = string.Empty; } if (u.UnionID == null) { u.UnionID = string.Empty; } repo.Save(u, trans); // 更新普通用户 user.WeChatOpenID = openId; // 按scope,获取微信用户详情 if (scope.Equals(ScopeType.snsapi_userinfo)) { var result = new WeChatSnsClient().GetUserInfo(accessToken, openId); if (!string.IsNullOrEmpty(result)) { var json = JToken.Parse(result); user.WeChatNickName = json["nickname"].Value <string>(); u.Gender = json["sex"].Value <short>(); u.Province = json["province"].Value <string>(); u.City = json["city"].Value <string>(); u.Country = json["country"].Value <string>(); u.HeadImgUrl = json["headimgurl"].Value <string>(); u.Privilege = json["privilege"].Value <JArray>().ToString(); u.UnionID = json["unionid"] != null ? json["unionid"].Value <string>() : string.Empty; repo.Update(u, trans); } } // 更新user的openId, nickname repo.Update(user, trans); trans.Commit(); return(u); } return(null); } catch { trans.Rollback(); throw; } } }
public User SyncUserWithWeChat(string userId, string deviceId = null) { // 调用Wechat接口,凭userid获取通讯录成员信息 var client = new WeChatUserClient(); var result = client.GetUser(userId); if (!string.IsNullOrEmpty(result)) { var json = JToken.Parse(result); if (json["errcode"] != null && json["errmsg"] != null && json["errcode"].Value <int>() == 0 && json["errmsg"].Value <string>() == "ok") { var user = new User { Password = Encrypt.GetMd5Hash("shsict"), Email = string.Empty, Role = UserRoleEnum.Employee, CreateDate = DateTime.Now, IsActive = true }; var userWeChat = new UserWeChat(); // user: { "errcode":0,"errmsg":"ok","userid":"cyrano","name":"陈继麟","department":[17],"position":"技术工程师","mobile":"13818059707", // "gender":"1","avatar":"http:\/\/shp.qpic.cn\/bizmp\/sfQa6NT594TUfQ42suia698Kz8KNY8eNmeogXYCNQicsaicnCMy5I1mfQ\/","status":1,"extattr":{"attrs":[]}} // { "UserId":"xudanfu1015","DeviceId":"c90af29b945abf19b1a3cace63ac9d45"} // user: { "errcode":0,"errmsg":"ok","userid":"xudanfu1015","name":"徐旦复","department":[34],"position":"系统开发主任","mobile":"13482045112", // "gender":"1","avatar":"http:\/\/shp.qpic.cn\/bizmp\/sfQa6NT594Qm6CnIQicHUTLTDCib0QlmdrlfI3GIsLxknRhBYc7JFb2Q\/","status":1, // "extattr":{"attrs":[{"name":"班组","value":"信息技术组"},{"name":"出生年月","value":"198509"},{"name":"政治面貌","value":"中共党员"},{"name":"工号","value":"1015"},{"name":"座机","value":""},{"name":"英文名","value":"xudanfu"}]}} // 获得微信用户的扩展属性 var extattr = json["extattr"].Value <JToken>(); var attrs = extattr?["attrs"].Value <JArray>(); var userdict = new Dictionary <string, string>(); if (attrs?.Count > 0) { foreach (var kvp in attrs) { userdict.Add(kvp["name"].Value <string>(), kvp["value"].Value <string>()); } } using (IDapperHelper dapper = DapperHelper.GetInstance()) { var trans = dapper.BeginTransaction(); try { using (IRepository repo = new Repository()) { // 通过userid,从数据库中获取对应用户 if (json["userid"] != null && repo.Any <User>(x => x.UserName == json["userid"].Value <string>())) { user = repo.Single <User>(x => x.UserName == json["userid"].Value <string>()); } #region 封装 User 实例 user.UserName = json["userid"] != null ? json["userid"].Value <string>() : string.Empty; user.EmployeeName = json["name"] != null ? json["name"].Value <string>() : string.Empty; user.EmployeeNo = userdict.ContainsKey("工号") && userdict["工号"] != null ? userdict["工号"] : string.Empty; if (json["department"]?.Value <JArray>() != null && json["department"].Value <JArray>().Count > 0) { user.Department = GetDepartment(json["department"].Value <JArray>()[0].Value <int>()); } else { user.Department = string.Empty; } user.Team = userdict.ContainsKey("班组") && userdict["班组"] != null ? userdict["班组"] : string.Empty; user.Position = json["position"] != null ? json["position"].Value <string>() : string.Empty; user.Mobile = json["mobile"] != null ? json["mobile"].Value <string>() : string.Empty; user.IsApproved = json["status"]?.Value <bool>() ?? true; user.LastLoginDate = DateTime.Now; user.Remark = json.ToString(); repo.Save(user, out var key); #endregion #region 封装 UserWeChat 实例 userWeChat.ID = (Guid)key; userWeChat.UserName = json["userid"] != null ? json["userid"].Value <string>() : string.Empty; userWeChat.LastAuthorizeDate = DateTime.Now; userWeChat.Gender = json["gender"]?.Value <short>() ?? -1; userWeChat.Avatar = json["avatar"] != null ? json["avatar"].Value <string>() : string.Empty; if (!string.IsNullOrEmpty(deviceId)) { userWeChat.DeviceId = deviceId; } repo.Save(userWeChat, out key); #endregion trans.Commit(); return(user); } } catch { trans.Rollback(); } } } } return(null); }
private static void SyncUserWeChatInfo() { IRepository repo = new Repository(); // 7天来未更新的微信会员 或 微信昵称为空的会员 var usersWeChat = repo.Query<UserWeChat>(x => x.LastAuthorizeDate < DateTime.Now.AddDays(-7)); var users = repo.Query<User>(x => x.WeChatOpenID != "") .FindAll(x => string.IsNullOrEmpty(x.WeChatNickName) || usersWeChat.Exists(y => y.ID == x.ID)); if (users.Count > 0 && ConfigGlobal_Arsenal.WeChatActive) { // 根据users,生成输入参数 //{"user_list": [ // { "openid": "otvxTs4dckWG7imySrJd6jSi0CWE", "lang": "zh-CN"}, // { "openid": "otvxTs_JZ6SEiP0imdhpi50fuSZg", "lang": "zh-CN" } // ] //} var mapper = UserWeChatRequestDto.ConfigMapper().CreateMapper(); var userList = new { user_list = mapper.Map<IEnumerable<UserWeChatRequestDto>>(users.DistinctBy(x => x.WeChatOpenID)).ToList() }; var openIds = JsonConvert.SerializeObject(userList); var client = new WeChatApiClient(); var result = client.BatchGetUserInfo(openIds); var json = JToken.Parse(result); if (!string.IsNullOrEmpty(json["user_info_list"].ToString())) { var list = JsonConvert.DeserializeObject<List<UserWeChatResponseDto>>(json["user_info_list"].ToString()); if (list.Count > 0) { foreach (var u in users) { var uResp = list.Find(x => x.openid == u.WeChatOpenID); var uWeChat = repo.Single<UserWeChat>(u.ID); if (uResp != null) { u.WeChatOpenID = uResp.openid; u.WeChatNickName = uResp.nickname; repo.Update(u); if (uWeChat != null) { uWeChat.Gender = uResp.sex; uWeChat.LastAuthorizeDate = DateTime.Now; uWeChat.City = uResp.city ?? string.Empty; uWeChat.Province = uResp.province ?? string.Empty; uWeChat.Country = uResp.country ?? string.Empty; uWeChat.HeadImgUrl = uResp.headimgurl ?? string.Empty; uWeChat.UnionID = uResp.unionid ?? string.Empty; repo.Update(uWeChat); } else { var instance = new UserWeChat { ID = u.ID, UserName = u.UserName, LastAuthorizeDate = DateTime.Now, AccessToken = string.Empty, AccessTokenExpiredDate = DateTime.Now, RefreshToken = string.Empty, RefreshTokenExpiredDate = DateTime.Now, Gender = uResp.sex, Province = uResp.province ?? string.Empty, City = uResp.city ?? string.Empty, Country = uResp.country ?? string.Empty, HeadImgUrl = uResp.headimgurl ?? string.Empty, Privilege = string.Empty, UnionID = uResp.unionid ?? string.Empty }; repo.Insert(instance); } } } } } } }