public async Task <AccessTokenEntity> UpdateChannelAccessToken(string identityUid, string channelUid) { if (identityUid is null) { throw new ArgumentNullException(nameof(identityUid)); } if (channelUid is null) { throw new ArgumentNullException(nameof(channelUid)); } var accessTokenEntity = new AccessTokenEntity { Value = GenerateAccessToken(), ValidUntil = DateTime.UtcNow.AddDays(30) }; await _repositoryService.UpdateIdentity(identityUid, e => { if (!e.Channels.TryGetValue(channelUid, out var channel)) { channel = new ChannelEntity(); e.Channels[channelUid] = channel; } channel.AccessToken = accessTokenEntity; }).ConfigureAwait(false); return(accessTokenEntity); }
public string PostMoths(string seriaNo) { string appId = "wx5e9e01270444b4c9"; string appSecret = "52deaa5c1c101b3a90197916e8dd2d82"; string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appId, appSecret); string error = ""; System.Net.CookieContainer cookie = null; string accessTokenJson = HttpRun("GET", "utf-8", url, "", ref cookie, 5000, "", "", "", ref error); if (accessTokenJson.ToLower().IndexOf("errcode") != -1) { return(""); } else { AccessTokenEntity obj = Newtonsoft.Json.JsonConvert.DeserializeObject <AccessTokenEntity>(accessTokenJson); //获取 access_token string _url = string.Format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={0}", obj.access_token); string strURL = _url; System.Net.HttpWebRequest request; request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8"; string json = "{\"scene\":\"" + seriaNo + "\",\"page\":\"pages/index/record_detail/record_detail\",\"width\":280,\"auto_color\":false,\"line_color\":{\"r\":\"26\",\"g\":\"173\",\"b\":\"25\"}}"; byte[] payload = System.Text.Encoding.UTF8.GetBytes(json); request.ContentLength = payload.Length; Stream writer = request.GetRequestStream(); writer.Write(payload, 0, payload.Length); writer.Close(); System.Net.HttpWebResponse response; response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream s; s = response.GetResponseStream(); List <byte> bytes = new List <byte>(); int temp = s.ReadByte(); while (temp != -1) { bytes.Add((byte)temp); temp = s.ReadByte(); } byte[] tt = bytes.ToArray(); string path = HttpContext.Current.Server.MapPath("\\Upload\\"); string curPath = DateTime.Now.ToString("yyyyMMdd") + "\\"; if (Directory.Exists(path + curPath) == false)//如果不存在就创建file文件夹 { Directory.CreateDirectory(path + curPath); } Random Random = new Random(); int Result = Random.Next(1000, 9999); string EditFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + Result + ".jpg"; string fileName = path + curPath + EditFileName; System.IO.File.WriteAllBytes(fileName, tt); return("\\Upload\\" + curPath + EditFileName); } }
private async Task <bool> CanMakeRequestAsync(AccessTokenEntity tokenEntity) { if (tokenEntity is null) { return(false); } var now = DateTime.Now; if (tokenEntity.ExpirationDate <= now || tokenEntity.IsBlocked) { return(false); } var lastUsageLog = await _unitOfWork.AccessTokensLogsRepository.GetLastTokenUsageAsync(tokenEntity.Id); if (lastUsageLog is null) { return(true); } return (now.Ticks - lastUsageLog.RequestDateTime.Ticks >= TimeSpan.TicksPerMinute); // the request to API can be made 1 time per 1 minute }
public string Operation(NameValueCollection parameters) { try { if (ConfigurationHelper.IsLog) { foreach (var item in parameters.AllKeys) { LogCommonHelper.WriteLog(string.Format("参数{0} / 值{1}", item, parameters[item])); } } string[] names = GetNamesOfMustParamter(); foreach (var item in names) { if (parameters[item] == null) { return(string.Format(ConstHelper.ERROR_100003, item)); } } dynamic token = GetAccessToken(parameters); if (token is AccessTokenEntity) { AccessTokenEntity entity = token as AccessTokenEntity; string data = Working(entity.access_token, parameters); try { var model = JsonHelper.Deserialize <ErrorEntity>(data); return(JsonHelper.Serialize(GetErrorChineseMessage(model))); } catch { return(data); } } else if (token is ErrorEntity) { return(JsonHelper.Serialize(GetErrorChineseMessage(token as ErrorEntity))); } else if (token is string) { return(token); } else { LogCommonHelper.WriteLog("Error:" + ConstHelper.ERROR_999998); return(ConstHelper.ERROR_999998); } } catch (Exception ex) { return(string.Format(ConstHelper.ERROR_999999, ex.InnerException.Message)); } }
private async Task <bool> BlockAsync(AccessTokenEntity tokenEntity) { if (tokenEntity.IsBlocked) { return(false); } tokenEntity.IsBlocked = true; return(await _unitOfWork.AccessTokensRepository.UpdateAsync(tokenEntity) && await _unitOfWork.SaveChangesAsync() > 0); }
public int AddEntity(AccessTokenEntity entity) { using (var Conn = new ConnectionFactory().Connection) { string query = "INSERT INTO AccessToken (AccessToken,ExpiresIn,CurrentTime,ResultJson) VALUES (@AccessToken,@ExpiresIn,@CurrentTime,@ResultJson)"; var result = Conn.Execute(query, entity); Conn.Close(); Conn.Dispose(); return(result); } }
/// <summary> /// 保存分类表单(新增、修改) /// </summary> /// <param name="keyValue">主键值</param> /// <param name="token">分类实体</param> /// <returns></returns> public void SaveForm(string keyValue, AccessTokenEntity token) { try { service.SaveForm(keyValue, token); } catch (Exception) { throw; } }
public async Task AddAccessToken(Guid userId, string code) { var entity = new AccessTokenEntity() { UserId = userId, Code = code, Created = DateTime.UtcNow }; userContext.AccessToken.Add(entity); await userContext.SaveChangesAsync(); }
private dynamic RequestNewToken(WxAccountEntity user, string appKey) { int times = 0; AccessTokenEntity entity = null; string data = string.Empty; while (times < 3) { NameValueCollection parameters = new NameValueCollection(); parameters.Add("appid", user.AppId); parameters.Add("secret", user.Secret); parameters.Add("grant_type", user.GrantType); // 发送Token请求 data = GetFromWebRequest(ConstHelper.WEIXIN_ACCESS_TOKEN, "GET", parameters); if (data.Contains("access_token")) { entity = JsonHelper.Deserialize <AccessTokenEntity>(data); break; } else { Thread.Sleep(1000 * 1); times++; } } if (entity != null) { ApplicationHelper.SetValue(appKey, new AccessTokenCacheEntity { AccessToken = entity.access_token, RequstTime = DateTime.Now }); return(entity); } else { if (string.IsNullOrWhiteSpace(data)) { return(JsonHelper.Deserialize <ErrorEntity>(ConstHelper.ERROR_100004)); } else { var model = JsonHelper.Deserialize <ErrorEntity>(data); return(GetErrorChineseMessage(model)); } } }
private dynamic GetAccessToken(NameValueCollection parameters) { string un = parameters["un"]; string unkey = parameters["unkey"]; WxAccountRepository cr = new WxAccountRepository(); var user = cr.FindByExpression(x => x.UserName == un).FirstOrDefault(); if (user == null) { return(ConstHelper.ERROR_100007); } string cryptKey = CryptHelper.MD5(un + user.Token); if (!Equals(unkey, cryptKey)) { return(ConstHelper.ERROR_100007); } string KEY_ACCESS_TOKEN = user.UserName + "ACCESSTOKEN"; if (!ApplicationHelper.Exists(KEY_ACCESS_TOKEN)) { return(RequestNewToken(user, KEY_ACCESS_TOKEN)); } else { AccessTokenCacheEntity accesstoken = ApplicationHelper.GetValue(KEY_ACCESS_TOKEN) as AccessTokenCacheEntity; TimeSpan ts = DateTime.Now - accesstoken.RequstTime; // 提前5秒过期 if (ts.TotalSeconds < (user.ExpiresIn ?? 0) - 5) { AccessTokenEntity entity = new AccessTokenEntity(); entity.access_token = accesstoken.AccessToken; entity.expires_in = user.ExpiresIn ?? 0; return(entity); } else { return(RequestNewToken(user, KEY_ACCESS_TOKEN)); } } }
private async Task <AccessTokenReadDto> ReserveNewTokenAsync(UserEntity user, TokenType type) { var tokenStartEvaluation = DateTime.Now; var tokenLifetime = GetTheExpirationDate(type); var newHashedToken = _tokenEncryptorService.CreateToken(); var newToken = new AccessTokenEntity { ExpirationDate = tokenLifetime, IsBlocked = false, StartEvaluationDate = tokenStartEvaluation, User = user, UserId = user.Id, HashedToken = newHashedToken }; var entity = await _unitOfWork.AccessTokensRepository.AddAsync(newToken); var saveChangesResult = await _unitOfWork.SaveChangesAsync() > 0; if (!saveChangesResult) { _logger.LogWarning($"Database not saved changes when tried to reserve new access tokenEntity. UserId = {user.Id}"); throw new DbUpdateException($"Database not saved changes when tried to reserve new access tokenEntity. UserId = {user.Id}"); } await _emailService.SendAPIAccessTokenAsync(user.Email, newHashedToken); return(new AccessTokenReadDto { ExpirationDate = tokenLifetime, HashedToken = newHashedToken, Id = entity.Id, IsBlocked = false, StartEvaluationDate = tokenStartEvaluation, UserId = user.Id }); }
private IEnumerable <AccessTokenLogReadDto> GetTokenLogsAsync(AccessTokenEntity tokenEntity) => _mapper.Map <IEnumerable <AccessTokenLog>, IEnumerable <AccessTokenLogReadDto> >(tokenEntity?.UsagesLogs ?? Enumerable.Empty <AccessTokenLog>());
public JsonResult WxLogin([FromForm] string code) { DataResult dr = new DataResult(); try { if (string.IsNullOrWhiteSpace(code)) { dr.code = "201"; dr.msg = "参数错误"; return(Json(dr)); } //UserEntity userEntity = userBLL.GetById(10007); //userEntity.account = code; //userBLL.ActionDal.ActionDBAccess.Updateable(userEntity).ExecuteCommand(); AccessTokenEntity accessTokenEntity = WeChat.LoginHelper.GetAccessToken(code); if (!string.IsNullOrWhiteSpace(accessTokenEntity.errcode)) { dr.code = "201"; dr.msg = "获取AccessToken失败"; return(Json(dr)); } AccessTokenEntity accessToken = WeChat.LoginHelper.GetRefreshToken(accessTokenEntity.refresh_token); if (!string.IsNullOrWhiteSpace(accessToken.errcode)) { dr.code = "201"; dr.msg = "获取RefreshToken失败"; return(Json(dr)); } AccessTokenEntity tokenEntity = WeChat.LoginHelper.SetExpiresIn(accessToken); if (string.IsNullOrWhiteSpace(tokenEntity.access_token) || string.IsNullOrWhiteSpace(tokenEntity.openid)) { dr.code = "201"; dr.msg = "续期失败"; return(Json(dr)); } WeChat.WxUserEntity wxUserEntity = WeChat.LoginHelper.GetWxUser(tokenEntity.access_token, tokenEntity.openid); if (string.IsNullOrWhiteSpace(wxUserEntity.openid) || !string.IsNullOrWhiteSpace(wxUserEntity.errcode)) { dr.code = "201"; dr.msg = "获取用户信息失败"; return(Json(dr)); } WxUserBLL wxUserBLL = new WxUserBLL(); Entity.WxUserEntity wxUser = wxUserBLL.GetByOpenId(wxUserEntity.openid); if (wxUser == null) { int rows = CreateWxUser(wxUserEntity); if (rows > 0) { dr.code = "201"; dr.msg = "创建用户失败"; return(Json(dr)); } } Entity.WxUserEntity wx = wxUserBLL.GetByOpenId(wxUserEntity.openid); UserEntity user = userBLL.GetById(wx.userId); UserTokenBLL userTokenBLL = new UserTokenBLL(); UserTokenEntity userTokenEntity = userTokenBLL.GetByUserId(user.userId); UserTokenEntity userToken = new UserTokenEntity(); if (userTokenEntity == null) { userToken = userTokenBLL.Create(user.userId); } else { userToken = userTokenBLL.Update(userTokenEntity); } LoginResult loginResult = new LoginResult(); loginResult.token = userToken.token; loginResult.userEntity = user; dr.code = "200"; dr.data = loginResult; } catch (Exception ex) { dr.code = "999"; dr.msg = ex.Message; } return(Json(dr)); }
public int SaveToken(AccessTokenEntity entity) { return(dal.AddEntity(entity)); }