Example #1
0
        /// <summary>
        /// QBO API Request
        /// </summary>
        public async Task <ActionResult> ApiCallService()
        {
            if (Session["realmId"] != null)
            {
                string realmId = Session["realmId"].ToString();
                try
                {
                    var principal = User as ClaimsPrincipal;
                    OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(principal.FindFirst("access_token").Value);

                    // Create a ServiceContext with Auth tokens and realmId
                    ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);
                    serviceContext.IppConfiguration.MinorVersion.Qbo = "23";

                    // Create a QuickBooks QueryService using ServiceContext
                    QueryService <CompanyInfo> querySvc = new QueryService <CompanyInfo>(serviceContext);
                    CompanyInfo companyInfo             = querySvc.ExecuteIdsQuery("SELECT * FROM CompanyInfo").FirstOrDefault();

                    string output = "Company Name: " + companyInfo.CompanyName + " Company Address: " + companyInfo.CompanyAddr.Line1 + ", " + companyInfo.CompanyAddr.City + ", " + companyInfo.CompanyAddr.Country + " " + companyInfo.CompanyAddr.PostalCode;
                    return(View("ApiCallService", (object)("QBO API call Successful!! Response: " + output)));
                }
                catch (IdsException ex)
                {
                    if (ex.Message == "Unauthorized-401")
                    {
                        // Expired tokens, refresh access token once to get new tokens and try QBO API call again.
                        var principal = User as ClaimsPrincipal;
                        var identity  = User.Identity as ClaimsIdentity;
                        var tokenResp = await auth2Client.RefreshTokenAsync(principal.FindFirst("refresh_token").Value);

                        if (tokenResp.AccessToken != null && tokenResp.RefreshToken != null)
                        {
                            identity.RemoveClaim(principal.FindFirst("access_token"));
                            identity.AddClaim(new Claim("access_token", tokenResp.AccessToken));
                            identity.RemoveClaim(principal.FindFirst("refresh_token"));
                            identity.AddClaim(new Claim("refresh_token", tokenResp.RefreshToken));
                            await ApiCallService();

                            return(View());
                        }
                        else
                        {
                            return(View("ApiCallService", (object)("QBO API call Failed!" + " Error message: " + ex.Message)));
                        }
                    }
                    else
                    {
                        return(View("ApiCallService", (object)("QBO API call Failed!" + " Error message: " + ex.Message)));
                    }
                }
                catch (Exception ex)
                {
                    return(View("ApiCallService", (object)("QBO API call Failed!" + " Error message: " + ex.Message)));
                }
            }
            else
            {
                return(View("ApiCallService", (object)"QBO API call Failed!"));
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            string clientid     = ConfigurationManager.AppSettings["clientid"];
            string clientsecret = ConfigurationManager.AppSettings["clientsecret"];
            string redirectUrl  = ConfigurationManager.AppSettings["redirectUrl"];
            string environment  = ConfigurationManager.AppSettings["appEnvironment"];

            OAuth2Client auth2Client = new OAuth2Client(clientid, clientsecret, redirectUrl, environment);

            List <OidcScopes> scopes = new List <OidcScopes>();

            scopes.Add(OidcScopes.Accounting);
            string authorizeUrl = auth2Client.GetAuthorizationURL(scopes);

            string realmId = "9130348210523456";

            var principal = User as ClaimsPrincipal;
            OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(principal.FindFirst("access_token").Value);

            // Create a ServiceContext with Auth tokens and realmId
            ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);

            serviceContext.IppConfiguration.MinorVersion.Qbo = "51";

            // Create a QuickBooks QueryService using ServiceContext
            QueryService <CompanyInfo> querySvc = new QueryService <CompanyInfo>(serviceContext);
            CompanyInfo companyInfo             = querySvc.ExecuteIdsQuery("SELECT * FROM CompanyInfo").FirstOrDefault();

            string output = "Company Name: " + companyInfo.CompanyName + " Company Address: " + companyInfo.CompanyAddr.Line1 + ", " + companyInfo.CompanyAddr.City + ", " + companyInfo.CompanyAddr.Country + " " + companyInfo.CompanyAddr.PostalCode;
        }
        static void GetInvoice()
        {
            var access_token = "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..LwSTn4HRGxVVQwYR8gCKCA.CgUGG49Xm9AL33-FLxErp8PCWysuLdVhWKVWOsXAdD32ogoZws0hwicnQwgoeI_NuBPOZsEv-TjFxDMblx42udGfW74bfAb9JUr9m94miOSPCuZGsw7LlnOaAEXp4JHQka8SEStVWlGQ_3jGzwygIyaoVF9QmVuExfFBnE0ZXG1AEatZscqLke_BAq-hyi_8hIm5JihrUpVq6qHXfp6XotH4ucakDC8z4U-KORYSVYWgRStQFQy9W2z_-hA1xg-kA1j3vMP4UkfE0292ORpPp_NU-__ZnRyj42OMP71pjTZpCB87dWXPZX9Vt8P7icxnaYQ2ZQL_z_VxDFbRnlOCzxwN7e6ukmZLbo7FTsZjuIgevYE46dF7cHwWJKqnRTsL7addty6DXcscOoM_q5qswlz8So_Klrnn6xNZVcJpF20QdKMK01GPDRyDBciAS1kq-U8CvESKa13F_LKM7_c-6Lmmw0OdMlomLRSc_ljwpuooQmI6GcAl-RZkoiuLR7UtFgdk6L0X99triME1aggWo5hZ0iMPNuUj9SHd-gMMvQl4IyqcZ7MAqNkxVeEDxkPUsgAiHX78eEHBkcfYhrxBEaTf6NEoztKrV8NaATJkLFEifwqy_xc2gKLZdoVpD0t787VDiMhGvlOFi_fSdSPrCrucU0jPR2zhKzfnXjNasXYP3RdxngRtlNO8GGuMvvqf.havdNFIRyLJ2ocADbZtpdg";

            realmId = "123146024163879";
            OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(access_token);

            ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);

            serviceContext.IppConfiguration.BaseUrl.Qbo = "https://sandbox-quickbooks.api.intuit.com/"; //sandbox
                                                                                                        //serviceContext.IppConfiguration.BaseUrl.Qbo = "https://quickbooks.api.intuit.com/";//prod

            serviceContext.IppConfiguration.Message.Request.SerializationFormat  = Intuit.Ipp.Core.Configuration.SerializationFormat.Xml;
            serviceContext.IppConfiguration.Message.Response.SerializationFormat = Intuit.Ipp.Core.Configuration.SerializationFormat.Xml;
            serviceContext.IppConfiguration.MinorVersion.Qbo = "8";

            //serviceContext.IppConfiguration.Logger.RequestLog.EnableRequestResponseLogging = true;
            //serviceContext.IppConfiguration.Logger.RequestLog.ServiceRequestLoggingLocation = @"C:\Users\nshrivastava\Documents\Logs";
            //serviceContext.RequestId = "897kjhjjhkh9";

            DataService commonServiceQBO = new DataService(serviceContext);

            Intuit.Ipp.Data.Item   item      = new Intuit.Ipp.Data.Item();
            List <Item>            results   = commonServiceQBO.FindAll <Item>(item, 1, 1).ToList <Item>();
            QueryService <Invoice> inService = new QueryService <Invoice>(serviceContext);
            Invoice In = inService.ExecuteIdsQuery("SELECT * FROM Invoice").FirstOrDefault();
        }
Example #4
0
        public void MyTestInitializer()
        {
            // OAuthRequestValidator oAuthRequestValidatorQbo = new OAuthRequestValidator(ValidAccessToken, ValidAccessTokenSecret,ValidConsumerKey, ValidConsumerSecret);
            OAuth2RequestValidator oAuthRequestValidatorQbo = new OAuth2RequestValidator(ValidAccessToken);

            qboContextOAuth = new ServiceContext(realmIAQBO, IntuitServicesType.QBO, oAuthRequestValidatorQbo);
        }
Example #5
0
        public void PlatformDisconnectValidOauth(String oauthtoken, String oauthtokensecret)
        {
            //try
            //{
            //     PlatformService.PlatformService.Disconnect(ValidConsumerKey, ValidConsumerSecret,
            //          oauthtoken, oauthtokensecret);
            //}
            //catch (PlatformException pex)
            //{
            //    Console.WriteLine("PlatformDisconnect throw PlatformException errCode:" + pex.ErrorCode + " errMsg:" + pex.ErrorMessage + " serverTime:" + pex.ServerTime);
            //     Assert.Fail();
            //}

            //OAuthRequestValidator ioAuthRequestValidatorQbo = new OAuthRequestValidator(oauthtoken, oauthtokensecret, ValidConsumerKey, ValidConsumerSecret);
            OAuth2RequestValidator ioAuthRequestValidatorQbo = new OAuth2RequestValidator(ValidAccessToken);
            ServiceContext         iqboContextOAuth          = new ServiceContext(realmIAQBO, IntuitServicesType.QBO, ioAuthRequestValidatorQbo);
            Customer customer = QBOHelper.CreateCustomer(iqboContextOAuth);

            try
            {
                Customer added = Helper.Add <Customer>(iqboContextOAuth, customer);
            }
            catch (InvalidTokenException e)
            {
                Assert.AreEqual("Unauthorized-401", e.Message);
                return;
            }
            Assert.Fail();
        }
        /// <summary>
        /// Test QBO api call
        /// </summary>

        /// <param name="apiCallFunction"></param>
        public async System.Threading.Tasks.Task QBOApiCall(Action <ServiceContext> apiCallFunction)
        {
            OAuth2Client oauthClient = new OAuth2Client(OAuth2Keys.ClientId, OAuth2Keys.ClientSecret, OAuth2Keys.RedirectUrl, OAuth2Keys.Environment);

            Token token = await _tokens.Token.FirstOrDefaultAsync(t => t.RealmId == OAuth2Keys.RealmId);

            try
            {
                if (OAuth2Keys.RealmId != "")
                {
                    if (token.AccessToken != null && token.RealmId != null)
                    {
                        OAuth2RequestValidator        reqValidator          = new OAuth2RequestValidator(token.AccessToken);
                        JsonFileConfigurationProvider configurationProvider = new JsonFileConfigurationProvider(Directory.GetCurrentDirectory() + "\\appsettings.json");
                        ServiceContext context = new ServiceContext(token.RealmId, IntuitServicesType.QBO, reqValidator, configurationProvider);
                        apiCallFunction(context);
                    }
                }
            }
            catch (IdsException ex)
            {
                if (ex.Message == "Unauthorized-401")
                {
                    var tokens = await oauthClient.RefreshTokenAsync(token.RefreshToken);

                    if (tokens.AccessToken != null && tokens.RefreshToken != null)
                    {
                        await  UpdateTokens(token.RealmId, tokens.AccessToken, tokens.RefreshToken);
                        await QBOApiCall(apiCallFunction);
                    }
                }
            }
        }
Example #7
0
        /// <summary>
        /// QBO API Request
        /// </summary>
        public ActionResult ApiCallService()
        {
            if (Session["realmId"] != null)
            {
                string realmId = Session["realmId"].ToString();
                try
                {
                    var principal = User as ClaimsPrincipal;
                    OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(principal.FindFirst("access_token").Value);

                    // Create a ServiceContext with Auth tokens and realmId
                    ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);
                    serviceContext.IppConfiguration.MinorVersion.Qbo = "23";

                    // Create a QuickBooks QueryService using ServiceContext
                    QueryService <CompanyInfo> querySvc = new QueryService <CompanyInfo>(serviceContext);
                    CompanyInfo companyInfo             = querySvc.ExecuteIdsQuery("SELECT * FROM CompanyInfo").FirstOrDefault();

                    string output = "Company Name: " + companyInfo.CompanyName + " Company Address: " + companyInfo.CompanyAddr.Line1 + ", " + companyInfo.CompanyAddr.City + ", " + companyInfo.CompanyAddr.Country + " " + companyInfo.CompanyAddr.PostalCode;
                    return(View("ApiCallService", (object)("QBO API call Successful!! Response: " + output)));
                }
                catch (Exception ex)
                {
                    return(View("ApiCallService", (object)("QBO API call Failed!" + " Error message: " + ex.Message)));
                }
            }
            else
            {
                return(View("ApiCallService", (object)"QBO API call Failed!"));
            }
        }
Example #8
0
        public ActionResult AddVendor(VendorModel objVendorModel)
        {
            if (Session["realmId"] != null)
            {
                string realmId = Session["realmId"].ToString();
                try
                {
                    string AccessToken = Session["access_token"].ToString();
                    var    principal   = User as ClaimsPrincipal;
                    OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(AccessToken);

                    // Create a ServiceContext with Auth tokens and realmId
                    ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);
                    serviceContext.IppConfiguration.MinorVersion.Qbo = "23";
                    DataService commonServiceQBO = new DataService(serviceContext);
                    // Create a QuickBooks QueryService using ServiceContext

                    PhysicalAddress vendorAddr   = new PhysicalAddress();
                    EmailAddress    vendoremail  = new EmailAddress();
                    TelephoneNumber mobileNumber = new TelephoneNumber();
                    WebSiteAddress  websiteaddr  = new WebSiteAddress();
                    Vendor          vendor       = new Vendor();
                    //Mandatory Fields
                    vendor.GivenName  = objVendorModel.FirstName;
                    vendor.Title      = objVendorModel.Title;
                    vendor.MiddleName = objVendorModel.MiddleName;
                    vendor.FamilyName = objVendorModel.LastName;
                    vendor.AcctNum    = objVendorModel.AccountNo;

                    vendor.Balance     = Convert.ToDecimal(objVendorModel.BalanceAmount);
                    vendor.CompanyName = objVendorModel.Company;

                    vendorAddr.City             = objVendorModel.City;
                    vendorAddr.Country          = objVendorModel.Country;
                    vendoremail.Address         = objVendorModel.Email;
                    mobileNumber.FreeFormNumber = objVendorModel.MobileNumber;
                    websiteaddr.URI             = objVendorModel.Website;

                    vendor.BillAddr         = vendorAddr;
                    vendor.PrimaryEmailAddr = vendoremail;
                    vendor.Mobile           = mobileNumber;
                    vendor.WebAddr          = websiteaddr;
                    Vendor resultVendor = commonServiceQBO.Add(vendor) as Vendor;
                    QueryService <Vendor> querySvcVendor = new QueryService <Vendor>(serviceContext);
                    List <Vendor>         vendorListData = querySvcVendor.ExecuteIdsQuery("SELECT * FROM Vendor").OrderByDescending(x => x.Id).ToList();
                    var    tt             = vendorListData.FirstOrDefault();
                    Vendor resultCustomer = commonServiceQBO.FindById(tt) as Vendor;
                    return(RedirectToAction("VendorList", "VendorQuickBook"));
                }
                catch (Exception ex)
                {
                    return(View("ApiCallService", (object)("QBO API call Failed!" + " Error message: " + ex.Message)));
                }
            }
            else
            {
                return(View("ApiCallService", (object)"QBO API call Failed!"));
            }
        }
Example #9
0
        internal static ServiceContext InitializeQBOServiceContextUsingoAuth()
        {
            if (counter == 0)
            {
                //if(tokenDict.Count == 0)
                Initialize();
            }
            else
            {
                //Load the second json file
                FileInfo fileinfo = new FileInfo(AuthorizationKeysQBO.tokenFilePath);
                string   jsonFile = File.ReadAllText(fileinfo.FullName);
                var      jObj     = JObject.Parse(jsonFile);
                AuthorizationKeysQBO.accessTokenQBO  = jObj["Oauth2Keys"]["AccessToken"].ToString();
                AuthorizationKeysQBO.refreshTokenQBO = jObj["Oauth2Keys"]["RefreshToken"].ToString();
            }

            ServiceContext         context      = null;
            OAuth2RequestValidator reqValidator = null;

            try
            {
                reqValidator = new OAuth2RequestValidator(AuthorizationKeysQBO.accessTokenQBO);
                context      = new ServiceContext(AuthorizationKeysQBO.realmIdIAQBO, IntuitServicesType.QBO, reqValidator);
                context.IppConfiguration.MinorVersion.Qbo = "54";
                context.IppConfiguration.BaseUrl.Qbo      = "https://sandbox-quickbooks.api.intuit.com/";
                DataService.DataService service = new DataService.DataService(context);
                var compinfo = service.FindAll <CompanyInfo>(new CompanyInfo());

                //Add a dataservice call to check 401

                return(context);
            }
            catch (IdsException ex)
            {
                if (ex.Message == "Unauthorized-401")
                {
                    //oauthClient = new OAuth2Client(AuthorizationKeysQBO.clientIdQBO, AuthorizationKeysQBO.clientSecretQBO, AuthorizationKeysQBO.redirectUrl, AuthorizationKeysQBO.appEnvironment);
                    //var tokenResp = oauthClient.RefreshTokenAsync(AuthorizationKeysQBO.refreshTokenQBO).Result;
                    //if (tokenResp.AccessToken != null && tokenResp.RefreshToken != null)
                    //{
                    //    FileInfo fileinfo = new FileInfo(AuthorizationKeysQBO.tokenFilePath);
                    //    string jsonFile = File.ReadAllText(fileinfo.FullName);
                    //    var jObj = JObject.Parse(jsonFile);
                    //    jObj["Oauth2Keys"]["AccessToken"] = tokenResp.AccessToken;
                    //    jObj["Oauth2Keys"]["RefreshToken"] = tokenResp.RefreshToken;

                    //    string output = JsonConvert.SerializeObject(jObj, Formatting.Indented);
                    //    File.WriteAllText(fileinfo.FullName, output);

                    var serviceContext = Helper.GetNewTokens_ServiceContext();
                    return(serviceContext);
                }
                else
                {
                    throw;
                }
            }
        }
        public void OAuthRequestValidatorConstructorTestWithApplicationToken()
        {
            string applicationToken = ConfigurationManager.AppSettings["ApplicationToken"];

            OAuth2RequestValidator target = new OAuth2RequestValidator(applicationToken);

            Assert.AreEqual(target.AccessToken, null);
        }
Example #11
0
        /// <summary>
        /// Test QBO api call
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="refresh_token"></param>
        /// <param name="realmId"></param>
        /// <returns></returns>
        public async System.Threading.Tasks.Task qboApiCall(string access_token, string refresh_token, string realmId)
        {
            try
            {
                if (realmId != "")
                {
                    output("Making QBO API Call.");

                    OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(access_token);

                    ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);
                    serviceContext.IppConfiguration.BaseUrl.Qbo = "https://sandbox-quickbooks.api.intuit.com/"; //sandbox
                                                                                                                //serviceContext.IppConfiguration.BaseUrl.Qbo = "https://quickbooks.api.intuit.com/";//prod

                    serviceContext.IppConfiguration.Message.Request.SerializationFormat  = Intuit.Ipp.Core.Configuration.SerializationFormat.Xml;
                    serviceContext.IppConfiguration.Message.Response.SerializationFormat = Intuit.Ipp.Core.Configuration.SerializationFormat.Xml;
                    serviceContext.IppConfiguration.MinorVersion.Qbo = "8";


                    //serviceContext.IppConfiguration.Logger.RequestLog.EnableRequestResponseLogging = true;
                    //serviceContext.IppConfiguration.Logger.RequestLog.ServiceRequestLoggingLocation = @"C:\Users\nshrivastava\Documents\Logs";
                    //serviceContext.RequestId = "897kjhjjhkh9";

                    DataService            commonServiceQBO = new DataService(serviceContext);
                    Intuit.Ipp.Data.Item   item             = new Intuit.Ipp.Data.Item();
                    List <Item>            results          = commonServiceQBO.FindAll <Item>(item, 1, 1).ToList <Item>();
                    QueryService <Invoice> inService        = new QueryService <Invoice>(serviceContext);
                    Invoice In = inService.ExecuteIdsQuery("SELECT * FROM Invoice").FirstOrDefault();

                    output("QBO call successful.");
                    lblQBOCall.Visible = true;
                    lblQBOCall.Text    = "QBO Call successful";
                }
            }
            catch (IdsException ex)
            {
                if (ex.Message == "UnAuthorized-401" || ex.Message == "The remote server returned an error: (401) Unauthorized.")
                {
                    output("Invalid/Expired Access Token.");
                    //if you get a 401 token expiry then perform token refresh
                    await performRefreshToken(refresh_token);

                    if ((dictionary.ContainsKey("accessToken")) && (dictionary.ContainsKey("accessToken")) && (dictionary.ContainsKey("realmId")))
                    {
                        await qboApiCall(dictionary["accessToken"], dictionary["refreshToken"], dictionary["realmId"]);
                    }
                }
                else
                {
                    output(ex.Message);
                }
            }
            catch (Exception ex)
            {
                //Check Status Code 401 and then
                output("Invalid/Expired Access Token.");
            }
        }
Example #12
0
        protected void GetPayments()
        {
            //Now assuming authentication successed, we can proceed with querying the API
            if (dictionary.ContainsKey("accessToken") && dictionary.ContainsKey("realmId"))
            {
                try
                {
                    OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(dictionary["accessToken"]);
                    ServiceContext         serviceContext = new ServiceContext(dictionary["realmId"], IntuitServicesType.QBO, oauthValidator);
                    serviceContext.IppConfiguration.BaseUrl.Qbo      = "https://sandbox-quickbooks.api.intuit.com/";
                    serviceContext.IppConfiguration.MinorVersion.Qbo = "29";

                    QueryService <Payment> pService = new QueryService <Payment>(serviceContext);

                    payments = pService.ExecuteIdsQuery("SELECT * from Payment");

                    JArray jPayments = new JArray();
                    for (int i = 0; i < payments.Count; i++)
                    {
                        JObject jp = new JObject(new JProperty("key", payments[i].Id),
                                                 new JProperty("customer", payments[i].CustomerRef.name),
                                                 new JProperty("value", payments[i].TotalAmt),
                                                 new JProperty("TxnDate", payments[i].TxnDate));
                        jPayments.Add(jp);
                    }

                    File.WriteAllText(Server.MapPath("/Payments.json"), jPayments.ToString());

                    // write JSON directly to a file
                    using (StreamWriter file = File.CreateText(Server.MapPath("/Payments.json")))
                        using (JsonTextWriter writer = new JsonTextWriter(file))
                        {
                            jPayments.WriteTo(writer);
                        }
                }
                catch (IdsException ex)
                {
                    if (ex.Message == "Unauthorized-401")
                    {
                        output("Invalid/Expired Access Token.");
                    }
                    else
                    {
                        output(ex.Message);
                    }
                }
                catch (IOException ex)
                {
                    //just ignore for now - it will just use the last saved file instead
                }
            }
            else
            {
                output("Access token not found.");
            }
        }
        public void OAuthRequestValidatorConstructorTest()
        {
            ServiceContext context     = Initializer.InitializeServiceContextQbo();
            string         accessToken = AuthorizationKeysQBO.accessTokenQBO;
            //DataService.DataService service = new DataService.DataService(context);

            OAuth2RequestValidator target = new OAuth2RequestValidator(accessToken);

            Assert.AreEqual(target.AccessToken, accessToken);
        }
        public static ServiceContext InitializeServiceContextQbo()
        {
            if (counter == 0)
            {
                Initialize();
            }
            else
            {
                //Load the second json file
                Logger.WriteLog("Entry3");
                FileInfo fileinfo = new FileInfo(AuthorizationKeyQbo.tokenFilePath);
                string   jsonFile = File.ReadAllText(fileinfo.FullName);
                var      jObj     = JObject.Parse(jsonFile);
                AuthorizationKeyQbo.accessTokenQBO  = jObj["Oauth2Keys"]["AccessToken"].ToString();
                AuthorizationKeyQbo.refreshTokenQBO = jObj["Oauth2Keys"]["RefreshToken"].ToString();
            }

            ServiceContext         context      = null;
            OAuth2RequestValidator reqValidator = null;

            try
            {
                reqValidator = new OAuth2RequestValidator(AuthorizationKeyQbo.accessTokenQBO);
                context      = new ServiceContext(AuthorizationKeyQbo.realmIdIAQBO, IntuitServicesType.QBO, reqValidator);
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                context.IppConfiguration.BaseUrl.Qbo = "https://quickbooks.api.intuit.com/";
                //context.IppConfiguration.MinorVersion.Qbo = "37";
                var service  = new DataService(context);
                var compinfo = service.FindAll <CompanyInfo>(new CompanyInfo());
                Logger.WriteLog("Entry5");
                return(context);
            }
            catch (IdsException ex)
            {
                if (ex.Message == "Unauthorized-401")
                {
                    counter++;
                    if (counter < 4)
                    {
                        Logger.WriteLog("Entry4");
                        var serviceContext11 = Helper.GetNewTokens_ServiceContext();
                        return(serviceContext11);
                    }
                    else
                    {
                        throw;
                    }
                }
                else
                {
                    throw;
                }
            }
        }
Example #15
0
        internal static ServiceContext GetServiceContext(ClaimsPrincipal principal, string realmId)
        {
            var oauthValidator = new OAuth2RequestValidator(principal.FindFirst("access_token").Value);

            // Create a ServiceContext with Auth tokens and realmId
            var serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);

            serviceContext.IppConfiguration.MinorVersion.Qbo = "23";

            return(serviceContext);
        }
Example #16
0
        //private static void Initialize()
        //{


        //}

        public ServiceContext InitializeQBOServiceContextUsingoAuth()
        {
            //Initialize();
            OAuth2RequestValidator reqValidator = new OAuth2RequestValidator(this.accessToken);
            ServiceContext         context      = new ServiceContext(this.realmId, IntuitServicesType.QBO, reqValidator);

            //MinorVersion represents the latest features/fields in the xsd supported by the QBO apis.
            //Read more details here- https://developer.intuit.com/docs/0100_quickbooks_online/0200_dev_guides/accounting/querying_data

            context.IppConfiguration.MinorVersion.Qbo = "12";
            return(context);
        }
Example #17
0
        internal static ServiceContext InitializeServiceContextQbo()
        {
            #region oldcode
            //string accessToken = ConfigurationManager.AppSettings["AccessTokenQBO"];
            //string accessTokenSecret = ConfigurationManager.AppSettings["AccessTokenSecretQBO"];
            //string consumerKey = ConfigurationManager.AppSettings["ConsumerKeyQBO"];
            //string consumerSecret = ConfigurationManager.AppSettings["ConsumerSecretQBO"];
            //string realmId = ConfigurationManager.AppSettings["realmIAQBO"];
            ////OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
            //OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator("bearertoken");
            //ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);
            //return serviceContext;
            #endregion

            if (counter == 0)
            {
                Initialize();
            }
            else
            {
                //Load the second json file
                FileInfo fileinfo = new FileInfo(AuthorizationKeysQBO.tokenFilePath);
                string   jsonFile = File.ReadAllText(fileinfo.FullName);
                var      jObj     = JObject.Parse(jsonFile);
                AuthorizationKeysQBO.accessTokenQBO  = jObj["Oauth2Keys"]["AccessToken"].ToString();
                AuthorizationKeysQBO.refreshTokenQBO = jObj["Oauth2Keys"]["RefreshToken"].ToString();
            }

            ServiceContext         context      = null;
            OAuth2RequestValidator reqValidator = null;
            try
            {
                reqValidator = new OAuth2RequestValidator(AuthorizationKeysQBO.accessTokenQBO);
                context      = new ServiceContext(AuthorizationKeysQBO.realmIdIAQBO, IntuitServicesType.QBO, reqValidator);
                context.IppConfiguration.MinorVersion.Qbo = "43";
                DataService.DataService service = new DataService.DataService(context);
                var compinfo = service.FindAll <CompanyInfo>(new CompanyInfo());
                return(context);
            }
            catch (IdsException ex)
            {
                if (ex.Message == "Unauthorized-401")
                {
                    var serviceContext11 = Helper.GetNewTokens_ServiceContext();
                    return(serviceContext11);
                }
                else
                {
                    throw;
                }
            }
        }
        /// <summary>
        /// Intialize servicecontext
        /// </summary>
        /// <param name="realmId"></param>
        /// <returns></returns>
        public ServiceContext IntializeContext(string realmId)
        {
            var principal = User as ClaimsPrincipal;
            OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(principal.FindFirst("access_token").Value);
            ServiceContext         serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);

            //Enable minorversion
            serviceContext.IppConfiguration.MinorVersion.Qbo = "23";
            //Enable logging
            //serviceContext.IppConfiguration.Logger.RequestLog.EnableRequestResponseLogging = true;
            //serviceContext.IppConfiguration.Logger.RequestLog.ServiceRequestLoggingLocation = @"C:\IdsLogs";//Create a folder in your drive first
            return(serviceContext);
        }
 public void ServiceContextConstructorWithAppTokenForQBOTest()
 {
     try
     {
         //OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessTokenQbo, accessTokenSecretQbo, consumerKeyQbo, consumerSecretQbo);
         OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator("bearertoken");
         ServiceContext         context        = new ServiceContext(appTokenQbo, realmIdIAQbo, IntuitServicesType.QBO, oauthValidator);
     }
     catch (System.Exception ex)
     {
         Assert.Fail(ex.Message);
     }
 }
        public void OAuthRequestValidatorConstructorTestConsumerSecretEmpty()
        {
            string accessToken = "accessToken";

            try
            {
                OAuth2RequestValidator target = new OAuth2RequestValidator(accessToken);
                Assert.Fail();
            }
            catch (InvalidTokenException)
            {
            }
        }
        public void OAuthRequestValidatorConstructorTestAccessTokenNull()
        {
            string accessTokenSecret = string.Empty;

            try
            {
                OAuth2RequestValidator target = new OAuth2RequestValidator(null);
                Assert.Fail();
            }
            catch (InvalidTokenException)
            {
            }
        }
        /// <summary>
        /// Test QBO api call
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="refresh_token"></param>
        /// <param name="realmId"></param>
        /// <param name="apiCallFunction"></param>
        public async System.Threading.Tasks.Task QBOApiCall(Action <ServiceContext> apiCallFunction)
        {
            try
            {
                if (realmId != "")
                {
                    output("Making QBO API Call.");

                    if (dictionary["accessToken"] != null && dictionary["realmId"] != null)
                    {
                        OAuth2RequestValidator reqValidator = new OAuth2RequestValidator(dictionary["accessToken"]);
                        ServiceContext         context      = new ServiceContext(dictionary["realmId"], IntuitServicesType.QBO, reqValidator);
                        context.IppConfiguration.MinorVersion.Qbo = "24";
                        apiCallFunction(context);
                    }
                    else
                    {
                        output("Access token not found.");
                    }
                }
            }
            catch (IdsException ex)
            {
                if (ex.Message == "Unauthorized-401")
                {
                    output("Invalid/Expired Access Token.");

                    var tokenResp = await oauthClient.RefreshTokenAsync(dictionary["refreshToken"]);

                    if (tokenResp.AccessToken != null && tokenResp.RefreshToken != null)
                    {
                        dictionary["accessToken"]  = tokenResp.AccessToken;
                        dictionary["refreshToken"] = tokenResp.RefreshToken;
                        await QBOApiCall(apiCallFunction);
                    }
                    else
                    {
                        output("Error while refreshing tokens: " + tokenResp.Raw);
                    }
                }
                else
                {
                    output(ex.Message);
                }
            }
            catch (Exception ex)
            {
                output("Invalid/Expired Access Token.");
            }
        }
Example #23
0
        // GET: VendorQuickBook
        public ActionResult VendorList()
        {
            if (Session["realmId"] != null)
            {
                string realmId = Session["realmId"].ToString();
                try
                {
                    string AccessToken = Session["access_token"].ToString();
                    if (AccessToken == null)
                    {
                        AccessToken = Session["refresh_token"].ToString();
                    }
                    var principal = User as ClaimsPrincipal;
                    OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(AccessToken);

                    // Create a ServiceContext with Auth tokens and realmId
                    ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);
                    serviceContext.IppConfiguration.MinorVersion.Qbo = "23";
                    DataService commonServiceQBO = new DataService(serviceContext);
                    // Create a QuickBooks QueryService using ServiceContext
                    Vendor vendor = new Vendor();

                    QueryService <Vendor>      querySvc        = new QueryService <Vendor>(serviceContext);
                    List <Vendor>              vendorList      = querySvc.ExecuteIdsQuery("SELECT * FROM Vendor").ToList();
                    QueryService <CompanyInfo> querySvcCompany = new QueryService <CompanyInfo>(serviceContext);
                    List <CompanyInfo>         companyInfo     = querySvcCompany.ExecuteIdsQuery("SELECT * FROM CompanyInfo").ToList();
                    string output     = "";
                    var    vendorData = new List <VendorModel>();
                    vendorData = vendorList.Select(x => new VendorModel()
                    {
                        VendorId   = Convert.ToInt64(x.Id),
                        Title      = x.Title,
                        FirstName  = x.GivenName,
                        MiddleName = x.MiddleName,
                        LastName   = x.FamilyName,
                    }).OrderByDescending(x => x.VendorId).ToList();


                    return(View("VendorList", vendorData));
                }
                catch (Exception ex)
                {
                    return(View("ApiCallService", (object)("QBO API call Failed!" + " Error message: " + ex.Message)));
                }
            }
            else
            {
                return(View("ApiCallService", (object)"QBO API call Failed!"));
            }
        }
        public void AuthorizeWithHeadersTest()
        {
            ServiceContext context = Initializer.InitializeServiceContextQbo();

            DataService.DataService service = new DataService.DataService(context);
            string     requestUri           = "https://appcenter.intuit.com/Developer/Create";
            WebRequest webRequest           = WebRequest.Create(requestUri);

            webRequest.Headers.Add("ContentType", "text/xml");
            OAuth2RequestValidator target = new OAuth2RequestValidator(AuthorizationKeysQBO.accessTokenQBO);

            target.Authorize(webRequest, string.Empty);
            Assert.IsTrue(webRequest.Headers.Count > 0);
        }
Example #25
0
        public void GetResponseInvalidTokenExceptionTest()
        {
            //OAuthRequestValidator validator = new OAuthRequestValidator("adfas", "afd", "adfas", "asdfa");
            OAuth2RequestValidator validator = new OAuth2RequestValidator("bearertoken");
            string            realmId        = AuthorizationKeysQBO.realmIdIAQBO;
            ServiceContext    serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, validator);
            AsyncRestHandler  handler        = new AsyncRestHandler(serviceContext);
            string            resourceUri    = string.Format("v3/company/{0}/customer", serviceContext.RealmId);
            RequestParameters parameters     = new RequestParameters(resourceUri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONXML);

            Intuit.Ipp.Data.Customer customer = new Data.Customer();
            HttpWebRequest           request  = handler.PrepareRequest(parameters, customer);

            this.GetResponseHelper(handler, request, true);
        }
        internal static ServiceContext InitializeServiceContextQbo(string status = null)
        {
            if (counter == 0)
            {
                Initialize();
            }
            else
            {
                //Load the second json file
                FileInfo fileinfo = new FileInfo(AuthorizationKeysQBO.tokenFilePath);
                string   jsonFile = File.ReadAllText(fileinfo.FullName);
                var      jObj     = JObject.Parse(jsonFile);
                AuthorizationKeysQBO.accessTokenQBO  = jObj["Oauth2Keys"]["AccessToken"].ToString();
                AuthorizationKeysQBO.refreshTokenQBO = jObj["Oauth2Keys"]["RefreshToken"].ToString();
            }

            ServiceContext         context      = null;
            OAuth2RequestValidator reqValidator = null;

            try
            {
                if (status == "Invalid")
                {
                    reqValidator = new OAuth2RequestValidator(status);
                }
                else
                {
                    reqValidator = new OAuth2RequestValidator(AuthorizationKeysQBO.accessTokenQBO);
                }
                context = new ServiceContext(AuthorizationKeysQBO.realmIdIAQBO, IntuitServicesType.QBO, reqValidator);
                context.IppConfiguration.MinorVersion.Qbo = "37";
                DataService.DataService service = new DataService.DataService(context);
                var compinfo = service.FindAll <CompanyInfo>(new CompanyInfo());
                return(context);
            }
            catch (IdsException ex)
            {
                if (ex.Message == "Unauthorized-401")
                {
                    var serviceContext11 = Helper.GetNewTokens_ServiceContext();
                    return(serviceContext11);
                }
                else
                {
                    throw;
                }
            }
        }
        public void OAuthRequestValidatorConstructorTestAccessTokenEmpty()
        {
            string accessToken = string.Empty;

            //string accessTokenSecret = string.Empty;
            //string consumerKey = string.Empty;
            //string consumerSecret = string.Empty;
            try
            {
                OAuth2RequestValidator target = new OAuth2RequestValidator(accessToken);
                Assert.Fail();
            }
            catch (InvalidTokenException)
            {
            }
        }
Example #28
0
        public static void CreateService()
        {
            List <OidcScopes> scopes = new List <OidcScopes>();

            scopes.Add(OidcScopes.Accounting);
            OAuth2RequestValidator reqValidator = new OAuth2RequestValidator(AccessToken);

            servicecontext = new ServiceContext(realmId, IntuitServicesType.QBO, reqValidator);

            services = new DataService(servicecontext);
            servicecontext.IppConfiguration.AdvancedLogger.RequestAdvancedLog.EnableSerilogRequestResponseLoggingForConsole     = true;
            servicecontext.IppConfiguration.AdvancedLogger.RequestAdvancedLog.EnableSerilogRequestResponseLoggingForDebug       = true;
            servicecontext.IppConfiguration.AdvancedLogger.RequestAdvancedLog.EnableSerilogRequestResponseLoggingForRollingFile = true;
            servicecontext.IppConfiguration.AdvancedLogger.RequestAdvancedLog.EnableSerilogRequestResponseLoggingForTrace       = true;
            servicecontext.IppConfiguration.AdvancedLogger.RequestAdvancedLog.ServiceRequestLoggingLocationForFile = @"C:\temp\Serilog_log";//Any drive logging location
        }
 public void ServiceContextConstructorWithAppTokenNullAppTokenTest()
 {
     try
     {
         //OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessTokenQbo, accessTokenSecretQbo, consumerKeyQbo, consumerSecretQbo);
         OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator("bearertoken");
         ServiceContext         context        = new ServiceContext(null, realmIdIAQbo, IntuitServicesType.QBO, oauthValidator);
     }
     catch (System.Exception ex)
     {
         if (ex.InnerException == null || ex.InnerException.GetType() != typeof(ArgumentNullException))
         {
             Assert.Fail(ex.ToString());
         }
     }
 }
        public void AuthorizeTest()
        {
            //string accessToken = ConfigurationManager.AppSettings["AccessTokenQBO"];
            //string accessTokenSecret = ConfigurationManager.AppSettings["AccessTokenSecretQBO"];
            //string consumerKey = ConfigurationManager.AppSettings["ConsumerKeyQBO"];
            //string consumerKeySecret = ConfigurationManager.AppSettings["ConsumerSecretQBO"];
            ServiceContext context = Initializer.InitializeServiceContextQbo();

            DataService.DataService service = new DataService.DataService(context);
            string requestUri = "https://appcenter.intuit.com/Developer/Create";

            WebRequest             webRequest = WebRequest.Create(requestUri);
            OAuth2RequestValidator target     = new OAuth2RequestValidator(AuthorizationKeysQBO.accessTokenQBO);

            target.Authorize(webRequest, string.Empty);
            Assert.IsTrue(webRequest.Headers.Count > 0);
        }