// GET: /Authorization/Callback
        public async Task <ActionResult> Callback(string code, string state)
        {
            var serviceProvider   = new ServiceCollection().AddHttpClient().BuildServiceProvider();
            var httpClientFactory = serviceProvider.GetService <IHttpClientFactory>();

            XeroConfiguration XeroConfig = new XeroConfiguration
            {
                ClientId     = ConfigurationManager.AppSettings["XeroClientId"],
                ClientSecret = ConfigurationManager.AppSettings["XeroClientSecret"],
                CallbackUri  = new Uri(ConfigurationManager.AppSettings["XeroCallbackUri"]),
                Scope        = ConfigurationManager.AppSettings["XeroScope"],
                State        = ConfigurationManager.AppSettings["XeroState"]
            };

            var client = new XeroClient(XeroConfig, httpClientFactory);

            var xeroToken = (XeroOAuth2Token)await client.RequestXeroTokenAsync(code);

            List <Tenant> tenants = await client.GetConnectionsAsync(xeroToken);

            Tenant firstTenant = tenants[0];

            TokenUtilities.StoreToken(xeroToken);

            return(RedirectToAction("Index", "OrganisationInfo"));
        }
示例#2
0
        public async Task <IActionResult> CallBack(string code, string session_state)
        {
            XeroConfiguration xconfig = new XeroConfiguration();

            xconfig.ClientId     = "713B16BE2997493E8F3F37AD00400F25";
            xconfig.ClientSecret = "GCu6vvrQ6HFgzWKsOAysK2Q78rtQW_jB_V97sKbGvulKuhib";
            xconfig.CallbackUri  = new Uri("http://localhost:5000/signin-oidc"); //default for standard webapi template
            xconfig.Scope        = "openid profile email files accounting.transactions accounting.contacts offline_access accounting.contacts.read";

            var client = new XeroClient(xconfig, _httpClientFactory);

            //before getting the access token please check that the state matches
            var token = await client.RequestAccessTokenAsync(code);

            XeroEmployeeService.Token  = token;
            XeroEmployeeService.Client = client;
            // //from here you will need to access your Xero Tenants
            // List<Tenant> tenants = await client.GetConnectionsAsync(token);
            //
            // // you will now have the tenant id and access token
            // foreach (Tenant tenant in tenants)
            // {
            //     // do something with your tenant and access token
            //     //client.AccessToken;
            //     //tenant.TenantId;
            // }

            return(Redirect("index.html"));
        }
示例#3
0
 /// <summary>Instantiate the API with a Configuration record already setup</summary>
 /// <param name="config">The configuration record to use <see cref="XeroConfiguration"/></param>
 public API(XeroConfiguration config = null)
 {
     if (config == null)
     {
         throw new ArgumentNullException("Missing XeroConfig");
     }
     if (config != null)
     {
         XeroConfig = config;
     }
     if (XeroConfig.AutoSelectTenant == null)
     {
         XeroConfig.AutoSelectTenant = true;
     }
     if (XeroConfig.codeVerifier == null)
     {
         XeroConfig.codeVerifier = GenerateCodeVerifier();
     }
     _authClient            = new oAuth2();
     _authClient.ParentAPI  = this;
     _authClient.XeroConfig = XeroConfig;
     // Setup the reference to the core wrapper
     AccountingApi = new Api.AccountingApi(this);
     AssetApi      = new Api.AssetApi(this);
     BankFeedsApi  = new Api.BankFeedsApi(this);
     PayrollAuApi  = new Api.PayrollAuApi(this);
     PayrollNzApi  = new Api.PayrollNzApi(this);
     PayrollUkApi  = new Api.PayrollUkApi(this);
     IdentityApi   = new Api.IdentityApi(this);
     ProjectApi    = new Api.ProjectApi(this);
     isConnected   = false;
 }
示例#4
0
        // GET: ContactsInfo
        public async Task <ActionResult> Index()
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            var serviceProvider   = new ServiceCollection().AddHttpClient().BuildServiceProvider();
            var httpClientFactory = serviceProvider.GetService <IHttpClientFactory>();

            XeroConfiguration XeroConfig = new XeroConfiguration
            {
                ClientId     = ConfigurationManager.AppSettings["XeroClientId"],
                ClientSecret = ConfigurationManager.AppSettings["XeroClientSecret"],
                CallbackUri  = new Uri(ConfigurationManager.AppSettings["XeroCallbackUri"]),
                Scope        = ConfigurationManager.AppSettings["XeroScope"],
                State        = ConfigurationManager.AppSettings["XeroState"]
            };

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var AccountingApi = new AccountingApi();
            var response      = await AccountingApi.GetContactsAsync(accessToken, xeroTenantId);

            var contacts = response._Contacts;

            return(View(contacts));
        }
示例#5
0
        private XeroConfiguration GetXeroConfiguration(IServiceProvider provider)
        {
            var xeroConfig = new XeroConfiguration();

            Configuration.GetSection("Values:" + nameof(XeroConfiguration)).Bind(xeroConfig);
            return(xeroConfig);
        }
示例#6
0
 /// <summary>
 /// Constructor, pass in xeroConfig and httpClient to generate the XeroClient. Can be used in conjunction with AddHttpClient extension of ServiceProvider for dependency injection
 /// </summary>
 /// <param name="xeroConfig"></param>
 /// <param name="httpClient"></param>
 /// <param name="authorizeUri"></param>
 /// <param name="tokenUri"></param>
 /// <param name="tokenRevocationUri"></param>
 /// <param name="connectionsUri"></param>
 public XeroClient(XeroConfiguration xeroConfig, HttpClient httpClient, Uri authorizeUri, Uri tokenUri, Uri tokenRevocationUri, Uri connectionsUri)
 {
     xeroConfiguration       = xeroConfig;
     _xeroAuthorizeUri       = new RequestUrl(authorizeUri.ToString());
     _xeroTokenUri           = tokenUri;
     _xeroTokenRevocationUri = tokenRevocationUri;
     _xeroConnectionsUri     = connectionsUri;
     _httpClient             = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
 }
示例#7
0
 /// <summary>
 /// Constructor, pass in xeroConfig and httpClient to generate the XeroClient. Can be used in conjunction with AddHttpClient extension of ServiceProvider for dependency injection
 /// </summary>
 /// <param name="xeroConfig"></param>
 /// <param name="httpClient"></param>
 public XeroClient(XeroConfiguration xeroConfig, HttpClient httpClient)
     : this(
         xeroConfig,
         httpClient,
         new Uri("https://login.xero.com/identity/connect/authorize"),
         new Uri("https://identity.xero.com/connect/token"),
         new Uri("https://identity.xero.com/connect/revocation"),
         new Uri("https://api.xero.com/connections"))
 {
 }
示例#8
0
 public oAuth2(XeroConfiguration xeroConfig)
 {
     XeroConfig = xeroConfig;
     // Setup the Listener client
     responseListener = new LocalHttpListener();
     if (!Timeout.HasValue)
     {
         Timeout = 60;
     }
     HasTimedout = false;
 }
示例#9
0
        public frmSPTExract()
        {
            InitializeComponent();
            RedirectUri = "http://localhost:8888/callback";
            XeroConfiguration xeroConfigTemp = new XeroConfiguration();

            xeroConfigTemp.AppName  = "SPTExtract";
            xeroConfigTemp.ClientId = "56A805C0E65E443ABEC86717DE2A9087";
            xeroConfigTemp.Scope    = Uri.EscapeUriString("offline_access openid profile email accounting.transactions accounting.settings accounting.contacts");
            xeroConfigTemp.State    = "12345678";
            XeroConfig = xeroConfigTemp;
        }
示例#10
0
        public IActionResult Index()
        {
            var xconfig = new XeroConfiguration();

            xconfig.ClientId     = "713B16BE2997493E8F3F37AD00400F25";
            xconfig.ClientSecret = "GCu6vvrQ6HFgzWKsOAysK2Q78rtQW_jB_V97sKbGvulKuhib";
            xconfig.CallbackUri  = new Uri("http://localhost:5000/signin-oidc"); //default for standard webapi template
            xconfig.Scope        = "openid profile email offline_access files accounting.transactions accounting.contacts";

            var client = new XeroClient(xconfig, _httpClientFactory);

            return(Redirect(client.BuildLoginUri()));
        }
示例#11
0
        public async Task <ActionResult> Create(string Name, string EmailAddress)
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            var serviceProvider   = new ServiceCollection().AddHttpClient().BuildServiceProvider();
            var httpClientFactory = serviceProvider.GetService <IHttpClientFactory>();

            XeroConfiguration XeroConfig = new XeroConfiguration
            {
                ClientId     = ConfigurationManager.AppSettings["XeroClientId"],
                ClientSecret = ConfigurationManager.AppSettings["XeroClientSecret"],
                CallbackUri  = new Uri(ConfigurationManager.AppSettings["XeroCallbackUri"]),
                Scope        = ConfigurationManager.AppSettings["XeroScope"],
                State        = ConfigurationManager.AppSettings["XeroState"]
            };

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var contact = new Contact
            {
                Name         = Name,
                EmailAddress = EmailAddress
            };

            var contacts = new Contacts();

            contacts._Contacts = new List <Contact>()
            {
                contact
            };

            var AccountingApi = new AccountingApi();
            var response      = await AccountingApi.CreateContactsAsync(accessToken, xeroTenantId, contacts);

            return(RedirectToAction("Index", "ContactsInfo"));
        }
        // GET: /Authorization
        public ActionResult Index()
        {
            var serviceProvider   = new ServiceCollection().AddHttpClient().BuildServiceProvider();
            var httpClientFactory = serviceProvider.GetService <IHttpClientFactory>();

            XeroConfiguration XeroConfig = new XeroConfiguration
            {
                ClientId     = ConfigurationManager.AppSettings["XeroClientId"],
                ClientSecret = ConfigurationManager.AppSettings["XeroClientSecret"],
                CallbackUri  = new Uri(ConfigurationManager.AppSettings["XeroCallbackUri"]),
                Scope        = ConfigurationManager.AppSettings["XeroScope"],
                State        = ConfigurationManager.AppSettings["XeroState"]
            };

            var client = new XeroClient(XeroConfig, httpClientFactory);

            return(Redirect(client.BuildLoginUri()));
        }
示例#13
0
 /// <summary>
 /// Constructor, pass in xeroConfig to generate the XeroClient. Creates an HttpClient by default to use for requests
 /// </summary>
 /// <param name="xeroConfig"></param>
 public XeroClient(XeroConfiguration xeroConfig) : this(xeroConfig, new HttpClient())
 {
 }
示例#14
0
 /// <summary>
 /// Constructor, pass in xeroConfig and httpClient to generate the XeroClient. Can be used in conjunction with AddHttpClient extension of ServiceProvider for dependency injection
 /// </summary>
 /// <param name="xeroConfig"></param>
 /// <param name="httpClient"></param>
 public XeroClient(XeroConfiguration xeroConfig, HttpClient httpClient)
 {
     xeroConfiguration = xeroConfig;
     _xeroAuthorizeUri = new RequestUrl("https://login.xero.com/identity/connect/authorize");
     _httpClient       = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
 }
示例#15
0
 /// <summary>
 /// Constructor, pass in IHttpFactory to generate the client
 /// </summary>
 /// <param name="XeroConfig"></param>
 /// <param name="httpClientFactory"></param>
 public XeroClient(XeroConfiguration XeroConfig, IHttpClientFactory httpClientFactory)
 {
     this.xeroConfiguration = XeroConfig;
     this.xeroAuthorizeUri  = new RequestUrl("https://login.xero.com/identity/connect/authorize");
     this.httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
 }
示例#16
0
 /// <summary>
 /// Constructor, pass in xeroConfig to generate the XeroClient. Creates an HttpClient by default to use for requests
 /// </summary>
 /// <param name="xeroConfig"></param>
 /// <param name="authorizeUri"></param>
 /// <param name="tokenUri"></param>
 /// <param name="tokenRevocationUri"></param>
 /// <param name="connectionsUri"></param>
 public XeroClient(XeroConfiguration xeroConfig, Uri authorizeUri, Uri tokenUri, Uri tokenRevocationUri, Uri connectionsUri)
     : this(xeroConfig, new HttpClient(), authorizeUri, tokenUri, tokenRevocationUri, connectionsUri)
 {
 }
示例#17
0
        private void LoadAPIConfig()
        {
            if (!isXeroSetup)
            {
                // We can ether save/restore the entire config or just the AccessToken element
                string tokendata = AGenius.UsefulStuff.Utils.ReadTextFile("tokendata.txt");
                UpdateStatus($"Loaded Token");
                XeroClientID = AGenius.UsefulStuff.Utils.ReadTextFile("XeroClientID.txt");
                if (!string.IsNullOrEmpty(tokendata))
                {
                    XeroConfig = Utils.DeSerializeObject <XeroConfiguration>(tokendata.Replace("XeroAPIToken", "AccessTokenSet"));
                    XeroConfig = new XeroConfiguration("tokendata.txt");                                     // Load from a text file
                    XeroConfig = new XeroConfiguration(tokendata.Replace("XeroAPIToken", "AccessTokenSet")); // Load from json string

                    if (XeroConfig.ClientID != XeroClientID)
                    {
                        // Setup New Config
                        XeroConfig = new XeroConfiguration
                        {
                            ClientID    = XeroClientID,
                            CallbackUri = XeroCallbackUri,
                            // Add them this way or see below
                            //Scopes = new List<XeroAuth2API.OAuth2.Model.XeroScope> { XeroAuth2API.OAuth2.Model.XeroScope.accounting_contacts, XeroAuth2API.OAuth2.Model.XeroScope.accounting_transactions },
                            State        = XeroState, // Optional - Not needed for a desktop app
                            codeVerifier = null       // Code verifier will be generated if empty
                        };
                        XeroConfig.AddScope(XeroAuth2API.Model.XeroScope.all);
                        XeroConfig.StoreReceivedScope = true;
                        SaveConfig();
                        UpdateStatus($"Client ID Changed");
                    }
                    else
                    {
                        //// Test the change of scope to force a revoke and re-auth
                        //XeroConfig.StoreReceivedScope = true;
                        //SaveConfig();
                        //UpdateStatus($"Scope Changed");
                    }
                }
                else
                {
                    // Setup New Config
                    XeroConfig = new XeroConfiguration
                    {
                        ClientID    = XeroClientID,
                        CallbackUri = XeroCallbackUri,
                        // Add them this way or see below
                        //Scopes = new List<XeroAuth2API.OAuth2.Model.XeroScope> { XeroAuth2API.OAuth2.Model.XeroScope.accounting_contacts, XeroAuth2API.OAuth2.Model.XeroScope.accounting_transactions },
                        State        = XeroState, // Optional - Not needed for a desktop app
                        codeVerifier = null       // Code verifier will be generated if empty
                    };
                    XeroConfig.AddScope(XeroAuth2API.Model.XeroScope.all);
                    XeroConfig.StoreReceivedScope = true;
                    // Or add idividualy
                    //XeroConfig.AddScope(XeroAuth2API.OAuth2.Model.XeroScope.files);
                    //XeroConfig.AddScope(XeroAuth2API.OAuth2.Model.XeroScope.accounting_transactions);
                    //XeroConfig.AddScope(XeroAuth2API.OAuth2.Model.XeroScope.accounting_reports_read);
                    //XeroConfig.AddScope(XeroAuth2API.OAuth2.Model.XeroScope.accounting_journals_read);
                    //XeroConfig.AddScope(XeroAuth2API.OAuth2.Model.XeroScope.accounting_settings_read);
                    //XeroConfig.AddScope(XeroAuth2API.OAuth2.Model.XeroScope.accounting_contacts);
                    //XeroConfig.AddScope(XeroAuth2API.OAuth2.Model.XeroScope.assets);
                }

                XeroConfig.AccessGrantedHTML = "<h1>ACCESS GRANTED</h1>";

                // Restore saved config
                xeroAPI = new XeroAuth2API.API(XeroConfig);

                SaveConfig();

                if (!SetupApi(tenantName))
                {
                    UpdateStatus($"Failed to Connect");
                    simpleButton1.Enabled = false;
                    button1.Enabled       = false;
                    return; /// Stop doing anything else
                }
                else
                {
                    UpdateStatus($"Ready - Refresh required : {XeroConfig.AccessTokenSet.ExpiresAtUtc.ToString()}");
                    simpleButton1.Enabled = true;
                    button1.Enabled       = true;
                }
                xeroAPI.StatusUpdates += StatusUpdates; // Bind to the status update event

                isXeroSetup = true;
            }
            else
            {
                // Already setup so just reload config
                string tokendata = AGenius.UsefulStuff.Utils.ReadTextFile("tokendata.txt");
                UpdateStatus($"Loaded Token");
                if (!string.IsNullOrEmpty(tokendata))
                {
                    XeroConfig         = DeSerializeObject <XeroConfiguration>(tokendata);
                    xeroAPI.XeroConfig = XeroConfig;
                    SaveConfig();
                }
                bool done = false;
                do
                {
                    try
                    {
                        xeroAPI.InitializeAPI();
                        UpdateStatus($"Initialized");
                        done = true;
                        SaveConfig(); // Ensure the new config (with new tokens are saved)
                    }
                    catch (Exception ex)
                    {
                        UpdateStatus(ex.Message);
                        DialogResult rslt = MessageBox.Show(ex.Message + " Try Again?", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (rslt == DialogResult.No)
                        {
                            done = true;
                        }
                    }
                } while (!done);
            }
        }
示例#18
0
 // Keep client secret and id of different application
 //private string clientId = "8443CF59A93F4F3EABACB7C9662A3036";
 //private string clientSecret = "1euUDCNAuxjbYU5PNyaHT-Nqt4zHzyonc03qkZzkPReqiCa0";
 public XeroService(IOptions <XeroConfiguration> config, IHttpClientFactory httpClientFactory, ILogger <XeroService> logger)
 {
     _logger                 = logger;
     _xeroConfig             = config.Value;
     this._httpClientFactory = httpClientFactory;
 }
示例#19
0
        /// <summary>
        /// DI Configure using Autofac container
        /// </summary>
        /// <param name="builder"></param>
        private void ConfigureAutofacContainer(ContainerBuilder builder)
        {
            builder.Register(activator =>
            {
                var xeroConfig = new XeroConfiguration();

                var config = activator.Resolve <IConfiguration>();
                config.GetSection(nameof(XeroConfiguration)).Bind(xeroConfig);

                return(xeroConfig);
            })
            .AsSelf()
            .SingleInstance();

            // register azure storage account
            builder.Register(activator =>
            {
                var storageAccount = activator.Resolve <StorageAccountProvider>().GetHost();

                return(storageAccount);
            })
            .AsSelf()
            .SingleInstance();

            // register Cosmos DB
            builder.Register(activator =>
            {
                var config           = activator.Resolve <IConfiguration>();
                var connectionString = config["CosmosDB:ConnectionString"];

                var serializerOptions = new CosmosSerializationOptions()
                {
                    IgnoreNullValues     = true,
                    Indented             = false,
                    PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
                };

                var cosmosClientBuilder = new CosmosClientBuilder(connectionString)
                                          .WithSerializerOptions(serializerOptions);

                return(cosmosClientBuilder.Build());
            })
            .AsSelf()
            .SingleInstance();

            // Register all functions that resides in a given namespace
            // The function class itself will be created using autofac
            builder
            .RegisterAssemblyTypes(typeof(Startup).Assembly)
            .InNamespace(typeof(IAzFunc).Namespace ?? string.Empty)
            .AsSelf()                     // Azure Functions core code resolves a function class by itself.
            .InstancePerTriggerRequest(); // This will scope nested dependencies to each function execution

            builder
            .RegisterAssemblyTypes(typeof(Startup).Assembly)
            .InNamespace(typeof(IStorageEnitity).Namespace ?? string.Empty)
            .AsImplementedInterfaces()
            .SingleInstance();     // This will scope nested dependencies to each function execution

            builder
            .RegisterAssemblyTypes(typeof(AccountingApi).Assembly)
            .InNamespace(typeof(AccountingApi).Namespace ?? string.Empty)
            .AsSelf()
            .SingleInstance();

            builder.RegisterType <TokenTable>()
            .As <ITokenStore>()
            .SingleInstance();
        }