// PUT api/User/5 public HttpResponseMessage Putwx_user(int id, wx_user wx_user) { if (!ModelState.IsValid) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } if (id != wx_user.ID) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } db.Entry(wx_user).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex)); } return(Request.CreateResponse(HttpStatusCode.OK)); }
/// <summary> /// 订阅(关注)事件 /// </summary> /// <returns></returns> public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage) { var accessToken = Senparc.Weixin.MP.Containers.AccessTokenContainer.TryGetAccessToken(appId, appSecret); var openId = requestMessage.FromUserName;//获取OpenId var userInfo = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(appId, openId, Language.zh_CN); var temp = wx_userService.LoadEntities(u => u.gzh_openid == openId).FirstOrDefault(); if (temp != null) { temp.state = (int)WXUserState.已关注; temp.add_time = DateTime.Now; wx_userService.EditEntity(temp); } else { //新用户 var user = new user(); user.pid = 0; user.name = userInfo.nickname; user.sex = userInfo.sex; user.state = (int)User_state.正常; user.isbuy = (int)Isbuy.未购买; //首次关注赠送积分 var config_ruleItem = Config_ruleService.LoadEntities(n => n.name == "首次关注" && n.state == (int)State.可用).FirstOrDefault(); if (config_ruleItem != null) { var usr = new user_score_record(); usr.id = Guid.NewGuid(); usr.score = config_ruleItem.value != null?Convert.ToDecimal(config_ruleItem.value) : 0; usr.type = (int)Score_type.收益; usr.state = (int)User_score_record_state.已完成; usr.source_name = "首次关注系统赠送"; usr.add_time = DateTime.Now; usr.remark = ((int)Score_source_remark.系统赠送).ToString(); user.total_score += usr.score; user.usable_score += user.total_score; user.user_score_record.Add(usr); } var newUser = new wx_user() { city = userInfo.city, country = userInfo.country, wx_head_protrait = userInfo.headimgurl, nickname = userInfo.nickname, gzh_openid = userInfo.openid, province = userInfo.province, sex = userInfo.sex, add_time = DateTime.Now, unionid = userInfo.unionid, state = (int)WXUserState.已关注, //已关注 user = user, }; wx_userService.AddEntity(newUser); } var responseMessage = base.CreateResponseMessage <ResponseMessageText>(); responseMessage.Content = userInfo.nickname + ",欢迎您关注我们~"; return(responseMessage); }
//#region 小程序授权入口 ///// <summary> ///// 小程序授权入口 ///// </summary> ///// <param name="code">The code.</param> ///// <returns>返回会话ID</returns> //public ActionResult OnLogin(string code) //{ // var jsonResult = SnsApi.JsCode2Json(wxOpenAppId, wxOpenAppSecret, code); // if (jsonResult.errcode == ReturnCode.请求成功) // { // var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); // dynamic data = new // { // sessionId = sessionBag.Key // }; // return Json(SysEnum.成功, data, "登录成功"); // } // else // { // return Json(SysEnum.失败); // } //} //#endregion #region 获取小程序用户token /// <summary> /// 解密用户数据(获取用户token) /// </summary> /// <param name="sessionId">会话ID</param> /// <param name="encryptedData">要解密的数据</param> /// <param name="iv">解密向量</param> /// <returns>返回Token</returns> public ActionResult DecodeEncryptedData(string sessionId, string encryptedData, string iv) { var userInfoJsonStr = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeEncryptedDataBySessionId(sessionId, encryptedData, iv); var wxUser = Common.SerializeHelper.SerializeToObject <DecodedUserInfo>(userInfoJsonStr); var tempUser = Wx_userService.LoadEntities(u => u.unionid == wxUser.unionId || u.xcx_openid == wxUser.openId).FirstOrDefault(); if (tempUser != null) { if (tempUser.state == (int)WXUserState.取消关注) { tempUser.state = (int)WXUserState.未关注; tempUser.add_time = DateTime.Now; } tempUser.unionid = wxUser.unionId; tempUser.xcx_openid = wxUser.openId; tempUser.nickname = wxUser.nickName; tempUser.wx_head_protrait = wxUser.avatarUrl; tempUser.sex = wxUser.gender; tempUser.city = wxUser.city; tempUser.province = wxUser.province; tempUser.country = wxUser.country; Wx_userService.EditEntity(tempUser); } else { var newUser = new wx_user() { city = wxUser.city, country = wxUser.country, wx_head_protrait = wxUser.avatarUrl, nickname = wxUser.nickName, xcx_openid = wxUser.openId, province = wxUser.province, sex = wxUser.gender, add_time = DateTime.Now, unionid = wxUser.unionId, state = (int)WXUserState.未关注, //未关注 }; Wx_userService.AddEntity(newUser); } dynamic data = new { token = Common.EncryptHelper.Encrypt(string.Format("{0}|{1}|{2}", wxUser.openId, Request.UserHostAddress, RequestCategory.微信小程序)) }; return(Json(SysEnum.成功, data, "获取成功")); }
//获取关注用户列表 public wx_user GetWXUser_list() { wx_user model = new wx_user(); WebClient client = new WebClient(); client.Encoding = System.Text.Encoding.UTF8; //var access_token = getAccessToken() + "1"; var access_token = getAccessToken(); string url = string.Format("https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}&next_openid={1}", access_token, ""); string rel = client.DownloadString(url); if (!string.IsNullOrEmpty(rel)) { model = JsonConvert.DeserializeObject <wx_user>(rel); } return(model); }
// DELETE api/User/5 public HttpResponseMessage Deletewx_user(int id) { wx_user wx_user = db.wx_user.Find(id); if (wx_user == null) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } db.wx_user.Remove(wx_user); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex)); } return(Request.CreateResponse(HttpStatusCode.OK, wx_user)); }
private int SaveAddress(string address, wx_user userInfo) { int id; var item = User_addressService.LoadEntities(n => n.address.Equals(address)).FirstOrDefault(); if (item != null) { id = item.id; } else { var ad = new user_address(); ad.del_flag = (int)Del_flag.正常; ad.state = (int)State.可用; ad.address = address; ad.user_id = userInfo.id; ad.name = userInfo.nickname; ad.add_time = DateTime.Now; var res = User_addressService.AddEntity(ad); id = res.id; } return(id); }
/// <summary> /// 在调用操作方法前调用。 /// </summary> /// <param name="filterContext">有关当前请求和操作的信息。</param> protected override void OnActionExecuting(ActionExecutingContext filterContext) { IApplicationContext ctx = ContextRegistry.GetContext(); Iwx_userService wx_userService = ctx.GetObject("wx_userService") as Iwx_userService; if (UserInfo == null) { string tokenStr = RequestParams["token"]; if (string.IsNullOrEmpty(tokenStr)) { filterContext.Result = Json(SysEnum.未授权登录, "缺少token"); return; } string openid; string userip; RequestCategory RequestCategory; try { string[] arr = Common.EncryptHelper.Decrypt(tokenStr).Split('|'); openid = arr[0]; userip = arr[1]; RequestCategory = (RequestCategory)Enum.Parse(typeof(RequestCategory), arr[2]); } catch (Exception) { filterContext.Result = Json(SysEnum.未授权登录, "token错误"); return; } if (string.IsNullOrEmpty(openid) || string.IsNullOrEmpty(userip)) { filterContext.Result = Json(SysEnum.未授权登录, "token错误"); return; } //if (!userip.Equals(Request.UserHostAddress)) //{ // filterContext.Result = Json(SysEnum.IP不匹配, "IP地址发生变化,请重新登录"); // return; //} switch (RequestCategory) { case RequestCategory.微信公众号: UserInfo = wx_userService.LoadEntities(s => s.gzh_openid == openid).FirstOrDefault(); break; case RequestCategory.微信小程序: UserInfo = wx_userService.LoadEntities(s => s.xcx_openid == openid).FirstOrDefault(); break; //case RequestCategory.APP: // UserInfo = wx_userService.LoadEntities(s => s.appopenid == openid).FirstOrDefault(); // break; //case RequestCategory.WEB: // UserInfo = wx_userService.LoadEntities(s => s.webopenid == openid).FirstOrDefault(); // break; default: filterContext.Result = Json(SysEnum.未授权登录, "token错误"); return; } if (UserInfo == null) { filterContext.Result = Json(SysEnum.未授权登录); return; } else { if (UserInfo.state != (int)WXUserState.已关注) //数据库中状态未关注 { try { var user = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(AppId, UserInfo.gzh_openid, Senparc.Weixin.Language.zh_CN); //微信获取用户信息 该接口每日可调用 50000000 次 保险起见用try包裹 if (user.subscribe == (int)WXUserState.已关注) //是否已关注 { UserInfo.wx_head_protrait = user.headimgurl; UserInfo.sex = user.sex; UserInfo.city = user.city; UserInfo.country = user.country; UserInfo.state = (int)WXUserState.已关注; UserInfo.unionid = user.unionid; UserInfo.gzh_openid = user.openid; UserInfo.city = user.city; UserInfo.nickname = user.nickname; wx_userService.EditEntity(UserInfo); //已关注 修改用户状态 } } catch (Exception) { } } } //只允许微信里访问 //String userAgent = Request.UserAgent; //if (userAgent != null && userAgent.IndexOf("MicroMessenger", StringComparison.Ordinal) <= -1) //{ // HttpContext.Response.Write("请在微信浏览器里访问"); // HttpContext.Response.End(); //} } }
/// <summary> /// 公众号授权回调 /// </summary> /// <param name="code">The code.</param> /// <param name="state">The state.</param> /// <param name="goUrl">要跳转的url地址</param> /// <returns>跳转的url地址会带上Token</returns> public ActionResult UserInfoCallback(string code, string state, string goUrl) { goUrl = Common.EncryptHelper.Decrypt(goUrl); var temp = Request; string parms = string.Empty; string strpid = string.Empty; if (goUrl.IndexOf('?') > -1) { parms = goUrl.Substring(goUrl.IndexOf('?')); if (parms.Contains("pid")) { strpid = parms.Substring(parms.IndexOf("pid")).Split('=')[1]; } } //var strpid = goUrl.Substring(goUrl.IndexOf('?'), goUrl.Length).Split('=')[1]; if (string.IsNullOrEmpty(code)) { return(Content("您拒绝了授权!")); } OAuthAccessTokenResult result = null; string token = string.Empty; //通过,用code换取access_token try { result = OAuthApi.GetAccessToken(appId, secret, code); token = Common.EncryptHelper.Encrypt(string.Format("{0}|{1}|{2}", result.openid, Request.UserHostAddress, RequestCategory.微信公众号)); } catch (Exception ex) { if (ex.Message.Contains("40163")) { return(Redirect(goUrl)); } return(Content(ex.Message)); } if (result.errcode != ReturnCode.请求成功) { return(Redirect(goUrl)); } try { var wxUser = OAuthApi.GetUserInfo(result.access_token, result.openid); var tempUser = Wx_userService.LoadEntities(u => u.unionid == wxUser.unionid || u.gzh_openid == wxUser.openid).FirstOrDefault(); if (!int.TryParse(strpid, out int pid)) { pid = 0; } if (tempUser != null) { if (tempUser.state == (int)WXUserState.取消关注) { tempUser.state = (int)WXUserState.未关注; tempUser.add_time = DateTime.Now; } //if (tempUser.unsubscribe_time==null||tempUser.unsubscribe_time<=DateTime.Now.AddDays(-7)) if (true) { if (tempUser.user == null) { //新用户 var user = new user(); user.pid = pid; user.name = wxUser.nickname; user.sex = wxUser.sex; user.state = (int)User_state.正常; user.isbuy = (int)Isbuy.未购买; //首次关注赠送积分 var config_ruleItem = Config_ruleService.LoadEntities(n => n.name == "首次关注" && n.state == (int)State.可用).FirstOrDefault(); if (config_ruleItem != null) { var usr = new user_score_record(); usr.id = Guid.NewGuid(); usr.score = config_ruleItem.value != null?Convert.ToDecimal(config_ruleItem.value) : 0; usr.type = (int)Score_type.收益; usr.state = (int)User_score_record_state.已完成; usr.source_name = "首次关注系统赠送"; usr.add_time = DateTime.Now; usr.remark = ((int)Score_source_remark.系统赠送).ToString(); user.total_score += usr.score; user.usable_score += user.total_score; user.user_score_record.Add(usr); } tempUser.user = user; } tempUser.unionid = wxUser.unionid; tempUser.gzh_openid = wxUser.openid; tempUser.nickname = wxUser.nickname; tempUser.wx_head_protrait = wxUser.headimgurl; tempUser.sex = wxUser.sex; tempUser.city = wxUser.city; tempUser.province = wxUser.province; tempUser.country = wxUser.country; tempUser.unsubscribe_time = DateTime.Now; Wx_userService.EditEntity(tempUser); } } else { //新用户 var user = new user(); user.pid = pid; user.name = wxUser.nickname; user.sex = wxUser.sex; user.state = (int)User_state.正常; user.isbuy = (int)Isbuy.未购买; //首次关注赠送积分 var config_ruleItem = Config_ruleService.LoadEntities(n => n.name == "首次关注" && n.state == (int)State.可用).FirstOrDefault(); if (config_ruleItem != null) { var usr = new user_score_record(); usr.id = Guid.NewGuid(); usr.score = config_ruleItem.value != null?Convert.ToDecimal(config_ruleItem.value) : 0; usr.type = (int)Score_type.收益; usr.state = (int)User_score_record_state.已完成; usr.source_name = "首次关注系统赠送"; usr.add_time = DateTime.Now; usr.remark = ((int)Score_source_remark.系统赠送).ToString(); user.total_score += usr.score; user.usable_score += user.total_score; user.user_score_record.Add(usr); } var newUser = new wx_user() { city = wxUser.city, country = wxUser.country, wx_head_protrait = wxUser.headimgurl, nickname = wxUser.nickname, gzh_openid = wxUser.openid, province = wxUser.province, sex = wxUser.sex, add_time = DateTime.Now, unionid = wxUser.unionid, state = (int)WXUserState.未关注,//未关注 user = user, }; Wx_userService.AddEntity(newUser); //SaveSyslog($"{wxUser.nickname}=>({Url})加入系统,pid={pid}", SysLogType.前台日志, "授权系统"); } var url = $"{goUrl}?state={Guid.NewGuid().ToString().Substring(0, 4)}#token={token}"; return(Redirect(url)); } catch (ErrorJsonResultException ex) { return(Content(ex.Message)); } }
public async Task <IHttpActionResult> GetWxLoginInfo(string openId) { try { HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"]; String clientIP = context.Request.UserHostAddress; string username = context.Request.Headers.Get("username"); string userfullname = context.Request.Headers.Get("userfullname"); string avatarUrl = context.Request.Headers.Get("avatarUrl"); int userId = 0; wx_user info = await db.wx_user.SingleOrDefaultAsync(m => m.wx_id.Equals(openId)); if (info != null) { userId = info.sid; } else { info = new wx_user(); info.avatar_url = avatarUrl; info.create_time = DateTime.Now; info.wx_id = openId; info.real_name = userfullname; info.wx_name = username; info.state = 0; db.wx_user.Add(info); await db.SaveChangesAsync(); userId = info.sid; } string Token = Guid.NewGuid().ToString(); var dtNow = DateTime.Now; ticketauth tka = await db.ticketauth.SingleOrDefaultAsync(m => m.user_id == userId && m.state == 1 && m.user_type == 2); if (tka != null) { tka.state = 0; db.ticketauth.Attach(tka); var stateEntity = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager.GetObjectStateEntry(tka); stateEntity.SetModifiedProperty("state"); } ticketauth tmp = new ticketauth(); tmp.user_id = userId; tmp.token = Token; tmp.create_time = dtNow; tmp.expire_time = dtNow.AddYears(1); tmp.state = 1; tmp.user_type = 2; tmp.client_ip = clientIP; db.ticketauth.Add(tmp); await db.SaveChangesAsync(); WxLoginToken res = new WxLoginToken(); res.code = 100; res.member = info; res.token = Token; return(Ok(res)); } catch (Exception e) { WxLoginToken res = new WxLoginToken(); log.Error(e.Message); res.code = 102; res.message = "未知错误:" + e.Message + "--" + e.InnerException.Message; return(Ok(res)); } }