public static WeixinUser AddWeixinUser(OAuthWeixinUserInfoResult oAuthWeixinUser) { ipowdb_suibian_webDataContext db = ConnHelper.ipowdb_suibian_web(); WeixinUser weixinUser = db.WeixinUser.FirstOrDefault(s => s.OpenId == oAuthWeixinUser.openid); if (weixinUser != null) return weixinUser; weixinUser = new WeixinUser { AddDate = DateTime.Now, City = oAuthWeixinUser.city, Country = oAuthWeixinUser.country, Headimgurl = oAuthWeixinUser.headimgurl, Language = "", Nickname = oAuthWeixinUser.nickname, OpenId = oAuthWeixinUser.openid, Privilege = oAuthWeixinUser.privilege.ToString(), Province = oAuthWeixinUser.province, Remark = "", Sex = oAuthWeixinUser.sex, Subscribe = 0, SubscribeTime = 0, Unionid = "", UpdateDate = DateTime.Now }; db.WeixinUser.InsertOnSubmit(weixinUser); db.SubmitChanges(); return weixinUser; }
public static int ImportOrderDragonBall(string flowNumber) { int i = 0; Order order = new Order(flowNumber); if (order._fields["type"].ToString().Trim().Equals("现货未付")) { SetPayStatus(flowNumber); } string openId = WeixinUser.GetVipUserOpenIdByNumber(order._fields["cell_number"].ToString().Trim()); if (!openId.Trim().Equals("") && (order._fields["pay_status"].ToString().Equals("1") || order._fields["pay_status"].ToString().Equals("3")) && order._fields["deal"].ToString().Equals("0")) { i = DragonBallBalance.Add(openId.Trim(), int.Parse(order._fields["dragon_ball_generated"].ToString().Trim()), order._fields["flow_number"].ToString(), DateTime.Parse(order._fields["order_date"].ToString())); } if (i > 0) { string[,] updateParam = { { "deal", "int", "1" } }; string[,] keyParam = { { "flow_number", "varchar", flowNumber } }; int r = DBHelper.UpdateData("orders", updateParam, keyParam, Util.conStr); if (r != 1) { string[,] keyParamDel = { { "id", "int", i.ToString() } }; DBHelper.DeleteData("user_point_balance", keyParamDel, Util.conStr); i = 0; } } return(i); }
public int PlaceOnlineOrder(string openId) { try { int.Parse(_fields["online_order_id"].ToString()); return(0); } catch { } string detailJson = _fields["order_detail_json"].ToString().Trim(); OnlineOrder newOrder = new OnlineOrder(); WeixinUser user = new WeixinUser(openId); string cellNumber = user.CellNumber.Trim(); if (cellNumber.Trim().Equals("")) { cellNumber = _fields["customer_number"].ToString().Trim(); } string[,] insertParam = { { "type", "varchar", _fields["type"].ToString().Trim() }, { "open_id", "varchar", openId.Trim() }, { "cell_number", "varchar", cellNumber.Trim() }, { "name", "varchar", user.Nick.Trim() }, { "pay_method", "varchar", _fields["pay_method"].ToString().Trim() }, { "pay_state", "int", "0" }, { "order_price", "float", _fields["market_price"].ToString() }, { "shop", "varchar", _fields["shop"].ToString().Trim() }, { "order_real_pay_price", "float", _fields["real_paid_price"].ToString() }, { "memo", "varchar", _fields["memo"].ToString().Trim() }, { "pay_time", "datetime", DateTime.Now.ToString() }, { "ticket_amount", "float", _fields["ticket_amount"].ToString() }, { "score_rate", "float", _fields["score_rate"].ToString() }, { "generate_score", "float", _fields["generate_score"].ToString() }, { "order_temp_id", "float", _fields["id"].ToString() }, { "ticket_code", "varchar", _fields["ticket_code"].ToString().Trim() } }; int i = DBHelper.InsertData("order_online", insertParam); if (i == 1) { i = DBHelper.GetMaxId("order_online"); } try { Dictionary <string, object>[] detailDicArr = Util.GetObjectArrayFromJsonByKey(detailJson, "order_details"); foreach (Dictionary <string, object> detail in detailDicArr) { string[,] detailInsertParam = { { "order_online_id", "int", i.ToString() }, { "product_id", "int", "0" }, { "product_name", "varchar", detail["name"].ToString().Trim() }, { "price", "float", detail["deal_price"].ToString() }, { "count", "int", detail["num"].ToString() }, { "retail_price", "float", detail["market_price"].ToString() } }; DBHelper.InsertData("order_online_detail", detailInsertParam); } } catch { } string[,] updateParam = { { "online_order_id", "int", i.ToString() } }; string[,] keyParam = { { "id", "int", _fields["id"].ToString() } }; DBHelper.UpdateData("order_online_temp", updateParam, keyParam, Util.conStr); return(i); }
public ActionResult WeixinSignIn(string code) { try { if (string.IsNullOrEmpty(code)) { return(Json(new { code = 1, Msg = "参数错误" })); } //微信互联配置信息 string appid = ""; string appkey = ""; WebClient wcl = new WebClient(); string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, appkey, code); string json = wcl.DownloadString(url); json = wcl.DownloadString(url); WeixinUser weixinUser = JsonConvert.DeserializeObject <WeixinUser>(json.Replace("\\", "")); SysUserOpenId userOpenId = dbContext.Set <SysUserOpenId>().Where(x => x.OpenId == weixinUser.openid).FirstOrDefault(); if (userOpenId != null && userOpenId.UserId != Guid.Empty) { SSOClient.SignIn(userOpenId.UserId.Value); return(Redirect("/pages/home/index.html")); } return(Redirect("/pages/account/bind.html?sign=pc&openid=" + weixinUser.openid)); //自动创建本地用户,适用面向公众网站,项目根据需要调整逻辑。 //url = string.Format("https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}", access_token, appid, openId); //wcl.Encoding = Encoding.UTF8; //json = wcl.DownloadString(url); //QQUser qqUser = JsonConvert.DeserializeObject<QQUser>(json.Replace("\\", "")); //user = new SysUser(); //user.UserId = Guid.NewGuid(); //user.UserName = qqUser.nickname; //user.UserCode = Guid.NewGuid().ToString("N").Substring(20); //user.DepartmentId = new Guid("2379788E-45F0-417B-A103-0B6440A9D55D"); //dbContext.SysUser.Add(user); //userOpenId = new SysUserOpenId(); //userOpenId.OpenId = token.openid; //userOpenId.UserId = user.UserId; //userOpenId.CreateTime = DateTime.Now; //userOpenId.BindTime = DateTime.Now; //dbContext.SysUserOpenId.Add(userOpenId); //dbContext.SaveChanges(); //SSOClient.SignIn(userOpenId.UserId.Value); //return Redirect("/pages/home/index.html"); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
private void AddSession(WeixinUser weixinUser) { var userData = new UserData { OpenId = weixinUser.OpenId, WeixinUserId = weixinUser.Id, HeadUrl = weixinUser.Headimgurl }; SessionHelp.UserData = userData; }
public static WeixinUser[] GetAllUsers() { DataTable dt = DBHelper.GetDataTable(" select * from users order by crt desc "); WeixinUser[] usersArr = new WeixinUser[dt.Rows.Count]; for (int i = 0; i < usersArr.Length; i++) { usersArr[i] = new WeixinUser(); usersArr[i]._fields = dt.Rows[i]; } return(usersArr); }
/// <summary> /// 客户Id /// </summary> /// <returns></returns> public int CustomerId() { try { var weixinUsers = WeixinUser.FindByList(OpenId()); return(null != weixinUsers && weixinUsers.Any() ? weixinUsers.First().CustomerId : 0); } catch (Exception ex) { LogManager.GetLogger().Error(ex); return(0); } }
/// <summary> /// 客户姓名 /// </summary> /// <returns></returns> public string CustomerName() { try { var weixinUsers = WeixinUser.FindByList(OpenId()); var accountId = null != weixinUsers && weixinUsers.Any() ? weixinUsers.First().CustomerId : 0; var account = Account.FindById(accountId); return(null != account ? account.Name : string.Empty); } catch (Exception ex) { LogManager.GetLogger().Error(ex); return(""); } }
public int WeixinUserInsert(WeixinUser weixinUser) { using (var cmd = DataCommandManager.GetDataCommand("WeixinUserInsert")) { cmd.SetParameterValue("@openid", weixinUser.openid); cmd.SetParameterValue("@nickname", weixinUser.nickname); cmd.SetParameterValue("@headimgurl", weixinUser.headimgurl); cmd.SetParameterValue("@createTime", weixinUser.createtime); var result = cmd.ExecuteScalar(); if (result != null) { return(Convert.ToInt32(result)); } return(0); } }
/// <summary> /// 我的粉丝 /// </summary> /// <returns></returns> public ActionResult Fans() { try { var customerId = CustomerId(); LogManager.GetLogger().Info("customerId:" + customerId); ViewData["CustomerId"] = customerId; ViewData["CustomerName"] = CustomerName(); ViewData["WeixinUser"] = WeiXinUser(); ViewData["WeiXinUsers"] = WeixinUser.FindByList(); var customerBases = CustomerBase.FindByList(); var fanCount = customerBases.Count(p => p.ParentId == customerId); ViewData["FanCount"] = fanCount; ViewData["CustomerBases"] = customerBases; var customerFanDic = new Dictionary <int, int>(); if (null != customerBases && customerBases.Any()) { foreach (var customerBase in customerBases) { customerFanDic[customerBase.Id] = customerBases.Count(p => p.ParentId == customerBase.Id); } } var dicSort = from objDic in customerFanDic orderby objDic.Value descending select objDic; ViewData["CustomerFanDic"] = dicSort; var index = 1; foreach (KeyValuePair <int, int> kvp in dicSort) { if (kvp.Key == customerId) { break; } index++; } ViewData["Ranking"] = index; } catch (Exception ex) { LogManager.GetLogger().Error(ex); } return(View()); }
public static WeixinUser GetTempWeixinUser(string cell) { WeixinUser user; DataTable dtUser = DBHelper.GetDataTable(" select * from users where cell_number = '" + cell.Trim() + "' and ISNUMERIC(open_id) = 1 "); if (dtUser.Rows.Count == 0) { string tempTimeStampOpenId = Util.GetTimeStamp(); DBHelper.InsertData("users", new string[, ] { { "open_id", "varchar", tempTimeStampOpenId }, { "nick", "varchar", "" }, { "cell_number", "varchar", cell.Trim() }, { "vip_level", "int", "0" }, { "head_image", "varchar", "" } }); user = new WeixinUser(tempTimeStampOpenId); } else { user = new WeixinUser(dtUser.Rows[0]["open_id"].ToString().Trim()); } dtUser.Dispose(); return(user); }
public ActionResult BaseCallback(string code, string state) { LoggerHelper.ToLog("code:" + code); LoggerHelper.ToLog("state:" + state); Session["oauth"] = "true"; ViewData["reurl"] = Request["reurl"]; LoggerHelper.ToLog("reurl:" + Request["reurl"]); if (string.IsNullOrEmpty(code)) { return(Content("您拒绝了授权!")); } if (state != "JeffreySu") { //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下 //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证 return(Content("验证失败!请从正规途径进入!")); } //通过,用code换取access_token var result = OAuth.GetAccessToken(appId, secret, code); LoggerHelper.ToLog("result:" + JsonConvert.SerializeObject(result)); Session["OpenId"] = result.openid; { var weixinUsers = WeixinUser.FindByList(openId: result.openid); if (null == weixinUsers || !weixinUsers.Any()) { var weixinUser = new WeixinUserEntity(); weixinUser.NickName = result.openid; weixinUser.Privilege = ""; weixinUser.Province = ""; weixinUser.OpenId = result.openid; WeixinUser.Save(weixinUser); } } //LogManager.GetLogger().Error("openid:" + result.openid); if (result.errcode != ReturnCode.请求成功) { return(Content("错误:" + result.errmsg)); } //下面2个数据也可以自己封装成一个类,储存在数据库中(建议结合缓存) //如果可以确保安全,可以将access_token存入用户的cookie中,每一个人的access_token是不一样的 Session["OAuthAccessTokenStartTime"] = DateTime.Now; Session["OAuthAccessToken"] = result; //因为这里还不确定用户是否关注本微信,所以只能试探性地获取一下 OAuthUserInfo userInfo = null; try { LoggerHelper.ToLog("已关注,可以得到详细信息。。。。"); //已关注,可以得到详细信息 userInfo = OAuth.GetUserInfo(result.access_token, result.openid); LoggerHelper.ToLog("userInfo:" + JsonConvert.SerializeObject(userInfo)); ViewData["ByBase"] = true; if (null != userInfo && !string.IsNullOrEmpty(userInfo.openid)) { var weixinUsers = WeixinUser.FindByList(openId: userInfo.openid); var weixinUser = null != weixinUsers && weixinUsers.Any() ? weixinUsers.First() : null; if (null != weixinUser) { weixinUser.City = userInfo.city; weixinUser.Country = userInfo.country; weixinUser.HeaderImage = userInfo.headimgurl; weixinUser.NickName = userInfo.nickname; weixinUser.Privilege = userInfo.province; weixinUser.Province = ""; WeixinUser.Save(weixinUser); } else { var weixinUser1 = new WeixinUserEntity(); weixinUser1.City = userInfo.city; weixinUser1.Country = userInfo.country; weixinUser1.HeaderImage = userInfo.headimgurl; weixinUser1.NickName = userInfo.nickname; weixinUser.Privilege = userInfo.province; weixinUser1.Province = ""; weixinUser1.OpenId = userInfo.openid; WeixinUser.Save(weixinUser1); } } var weixinUsers1 = WeixinUser.FindByList(openId: result.openid); Session["wUserInfo"] = null != weixinUsers1 && weixinUsers1.Any() ? weixinUsers1.First() : new WeixinUser(); return(View("UserInfoCallback", userInfo)); } catch (ErrorJsonResultException ex) { //未关注,只能授权,无法得到详细信息 //这里的 ex.JsonResult 可能为:"{\"errcode\":40003,\"errmsg\":\"invalid openid\"}" LoggerHelper.ToLog("BaseCallback:" + ex); //return Content("用户已授权,授权Token:" + result); return(View("UserInfoCallback", userInfo)); } }
private void WeixinLogin(System.Web.Http.Controllers.HttpActionContext actionContext, string userInfo) { var tokens = userInfo.Split(':'); var appId = tokens[0].Trim(); var openId = tokens[1].Trim(); var obj = CacheHelper.GetCache("bw_" + openId); if (obj != null) { if ((string)obj == appId) { IsAuthorized(actionContext); return; } CacheHelper.RemoveAllCache("bw_" + openId); } string appAppId = PubConstant.GetConfigString("AppAppId") ?? ""; string mpAppId = PubConstant.GetConfigString("MpAppId") ?? ""; string webAppId = PubConstant.GetConfigString("WebAppId") ?? ""; RunTecMs.Model.FaFaApi.WeixinUser wxUser = new WeixinUser(); if (!string.IsNullOrEmpty(appAppId)) { if (appId == appAppId) { wxUser.AppOpenID = openId; } } if (!string.IsNullOrEmpty(mpAppId)) { if (appId == mpAppId) { wxUser.MPOpenID = openId; } } if (!string.IsNullOrEmpty(webAppId)) { if (appId == webAppId) { wxUser.WebOpenID = openId; } } RunTecMs.BLL.FaFaApi.User bll = new RunTecMs.BLL.FaFaApi.User(); var user = bll.GetWeixinLoginUser(wxUser); if (user == null) { HandleUnauthorizedRequest(actionContext); return; } if ((user.AppOpenID == openId) || (user.MPOpenID == openId) || (user.WebOpenID == openId)) { IsAuthorized(actionContext); CacheHelper.SetCache("bw_" + openId, appId, TimeSpan.FromSeconds(20)); user = null; } else { HandleUnauthorizedRequest(actionContext); } }
public int WeixinUserInsert(WeixinUser weixinUser) { return(payLogDataAccess.WeixinUserInsert(weixinUser)); }
public IActionResult UserInfoCallback(string code, string returnUrl) { if (string.IsNullOrWhiteSpace(code)) { return(RedirectToAction("Error", new { title = "无效访问", message = "您的请求参数不合法,请从正规渠道访问此功能。" })); } try { var token = AccessTokenContainer.TryGetToken(_corpId, _secret); if (string.IsNullOrWhiteSpace(token)) { _log.Error("获取ACCESSTOKEN详情失败:AccessTokenContainer.TryGetToken()获取失败"); return(RedirectToAction("Error", new { title = "访问失败", message = "从微信服务端请求数据失败,请稍候再试。" })); } var user = OAuth2Api.GetUserId(token, code); if (user.errcode != Senparc.Weixin.ReturnCode_Work.请求成功) { _log.Error("获取用户ID失败:" + user.errmsg); return(RedirectToAction("Error", new { title = "加载失败", message = "从微信服务端获取用户信息失败,请联系管理员或稍候再试" })); } if (string.IsNullOrWhiteSpace(user.UserId)) { _log.Error("获取用户ID失败,接口调用成功,但USERID为空:" + JsonConvert.SerializeObject(user)); return(RedirectToAction("Error", new { title = "拒绝访问", message = "仅限企业微信内部员工使用,未能获取到您的数据,请联系管理员" })); } else { var userInfo = _userUtil.Get(user.UserId); if (userInfo != null) { var userName = userInfo.name; var deptId = 0; if (userInfo.department.Length > 0) { deptId = (int)userInfo.department.Max(); } var dept = _deptUtil.Get(deptId); if (dept == null) { _log.Error("获取部门失败,用户消息:" + string.Join(',', userInfo.department)); return(RedirectToAction("Error", new { title = "访问失败", message = "获取部门数据失败,请联系管理员" })); } var userDto = new WeixinUser { UserId = userInfo.userid.ToLower(), UserName = userInfo.name, DeptId = deptId, DeptName = dept.name }; var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, "WeixinUserName", ClaimTypes.Role); identity.AddClaim(new Claim("WeixinUserId", user.UserId)); identity.AddClaim(new Claim("WeixinUserName", userName)); identity.AddClaim(new Claim("WeixinDeptId", dept.id.ToString())); identity.AddClaim(new Claim("WeixinDeptName", dept.name)); identity.AddClaim(new Claim(ClaimTypes.Role, "Weixin")); var principal = new ClaimsPrincipal(identity); HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); HttpContext.SignInAsync(principal, new AuthenticationProperties { IsPersistent = true, RedirectUri = "/OAuth2/Index" }); HttpContext.Session.Set("WeixinUser", userDto); return(Redirect(returnUrl)); } else { _log.Error("获取用户详情失败:缓存中不存在此"); return(RedirectToAction("Error", new { title = "无效访问", message = "仅限企业微信内部员工使用,若您加入企业,请联系管理员" })); } } } catch (Exception ex) { _log.Error(ex); return(RedirectToAction("Error", new { title = "访问失败", message = "系统错误:" + ex.Message + ",请联系管理员" })); } }