public ActionResult OnLogin(string code) { JsCode2JsonResult jsonResult = SnsApi.JsCode2Json(Comman.Appid, Comman.AppSecret, code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { SessionBag sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); Session[sessionBag.Key] = jsonResult; Session.Timeout = 60; StatusReport sr = EmployeeDal.CheckOpenIdExist(jsonResult.openid); return(Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, userInfo = sr })); } else { return(Json(new { success = false, mag = jsonResult.errmsg, result = jsonResult })); } }
public ActionResult OnLogin(string code) { var jsonResult = SnsApi.JsCode2Json(AppId, AppSecret, code); if (jsonResult.errcode == ReturnCode.请求成功) { //Session["WxOpenUser"] = jsonResult;//使用Session保存登陆信息(不推荐) //使用SessionContainer管理登录信息(推荐) var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); //注意:生产环境下SessionKey属于敏感信息,不能进行传输! return(Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, sessionKey = sessionBag.SessionKey })); } else { return(Json(new { success = false, msg = jsonResult.errmsg })); } }
public async Task <ApiResult <UserOutput> > MpLogin([FromQuery] MpLoginInput input) { var config = Resolve <IAutoConfigService>().GetValue <MiniProgramConfig>(); var openId = SnsApi.JsCode2Json(config.AppID, config.AppSecret, input.Code) .openid; if (openId.IsNullOrEmpty()) { return(ApiResult.Failure <UserOutput>("获取openId失败")); } return(null); //try { // var result = await _userManager.LoginByOpenIdAsync(openId); // if (result.Succeeded) { // var _user = Resolve<IUserService>().GetUserDetail(AutoModel.BasicUser.Id); // var userOutput = Resolve<IUserDetailService>().GetUserOutput(_user.Id); // return ApiResult.Success(userOutput); //登录成功,返回用户的详细信息 // } else { // var user = new Domain.Entities.User { // UserName = "******" + new Random(DateTime.Now.Millisecond).Next(int.MaxValue).ToString() // .PadLeft(10, '0') + Resolve<IUserService>().MaxUserId(), // Name = input.nickname, // //ParentId = usercode, // Detail = new UserDetail { // Password = "******".ToMd5HashString(), // PayPassword = "******".ToMd5HashString(), // Avator = input.avatarUrl, // OpenId = openId, // Sex = input.gender == 1 ? Sex.Man : (input.gender == 2 ? Sex.WoMan : Sex.UnKnown) // } // }; // user.Email = user.UserName + "@qnn.com"; // user.Mobile = user.UserName; // // _userManager.RegisterAsync(user, true).GetAwaiter().GetResult(); // var userOutput = Resolve<IUserDetailService>().GetUserOutput(user.Id); // return ApiResult.Success(userOutput); //登录成功,返回用户的详细信息 // } //} catch (Exception e) { // return ApiResult.Failure<UserOutput>(e.Message); //} }
public ActionResult OnLogin(string code, string shareNumber, string userId, string userName, string shareTime, string kindergartenName) { StatusReport sr = new StatusReport(); var jsonResult = SnsApi.JsCode2Json(Comman.Appid, Comman.AppSecret, code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { //Session["WxOpenUser"] = jsonResult; var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); Session[sessionBag.Key] = jsonResult; Session.Timeout = 60; sr = WXUserDal.SetNewUser(jsonResult.openid, kindergartenName); if (sr.status == "Success") { User user = (User)sr.data; string receiverId = user.id; if (!string.IsNullOrEmpty(shareNumber) && !string.IsNullOrEmpty(userId) && !string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(shareTime)) { if (userId != receiverId) { sr = WXShareDal.SetShareInfo(receiverId, shareNumber, userId, userName, shareTime, kindergartenName); using (StreamWriter sw = new StreamWriter("D:\\1_importTemp\\TestFile1.txt")) { sw.WriteLine(sr.result.ToString()); } } } sr.data = new { success = true, msg = "OK", sessionId = sessionBag.Key, user = user }; } else { sr.data = new { success = true, msg = "OK", sessionId = sessionBag.Key }; } return(Json(sr)); } else { sr.status = "Fail"; sr.data = new { success = false, mag = jsonResult.errmsg, result = jsonResult }; return(Json(sr)); //return Json(new { success = false, mag = jsonResult.errmsg, result = jsonResult }); } }
private string GetWechatSessionId(string weiXinCode) { if (environment.EnvironmentName == "dev" || environment.EnvironmentName == "qa") { var tag = SessionContainer.UpdateSession(null, "071TIDkB14xCof0eHekB1I4NkB1TIDk5", "071TIDkB14xCof0eHekB1I4NkB1TIDk5"); return(tag.Key); } var jsonResult = SnsApi.JsCode2Json(wxConfiguration.AppId, wxConfiguration.AppSecret, weiXinCode); if (jsonResult.errcode == ReturnCode.请求成功) { SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); return(jsonResult.openid); } else { logger.LogError(JsonConvert.SerializeObject(jsonResult)); } return(string.Empty); }
public ActionResult OnLogin(string code) { StatusReport sr = new StatusReport(); var jsonResult = SnsApi.JsCode2Json(Common.Appid, Common.AppSecret, code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); Session[sessionBag.Key] = jsonResult; Session.Timeout = 60; string openId = sessionBag.OpenId; sr = ProprietorDal.CheckOpenIdExist(openId); sr.parameters = sessionBag.Key; return(Json(sr)); //return Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, result = Session[sessionBag.Key] }); } else { return(Json(sr.SetFail("微信登录失败:" + jsonResult.errmsg))); //return Json(new { success = false, mag = jsonResult.errmsg, result = jsonResult }); } }
public object Do_Login(object param) { LoginParam loginParam = JsonConvert.DeserializeObject <LoginParam>(param.ToString()); if (loginParam == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } var jsonResult = SnsApi.JsCode2Json(Global.APPID, Global.APPSECRET, loginParam.code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { var manager = Senparc.Weixin.Cache.Redis.RedisManager.Manager; AccessTokenContainer.Register(Global.APPID, Global.APPSECRET); var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); return(new { sessionId = sessionBag.Key }); } else { throw new ApiException(CodeMessage.SenparcCode, jsonResult.errmsg); } }
public IActionResult OnLogin(string code) { CommonResult result = new CommonResult(); try { var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, code); if (jsonResult.errcode == ReturnCode.请求成功) { //使用SessionContainer管理登录信息(推荐) var unionId = jsonResult.unionid; var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, unionId); //注意:生产环境下SessionKey属于敏感信息,不能进行传输! //return Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, sessionKey = sessionBag.SessionKey }); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); //User user = userApp.GetUserByUnionId(unionId); User user = userService.GetUserByOpenId("yuebon.openid.wxapplet", jsonResult.openid); if (user == null) { UserInputDto userInput = new UserInputDto(); userInput.OpenId = jsonResult.openid; user.UnionId = jsonResult.unionid; userInput.OpenIdType = "yuebon.openid.wxapplet"; userInput.NickName = "游客"; userInput.UnionId = jsonResult.unionid; result.Success = userService.CreateUserByWxOpenId(userInput); } //针对老用户更新UnionId if (user != null && string.IsNullOrEmpty(user.UnionId)) { user.UnionId = jsonResult.unionid; result.Success = userService.Update(user, user.Id); } string userId = string.Empty; if (result.ResData != null) { userId = result.ResData.ToString(); } if (user == null) { user = userService.GetUserByOpenId("yuebon.openid.wxapplet", jsonResult.openid); } var currentSession = (YuebonCurrentUser)(yuebonCacheHelper.Get("login_user_" + userId)); if (currentSession == null || string.IsNullOrWhiteSpace(currentSession.AccessToken)) { JwtOption jwtModel = App.GetService <JwtOption>(); TokenProvider tokenProvider = new TokenProvider(jwtModel); TokenResult tokenResult = tokenProvider.LoginToken(user, "wxapplet"); currentSession = new YuebonCurrentUser { UserId = user.Id, Account = user.Account, Name = user.RealName, NickName = user.NickName, AccessToken = tokenResult.AccessToken, AppKey = "wxapplet", CreateTime = DateTime.Now, HeadIcon = user.HeadIcon, Gender = user.Gender, ReferralUserId = user.ReferralUserId, MemberGradeId = user.MemberGradeId, Role = roleService.GetRoleEnCode(user.RoleId), MobilePhone = user.MobilePhone, WxSessionId = sessionBag.Key }; TimeSpan expiresSliding = DateTime.Now.AddMinutes(120) - DateTime.Now; yuebonCacheHelper.Add("login_user_" + user.Id, currentSession, expiresSliding, true); } CurrentUser = currentSession; result.ResData = currentSession; //new AuthorizeApp().GetAccessedControls(user.Account); result.ErrCode = ErrCode.successCode; result.Success = true; } else { result.ErrCode = ErrCode.failCode; result.ErrMsg = jsonResult.errmsg; } } catch (Exception ex) { result.ErrMsg = ex.Message; } return(ToJsonContent(result)); }
public async Task <Result> LiteAppLogin([FromBody] WeChatLiteAppLoginRequest request) { string errorMsg = string.Empty; try { JsCode2JsonResult jsonResult = SnsApi.JsCode2Json(WechatService.WxOpenAppId, WechatService.WxOpenAppSecret, request.Code); if (jsonResult != null && jsonResult.errcode == ReturnCode.请求成功) { var customer = await _customerRepository.Query() .FirstOrDefaultAsync(e => e.OpenId == jsonResult.openid); if (customer == null) { int?parentId = null; var anyParent = await _customerRepository.Query().AnyAsync(e => e.Id == request.ParentId); if (anyParent) { parentId = request.ParentId; } var userInfo = request.UserInfo; customer = new Customer { NickName = userInfo.NickName, OpenId = jsonResult.openid, SessionKey = jsonResult.session_key, UnionId = jsonResult.unionid, Gender = userInfo.Gender, Country = userInfo.Country, Province = userInfo.Province, City = userInfo.City, AvatarUrl = userInfo.AvatarUrl, Language = userInfo.Language, ParentId = parentId, Createat = DateTime.Now, Assets = new Assets() { TotalAssets = 0, AvailableAmount = 0, TotalCommission = 0, UpdateTime = DateTime.Now, Createat = DateTime.Now } }; await _customerRepository.InsertAsync(customer); if (parentId.HasValue) { await _mediator.Publish(new CustomerRelationEvent { ParentId = request.ParentId, ChildrenId = customer.Id }); } } else { if (!customer.ParentId.HasValue && request.ParentId > 0) { var anyParent = await _customerRepository.Query().AnyAsync(e => e.Id == request.ParentId); if (anyParent) { customer.ParentId = request.ParentId; await _mediator.Publish(new CustomerRelationEvent { ParentId = request.ParentId, ChildrenId = customer.Id }); } } if (customer.SessionKey != jsonResult.session_key) { customer.SessionKey = jsonResult.session_key; await _customerRepository.UpdateProperyAsync(customer, nameof(customer.SessionKey), nameof(customer.ParentId)); } } List <Claim> claims = new List <Claim>(); claims.Add(new Claim("id", customer.Id.ToString())); // claims.Add(new Claim("openId", customer.OpenId)); var token = _tokenService.JwtToken(claims); var customerRes = _mapper.Map <CustomerResponse>(customer); return(Result.Ok(new WeChatLiteAppLoginResponse(token, customerRes))); } } catch (Exception ex) { errorMsg = ex.Message; } return(Result.Fail(ResultCodes.RequestParamError, errorMsg)); }
public static JsCode2JsonResult WxLogin(Wx_App app, string code) { return(SnsApi.JsCode2Json(app.AppId, app.AppSecret, code)); }
public async Task <IActionResult> login([FromBody] JObject jObject) { var code = jObject["code"].ToString(); var activityNo = this.GetActivityNo(); #region 校验参数 StringBuilder sb = new StringBuilder(); if (string.IsNullOrWhiteSpace(code)) { sb.AppendLine("code无效!"); } if (string.IsNullOrWhiteSpace(appId)) { sb.AppendLine("appid无效!"); } if (!string.IsNullOrEmpty(sb.ToString())) { return(BadRequest(sb.ToString())); } #endregion 校验参数 #region 获取微信openId var jsonResult = new JsCode2JsonResult(); try { jsonResult = SnsApi.JsCode2Json(appId, appSecret, code); //Console.WriteLine("jsonResult:" + Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult)); if (jsonResult.errcode == ReturnCode.请求成功) { if (string.IsNullOrEmpty(jsonResult.openid)) { return(BadRequest("获取OpenId失败")); } } } catch (Exception ex) { Console.WriteLine("登录失败:" + ex.Message); return(BadRequest("登录失败")); } #endregion 获取微信openId //开放平台下存在同一主体小程序+公众号且用户已关注返回unionId,否则不返回 //同主体公众号小程序 用户是否关注 1:关注 0:否 var subscsribe = !string.IsNullOrEmpty(jsonResult.unionid) ? 1 : 0; //获取会员信息,每次都会更新sessionKey var data = await _activityApplication.GetMemberByOpenIdAsync(activityNo, jsonResult.openid, jsonResult.session_key); //获取活动信息 var activityInfo = await _activityApplication.GetActivityResponseAsync(this.GetActivityNo()); // 愿望状态 var wish = await _activityApplication.MemberWishStatusAsync(activityNo, data.memberId); return(this.MyOK( new { subscsribe, data.memberId, data.gender, data.isBind, data.nickName, data.avatarUrl, activity = new { activityInfo?.status, activityInfo?.startTime, activityInfo?.endTime, activityInfo?.serverTime }, myWish = new { wishId = wish.Item1, status = wish.Item2, mchNo = wish.Item3 } })); }
public async Task <IActionResult> BindPhone([FromBody] BindTelRequestParam request) { if (request == null) { return(BadRequest("参数错误")); } if (string.IsNullOrEmpty(request.encryptedData) || string.IsNullOrEmpty(request.iv)) { return(BadRequest("参数错误")); } var memberId = this.GetMemberId(); if (memberId == 0) { return(BadRequest("未获取会员id")); } #region 更新session_key if (!string.IsNullOrEmpty(request.code)) { var jsonResult = new JsCode2JsonResult(); try { jsonResult = SnsApi.JsCode2Json(appId, appSecret, request.code); await _activityApplication.UpdateSessionKeyAsync(memberId, jsonResult.session_key); } catch (Exception ex) { Console.WriteLine("更新session_key失败:" + ex.Message); } } #endregion 更新session_key string sessionKey = await _activityApplication.GetSessionKeyAsync(memberId); string tel = ""; #region 解析手机号 try { var jsonStr = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeEncryptedData(sessionKey, request.encryptedData, request.iv); var phoneNumber = Newtonsoft.Json.JsonConvert.DeserializeObject <Senparc.Weixin.WxOpen.Entities.DecodedPhoneNumber>(jsonStr); tel = phoneNumber.purePhoneNumber; } catch (Exception ex) { var logger = _loggerFactory.CreateLogger($"Error-BindPhoneNumber:{DateTime.Now}"); logger.LogError(ex.Message); return(BadRequest("手机号解析失败")); } #endregion 解析手机号 if (string.IsNullOrEmpty(tel)) { return(BadRequest("手机号解析失败")); } var(resCode, res) = await _activityApplication.BindTelAsync(memberId, tel); if (resCode == 0) { return(BadRequest(res)); } return(this.MyOK(new { resCode = 1 })); }
private static readonly string CertPassword = AppConfig.GetApp("certPwd"); //秘钥 #endregion /// <summary> /// 通过code获取openid,session_key /// </summary> /// <param name="code"></param> /// <returns></returns> public JsCode2JsonResult JsCode2Json(string code) { var result = SnsApi.JsCode2Json(WxOpenId, WxOpenSecret, code); return(result); }
public ActionResult LoginByWeixin(string code, string userInfo) { try { var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, code); if (jsonResult.errcode == ReturnCode.请求成功) { //Session["WxOpenUser"] = jsonResult;//使用Session保存登陆信息(不推荐) //使用SessionContainer管理登录信息(推荐) //var unionId = ""; //var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, unionId); var accountViewModel = new AccountViewModel(); var accountDto = SerializeHelper.DeserializeString <AccountDto>(userInfo); var user = _context.Account.FirstOrDefault(_ => _.OpenId == jsonResult.openid); if (user == null) { user = new Account { OpenId = jsonResult.openid, NickName = accountDto.NickName, AvatarUrl = accountDto.AvatarUrl, Status = AccountStatus.Enabled }; var account = _context.Account.Add(user).Entity; _context.SaveChanges(); //角色控制 Role role = _context.Role.FirstOrDefault(_ => _.RoleName == "普通用户"); _context.UserRole.Add(new UserRole { RoleId = role.Id, UserId = account.Id }); _context.SaveChanges(); } //角色控制 var userRole = _context.UserRole.FirstOrDefault(_ => _.UserId == user.Id); Role bindRole = userRole == null ? null : userRole.Role; accountViewModel = _mapper.Map <AccountViewModel>(user); //角色控制 accountViewModel.Role = _mapper.Map <RoleViewModel>(bindRole); accountViewModel.RoleName = bindRole == null ? null : bindRole.RoleName; // 将用户id和角色名,作为单独的自定义变量封装进 token 字符串中。 TokenModelJwt tokenModel = new TokenModelJwt { Uid = user.Id.ToString(), Role = accountViewModel.Role == null ? "" : accountViewModel.Role.RoleName }; string jwtStr = JwtHelper.IssueJwt(tokenModel, TokenType.AccessToken);//登录,获取到一定规则的 Token 令牌 _distributeCache.Set("AppAccount" + tokenModel.Uid, SerializeHelper.ObjectToByteArray(accountViewModel)); //注意:生产环境下SessionKey属于敏感信息,不能进行传输! return(Ok(new { success = true, msg = "OK", data = new { token = jwtStr, userInfo = accountViewModel } })); } else { return(Ok(new { success = false, msg = jsonResult.errmsg })); } } catch (Exception ex) { return(Ok(new { success = false, msg = ex.Message })); } }
/// <summary> /// 登录(获取基础信息) /// 需获取unionId时,为下一步获取用户详细信息做准备 /// </summary> /// <param name="model"></param> /// <returns></returns> public InvokeResult <DataLoginInfo> Login(InputLoginModel model) { var xLog = new Logger(); xLog.AddLine("=================== Member Login ========================"); xLog.AddLine($"JsCode :{model.JsCode}"); string ip = HttpContext.Current.Request.UserHostAddress; xLog.AddLine($"Ip :{ip}"); xLog.AddLine("---------------------------------------------------------------"); xLog.AddLine($"Input Data:{Environment.NewLine}{JsonConvert.SerializeObject(model, Formatting.Indented)}"); xLog.AddLine($"{WxOpenAppId} {WxOpenAppSecret}"); var r = new InvokeResult <DataLoginInfo>() { Data = new DataLoginInfo() }; try { var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, model.JsCode); if (jsonResult.errcode == ReturnCode.请求成功) { //使用SessionContainer管理登录信息(推荐) var unionId = jsonResult.unionid; var sessionId = Guid.NewGuid(); var sessionBag = SessionContainer.UpdateSession(sessionId.ToString(), jsonResult.openid, jsonResult.session_key, unionId); r.Data.OpenId = jsonResult.openid; r.Data.UnionId = jsonResult.unionid; xLog.AddLine($"JsonResult:{Environment.NewLine}{Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult, Formatting.Indented)}"); var xSession = new TinyAppSession(); if (!xSession.Add(jsonResult.openid, jsonResult.session_key, sessionId)) { xLog.AddLine($"Session update error:{xSession.ErrorMessage}"); } var openId = jsonResult.openid; unionId = jsonResult.unionid; if (string.IsNullOrEmpty(openId)) { openId = ""; } if (string.IsNullOrEmpty(unionId)) { unionId = ""; } var xUser = new WeiXinUser(); if (xUser.LoadByTinyAppAccount(unionId, openId, out var user)) { if (user != null) { r.Data.UnionId = unionId; r.Data.Avatar = user.HeadImage; r.Data.NickName = user.NickName; if (!string.IsNullOrEmpty(openId) && !string.IsNullOrEmpty(unionId) && (user.OpenId != user.UnionId) && !string.IsNullOrEmpty(user.HeadImage) && !string.IsNullOrEmpty(user.NickName)) { if (xUser.FetchRole(unionId, out _, out var parents, out var teachers)) { if (parents != null) { r.Data.Parents = new List <DataParentRole>(); foreach (var item in parents) { var p = new DataParentRole(); p.ParentId = item.ParentId; p.StudentId = item.StudentId; r.Data.Parents.Add(p); } } if (teachers != null) { r.Data.Teachers = new List <DataTeacherRole>(); foreach (var item in teachers) { var t = new DataTeacherRole(); t.TeacherId = item.TeacherId; t.TeamId = item.TeamId; r.Data.Teachers.Add(t); } } r.Success = true; } else { r.ErrorMessage = xUser.ErrorMessage; xLog.AddLine("获取角色失败:" + xUser.ErrorMessage); r.Success = false; } } else { r.ErrorNumber = 404; r.ErrorMessage = "信息不全!"; r.Success = false; } } else { r.Success = false; r.ErrorNumber = 404; r.ErrorMessage = "用户不存在!"; } } else { r.ErrorNumber = 404; r.Success = false; r.ErrorMessage = "用户不存在!"; } } else { r.Success = false; r.ErrorMessage = "请求失败:" + jsonResult.errmsg; } if (string.IsNullOrEmpty(r.Data.OpenId)) { r.Data.OpenId = ""; } if (string.IsNullOrEmpty(r.Data.UnionId)) { r.Data.UnionId = ""; } return(r); }
public object Do_Login(BaseApi baseApi) { LoginParam loginParam = JsonConvert.DeserializeObject <LoginParam>(baseApi.param.ToString()); if (loginParam == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } var jsonResult = SnsApi.JsCode2Json(Global.APPID, Global.APPSECRET, loginParam.code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { AccessTokenContainer.Register(Global.APPID, Global.APPSECRET); var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, jsonResult.unionid); OpenDao openDao = new OpenDao(); SessionUser sessionUser = new SessionUser(); if (loginParam.tempOpenId != null && loginParam.tempOpenId.StartsWith("3rd-")) { Member member1 = openDao.GetMember(Utils.GetOpenID(sessionBag.Key)); if (member1 == null) { openDao.UpdateMemberOpenID(Utils.GetOpenID(sessionBag.Key), loginParam.tempOpenId); } else { Member member2 = openDao.GetMember(loginParam.tempOpenId); if (member1.openid != member2.openid) { openDao.MoveMember(member1.memberId, member2.memberId, member2.heart); } } } Member member = openDao.GetMember(Utils.GetOpenID(sessionBag.Key)); if (member == null) { sessionUser.userType = "GUEST"; sessionBag.Name = JsonConvert.SerializeObject(sessionUser); SessionContainer.Update(sessionBag.Key, sessionBag, new TimeSpan(Global.SESSION_EXPIRY_H, Global.SESSION_EXPIRY_M, Global.SESSION_EXPIRY_S)); return(new { token = sessionBag.Key, isReg = false }); } else { sessionUser.userType = "MEMBER"; sessionUser.openid = sessionBag.OpenId; sessionUser.memberId = member.memberId; sessionBag.Name = JsonConvert.SerializeObject(sessionUser); SessionContainer.Update(sessionBag.Key, sessionBag, new TimeSpan(Global.SESSION_EXPIRY_H, Global.SESSION_EXPIRY_M, Global.SESSION_EXPIRY_S)); openDao.AddMemberHeartCommit(member); return(new { token = sessionBag.Key, isReg = true, member.memberId, member.memberName, member.memberImg, member.memberPhone, member.memberSex, member.scanCode }); } } else { throw new ApiException(CodeMessage.SenparcCode, jsonResult.errmsg); } }
public async Task <ApiResult <WeixinJsPaySignature> > Pay([FromBody] PayModelInput model, CancellationToken cancelToken) { /* * 接口根据订单id和小程序Code * 获取支付调起参数 */ if (string.IsNullOrWhiteSpace(model.Id)) { throw new NotImplementedException("订单Id信息为空!"); } //查询订单 var data = await _orderRepository.GetIncludeAsync(model.Id, cancelToken); ApiResult <WeixinJsPaySignature> apiResult = new ApiResult <WeixinJsPaySignature>(); _ = new ApiResult(); string timeStamp = TenPayV3Util.GetTimestamp(); AppLogger.Debug(JsonConvert.SerializeObject("1" + timeStamp), JsonConvert.SerializeObject(timeStamp)); string nonceStr = TenPayV3Util.GetNoncestr(); AppLogger.Debug(JsonConvert.SerializeObject("2" + nonceStr), JsonConvert.SerializeObject(nonceStr)); string PayV3_TenpayNotify = ConfigurationManager.AppSettings["PayV3_TenpayNotify"]; TenPayV3Info tenPayV3Info = new TenPayV3Info(GuoGuoCommunity_WxOpenAppId, GuoGuoCommunity_WxOpenAppSecret, PayV3_MchId, PayV3_Key, string.Empty, string.Empty, PayV3_TenpayNotify, string.Empty); AppLogger.Debug(JsonConvert.SerializeObject(tenPayV3Info), JsonConvert.SerializeObject(tenPayV3Info)); var openIdResult = SnsApi.JsCode2Json(GuoGuoCommunity_WxOpenAppId, GuoGuoCommunity_WxOpenAppSecret, model.Code); AppLogger.Debug(JsonConvert.SerializeObject(openIdResult), JsonConvert.SerializeObject(openIdResult)); var xmlDataInfo = new TenPayV3UnifiedorderRequestData(tenPayV3Info.AppId, tenPayV3Info.MchId, "呙呙社区购物", data.Number, Convert.ToInt32(data.PaymentPrice * 100), GetClientIpAddress(Request), tenPayV3Info.TenPayV3Notify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, openIdResult.openid, tenPayV3Info.Key, nonceStr, attach: data.Id.ToString()); AppLogger.Debug(DateTime.Now.ToString("yyyyMMddHHmmss") + "****TenPayV3UnifiedorderRequestData对象" + JsonConvert.SerializeObject(xmlDataInfo), "****TenPayV3UnifiedorderRequestData对象" + JsonConvert.SerializeObject(xmlDataInfo)); var resultPay = await TenPayV3.UnifiedorderAsync(xmlDataInfo); AppLogger.Debug("****TenPayV3.Unifiedorder返回对象" + JsonConvert.SerializeObject(resultPay), "****TenPayV3.Unifiedorder返回对象" + JsonConvert.SerializeObject(resultPay)); if (resultPay.return_code.ToUpper() == "SUCCESS") { if (resultPay.result_code.ToUpper() == "SUCCESS") { //设置支付参数 RequestHandler paySignReqHandler = new RequestHandler(null); paySignReqHandler.SetParameter("appId", tenPayV3Info.AppId); paySignReqHandler.SetParameter("timeStamp", timeStamp); paySignReqHandler.SetParameter("nonceStr", nonceStr); paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", resultPay.prepay_id)); paySignReqHandler.SetParameter("signType", "MD5"); paySignReqHandler.SetParameter("nonceStr", nonceStr); string paySign = paySignReqHandler.CreateMd5Sign("key", tenPayV3Info.Key); var jsmodel = new WeixinJsPaySignature { AppId = tenPayV3Info.AppId, Timestamp = timeStamp, NonceStr = nonceStr, Package = string.Format("prepay_id={0}", resultPay.prepay_id), PaySign = paySign, OrderId = data.Number, SignType = "MD5" }; apiResult.Data = jsmodel; return(apiResult); } else { } } else { throw new NotImplementedException(JsonConvert.SerializeObject(resultPay)); } return(apiResult); }
public async Task <ApiResult <WXLoginOutput> > Login([FromUri] string code, CancellationToken cancelToken) { try { var openIdResult = SnsApi.JsCode2Json(GuoGuoCommunity_WxOpenAppId, GuoGuoCommunity_WxOpenAppSecret, code); var user = await _userRepository.GetForOpenIdAsync(new UserDto { OpenId = openIdResult.openid }); if (user == null) { user = await _userRepository.AddWeiXinAsync(new UserDto() { OpenId = openIdResult.openid, UnionId = openIdResult.unionid, OperationTime = DateTimeOffset.Now, OperationUserId = "system" }, cancelToken); } //产生 Token var token = _tokenRepository.Create(user); //存入数据库 await _userRepository.UpdateTokenAsync( new UserDto { Id = user.Id.ToString(), RefreshToken = token.Refresh_token }); var weiXinUser = await _weiXinUserRepository.GetAsync(openIdResult.unionid, cancelToken); /* * 一期只有一个认证 */ var ownerCertificationList = await _ownerCertificationRecordRepository.GetListAsync(new OwnerCertificationRecordDto() { UserId = user.Id.ToString() }); //var isVipOwner = false; //if (ownerCertificationList.Any()) //{ // var vipOwner = await _vipOwnerRepository.GetForSmallDistrictIdAsync(new VipOwnerDto { SmallDistrictId = ownerCertificationList.FirstOrDefault().Industry.BuildingUnit.Building.SmallDistrictId.ToString() }); // if (vipOwner != null) // { // var vipOwnerCertificationRecord = await _vipOwnerCertificationRecordRepository.GetForVipOwnerIdAsync(new VipOwnerCertificationRecordDto // { // VipOwnerId = vipOwner.Id.ToString(), // UserId = user.Id.ToString() // }); // if (vipOwnerCertificationRecord != null) // { // isVipOwner = true; // } // } //} return(new ApiResult <WXLoginOutput>(APIResultCode.Success, new WXLoginOutput() { OpenId = user.OpenId, Token = token.Access_token, Headimgurl = weiXinUser?.Headimgurl, Nickname = weiXinUser?.Nickname, IsSubscription = weiXinUser == null ? false : true, IsOwner = ownerCertificationList.Any(), //IsVipOwner = isVipOwner }, APIResultMessage.Success)); } catch (Exception e) { return(new ApiResult <WXLoginOutput>(APIResultCode.Success_NoB, new WXLoginOutput() { }, e.Message)); } }
public ApiResult <string> GetOpenId([FromUri] string code) { var openIdResult = SnsApi.JsCode2Json(GuoGuoCommunity_WxOpenAppId, GuoGuoCommunity_WxOpenAppSecret, code); return(new ApiResult <string>(APIResultCode.Success, openIdResult.openid)); }