/// <summary> /// Refreshes your current token /// </summary> /// <param name="xeroToken"></param> /// <returns></returns> public async Task <IXeroToken> RefreshAccessTokenAsync(IXeroToken xeroToken) { if (xeroToken == null) { throw new ArgumentNullException("xeroToken"); } var response = await _httpClient.RequestRefreshTokenAsync(new RefreshTokenRequest { Address = "https://identity.xero.com/connect/token", ClientId = xeroConfiguration.ClientId, ClientSecret = xeroConfiguration.ClientSecret, RefreshToken = xeroToken.RefreshToken }); if (response.IsError) { throw new Exception(response.Error); } xeroToken.AccessToken = response.AccessToken; xeroToken.RefreshToken = response.RefreshToken; xeroToken.IdToken = response.IdentityToken; xeroToken.ExpiresAtUtc = DateTime.UtcNow.AddSeconds(response.ExpiresIn); return(xeroToken); }
public async Task SetToken(IXeroToken xeroToken) { try { var currentToken = (XeroToken)xeroToken; var tokens = await _tokenRepository.Get(t => t.XeroUserId == currentToken.XeroUserId, 0, 1); var tokenSaved = tokens.FirstOrDefault(); if (tokenSaved == null) { currentToken.ObjectId = ObjectId.GenerateNewId().ToString(); await _tokenRepository.Add(currentToken); } else { tokenSaved.AccessToken = currentToken.AccessToken; tokenSaved.RefreshToken = currentToken.RefreshToken; tokenSaved.ExpiresAtUtc = currentToken.ExpiresAtUtc; await _tokenRepository.Update(tokenSaved); } } catch (Exception ex) { throw ex; //or log here } }
/// <summary> /// Convenience method to refresh token for you if it is expired /// </summary> /// <param name="xeroToken">your current XeroToken</param> /// <returns></returns> public async Task <IXeroToken> GetCurrentValidTokenAsync(IXeroToken xeroToken) { if (DateTime.UtcNow > xeroToken.ExpiresAtUtc) { return(await RefreshAccessTokenAsync(xeroToken)); } return(xeroToken); }
public async Task <IXeroToken> GetTokensAsync(string code, string state) { var client = new XeroClient(_xeroConfig, _httpClientFactory); //before getting the access token please check that the state matches _xeroToken = await client.RequestXeroTokenAsync(code); //from here you will need to access your Xero Tenants List <Tenant> tenants = await client.GetConnectionsAsync(_xeroToken); _xeroToken.Tenants = tenants; return(_xeroToken); }
/// <summary> /// Delete the connection given the accesstoken and xero tenant id /// </summary> /// <param name="xeroToken"></param> /// <param name="xeroTenant"></param> /// <returns>List of Tenants attached to accesstoken</returns> public async Task DeleteConnectionAsync(IXeroToken xeroToken, Tenant xeroTenant) { using (var requestMessage = new HttpRequestMessage(HttpMethod.Delete, "https://api.xero.com/connections" + "/" + xeroTenant.id)) { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", xeroToken.AccessToken); var result = await _httpClient.SendAsync(requestMessage); if (result.StatusCode == System.Net.HttpStatusCode.NoContent) { return; } throw new HttpRequestException(await result.Content.ReadAsStringAsync()); } }
/// <summary> /// Get's a list of Tokens given the accesstoken /// </summary> /// <param name="xeroToken"></param> /// <returns>List of Tenants attached to accesstoken</returns> public async Task <List <Tenant> > GetConnectionsAsync(IXeroToken xeroToken) { using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://api.xero.com/connections")) { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", xeroToken.AccessToken); var result = await _httpClient.SendAsync(requestMessage); var json = await result.Content.ReadAsStringAsync(); if (result.StatusCode == System.Net.HttpStatusCode.OK) { xeroToken.Tenants = JsonConvert.DeserializeObject <List <Tenant> >(json); return(xeroToken.Tenants); } throw new HttpRequestException(await result.Content.ReadAsStringAsync()); } }
/// <summary> /// Revokes the current token - immediate disconnect all orgs and stops the user authorisation /// </summary> /// <param name="xeroToken"></param> /// <returns></returns> public async Task RevokeAccessTokenAsync(IXeroToken xeroToken) { if (xeroToken == null) { throw new ArgumentNullException("xeroToken"); } var response = await _httpClient.RevokeTokenAsync(new TokenRevocationRequest { Address = "https://identity.xero.com/connect/revocation", ClientId = xeroConfiguration.ClientId, ClientSecret = xeroConfiguration.ClientSecret, Token = xeroToken.RefreshToken }); if (response.IsError) { throw new Exception(response.Error); } return; }
/// <summary> /// Delete the connection given the accesstoken and xero tenant id /// </summary> /// <param name="xeroToken"></param> /// <param name="xeroTenant"></param> /// <returns>List of Tenants attached to accesstoken</returns> public async Task DeleteConnectionAsync(IXeroToken xeroToken, Tenant xeroTenant) { var client = httpClientFactory.CreateClient("Xero"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", xeroToken.AccessToken); using (var requestMessage = new HttpRequestMessage(System.Net.Http.HttpMethod.Delete, "https://api.xero.com/connections" + "/" + xeroTenant.id)) { HttpResponseMessage result = await client.SendAsync(requestMessage); string json = await result.Content.ReadAsStringAsync(); if (result.StatusCode == System.Net.HttpStatusCode.NoContent) { return; } else { throw new HttpRequestException(await result.Content.ReadAsStringAsync()); } } }
/// <summary> /// Get's a list of Tokens given the accesstoken /// </summary> /// <param name="xeroToken"></param> /// <returns>List of Tenants attached to accesstoken</returns> public async Task <List <Tenant> > GetConnectionsAsync(IXeroToken xeroToken) { var client = httpClientFactory.CreateClient("Xero"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", xeroToken.AccessToken); using (var requestMessage = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, "https://api.xero.com/connections")) { HttpResponseMessage result = await client.SendAsync(requestMessage); string json = await result.Content.ReadAsStringAsync(); if (result.StatusCode == System.Net.HttpStatusCode.OK) { xeroToken.Tenants = JsonConvert.DeserializeObject <List <Tenant> >(json); return(xeroToken.Tenants); } else { throw new HttpRequestException(await result.Content.ReadAsStringAsync()); } } }
public void SetToken(string xeroUserId, IXeroToken xeroToken) { _tokens[xeroUserId] = xeroToken; }
public void Run(string name) { try { Console.WriteLine(name + ": Starting "); var clientId = _config["ClientId"]; XeroClient client = null; IXeroToken token = null; lock (_lockObj) { client = new XeroClient(new XeroConfiguration { ClientId = clientId }); if (System.IO.File.Exists("Token.json")) { var savedJson = System.IO.File.ReadAllText("Token.json"); token = JsonConvert.DeserializeObject <XeroOAuth2Token>(savedJson); } if (token == null) { token = new XeroOAuth2Token { RefreshToken = _config["RefreshToken"] } } ; IXeroToken newToken = Task.Run(() => client.RefreshAccessTokenAsync(token)).GetAwaiter().GetResult(); if (newToken != null) { token = newToken; } var json = JsonConvert.SerializeObject(token, Formatting.Indented); System.IO.File.WriteAllText("Token.json", json); } Console.WriteLine(name + ": Token refreshed"); var accessToken = token.AccessToken; var tenant = ""; try { var conRes = Task.Run(() => client.GetConnectionsAsync(token)).GetAwaiter().GetResult(); tenant = conRes[0].TenantId.ToString(); Console.WriteLine(name + ": Tenants"); } catch (Exception e) { Console.WriteLine(e); SerializeException(e); return; } var api = new AccountingApi { ExceptionFactory = CustomExceptionFactory }; Console.WriteLine(name + ": New token process"); var response = Task.Run(() => api.GetInvoicesAsyncWithHttpInfo(accessToken, tenant)).GetAwaiter().GetResult(); var respInvoices = Task.Run(() => api.GetInvoicesAsyncWithHttpInfo(accessToken, tenant, page: 1, where : "")).GetAwaiter().GetResult(); var invDate = respInvoices.Data._Invoices[0].Date; var recurring = Task.Run(() => api.GetRepeatingInvoicesAsyncWithHttpInfo(accessToken, tenant)).GetAwaiter().GetResult(); var status = recurring.Data._RepeatingInvoices[0].Status; var schedule = recurring.Data._RepeatingInvoices[0].Schedule; Console.WriteLine(name + ": Complete"); } catch (CustomApiException ce) { Console.WriteLine(name + ": Failed: " + ce.Message); SerializeException(ce); Console.WriteLine(ce); var limits = new XeroLimits(ce.Headers); } catch (Exception e) { Console.WriteLine(name + ": Failed: " + e.Message); SerializeException(e); } }