Xero Accounting Sdk Core: authentication error - c#

I'm implementing an internal procedure to generate invoices from my database. In using .NET Core. I installed the Xero.Api.SDK.Core v. 1.1.4
I find the Xero documentation quite difficult to understand and a bit up to date. I took a look to the Github repository and they refer only to OAuth 2.0. In my case I don't want any user interaction because I want a background process.
I created an account as developer and a demo company for test.
I googled a bit and I found in a site an example how to connect to the api (I couldn't find any details in the Xero documentation).
X509Certificate2 cert = new X509Certificate2(#"public_privatekey.pfx", "password");
var api = new Xero.Api.Example.Applications.Private.PrivateAuthenticator(cert);
var private_app_api = new XeroCoreApi("https://api.xero.com",
new PrivateAuthenticator(cert),
new Consumer("ClientId", "ClientSecret"),
null, null);
Now, I thought, I should use the api. I tried to read the list of contacts:
var contacts = private_app_api.Contacts;
var list = contacts.FindAsync().Result;
The result is the following error:
System.AggregateException: 'One or more errors occurred. (oauth_problem=consumer_key_unknown&oauth_problem_advice=Consumer%20key%20was%20not%20recognised)'
Inner Exception
UnauthorizedException: oauth_problem=consumer_key_unknown&oauth_problem_advice=Consumer%20key%20was%20not%20recognised
Then, I downloaded the repository from Github. I copy and paste the ClientId and ClientSecret and run the tests. No one test is passed!
My goal is to create a contact or find one in the list, create an invoice and save the invoice in PDF format in my storage.
How can I do that? Is there any example for that?
PS: In the developer forum the login doesn't work and the Postman collection is old and it doesn't either.
Update
I was desperate. I tried to connect to the apis in another way with XOauth. Worst. I created the connection as Xero explains on Github.
When I try to connect with
xoauth connect
a new tab in my browser is opened and...
Postman Update
I followed the steps with Postman. I opened the collection in my Postman. In the environment I updated client_id and client_secret from the Xero Developer site and then the following configurations:
re_directURI: https://developer.xero.com
scopes: offline_access profile email accounting.transactions
Auth URL: https://login.xero.com/identity/connect/authorize
Access Token: https://identity.xero.com/connect/token
I opened Get started api, Generate token and I gave the same result.

Honestly, it was quite a mess. I spent more than 2 weeks to understand how to call Xero. I created a post to explain step by step what I have to do.
There were a lot of issues:
understand the Xero documentation because it is not very clear
find the right values to put in the request
translate the Postman request in code
no Xero documentation for that, only a useless bunch of projects
It is quite long to explain everything but for example if you want to read an Organization the code with RestSharp is:
/// <summary>
/// Gets the organizations.
/// </summary>
/// <returns>OrganizationResponse.</returns>
public OrganizationResponse GetOrganizations()
{
var _client = new RestClient("https://api.xero.com/connections");
_client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer " + _settings.AccessToken);
var response = _client.Execute<IList<Organization>>(request);
return response;
}
I'll create other posts to explain how to implement more functions.
I created a NuGet package for that. Source code on Github.

Related

Unauthorize-401 Error ,QuickBooks

Getting Unauthorize-401 Error.
I am working on QuickBooks Integration module .Everything working fine few days back on sandbox-US-company.
Today I created new separate account for sandbox for testing purpose.
For Older Account, Everything is going perfect .But for newly created account Unauthorize-401 issue is coming.
The steps I gone through follow, today:
1. Created account in developer.intuit.com/
2. Under My App, Created new app for Accounting.
3. Under Sandbox, Added US Company.
4. From My Project, Hosted at my localhost .Done OAuth process to collect Access Token and Access Token Secret.
5. Now when I tried to get the list of Customer or (Other intuit object), Getting Unauthorize-401 Error.
Entire system of my project is perfectly working on the sandbox company created earlier.
But for the today configured company, Unauthorize-401 Error is company.
Multiple links i Gone through ,But did't get rid of the issue facing, follows:
Getting “Unauthorized-401” Error in .NET while accessing quickBooks
data through Intuit API
How to fix Unauthorized-401 error
Unauthorized 401
In Advance, I thanks for getting me out from this issue.
CODE :
To Collect the DataService :
private DataService GetDataService()
{
try
{
string accessToken = AppSessions.QBAccessToken,
accessTokenSecret = AppSessions.QBAccessTokenSecret
, consumerKey = AppSessions.QBConsumerKey, consumerSecret = AppSessions.QBConsumerSecret
, realmId = AppSessions.QBCompanyCode;
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
var serviceType = IntuitServicesType.QBO;
var validator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
var context = new ServiceContext(realmId, serviceType, validator);
context.IppConfiguration.BaseUrl.Qbo = AppSessions.IppConfigBaseURL;// "https://sandbox-quickbooks.api.intuit.com/";
return new DataService(context);
}
catch (Exception ex)
{
return null;
}
}
To Get the Customer List from Sandbox US Company :
public List<Customer> GetCustomer()
{
return service.FindAll(new NSQB.Customer(), StartPosition, MaxResult).ToList<NSQB.Customer>();
}
NOTE :
I am using AppSessions static Class to Manage Session .
NSQB is alias for namespace used for QuickBook , i.e.
using NSQB =
Intuit.Ipp.Data;
I discussed with Intuit Team .Quick-book System was in the Maintenance .
One of the response I Had over email by Quick-Books Team:
We had an outage today. Please retry. Do remember to change your base
url to sandbox if you changed your prod keys to dev keys for testing
with sandbox.
Outages cause 401 errors.
Maintenance Link they share about their Status Management.
Issue Still Exists !!
Your code looks fine; when there is a 401 error from QuickBooks Online, there can be two reasons:
The access token is invalid;
The sandbox server is having a problem.
What most developers didn't know is, when there is an outrage on sandbox server, the access token will be reset. It will result a previous working access token become invalid, i.e., the 401 error.
Here below are some steps I found very helpful when you see a 401 error:
Go to Intuit's status page: http://status.developer.intuit.com/ and see if there is any issue with Sandbox server
If you believe the sandbox is not available, go to API explorer: https://developer.intuit.com/v2/apiexplorer?apiname=V3QBO#?id=Account and see if it worked
Try POSTMAN(or simple cUrl), adding the access token, access secrets, consumer secrets and consumer key and make a sample call to see if it can goes through(make sure it is pointing to the sandbox url).
If it didn't go through, and a 401 status code is returned, regenerate the access tokens. The best way to do it for sandbox is using the OAuth Playground. In the dashboard in your app, there is a link called "Test with OAuth Playground and OpenID Playground". Click on the OAuth Playground, change the access token duration from 120 to 15552000 and complete the OAuth flow. Now a new token will be available for you to test.
If neither above works, create a ticket for intuit QuickBooks Online team.

.Net Rally.RestApi error "Not authorized to perform action: Invalid key" when creating Rally test folder

I have a C# application using version 2.0.1.0 of the Rally Rest API for .NET. The application will successfully query Rally for data, but when I try to create an object, an error is returned indicating invalid key. This issue started today and is occurring for multiple users of the application.
I use the following line of code to authenticate.
myRestApi = new RallyRestApi(Rally_username, Rally_password, Rally_URL, "v2.0", myProxy);
I have read some help online indicating the need for a security token, however this note makes me feel like that is not needed: "Note: When using any of the Rally REST Toolkits or the App SDK this will be automatically handled. "
I have tried updating to version 3.0 (Beta), but this does not resolve the problem.
There are reports that using ApiKey instead of basic authentication with username/password resolves the invalid key error.
Rally .NET toolkit supports ApiKey authentication.
The constructor for v2.0.1:
restApi = new RallyRestApi("_abc123","https://rally1.rallydev.com","v2.0");
The constructor for v3.0.1:
restApi.Authenticate("_abc123", "https://rally1.rallydev.com", allowSSO: false);
I was getting the same error and noticed it was not recognizing my username and password that I had stored in the <appSettings> section of Web.config.
For some reason it would not allow them to be read so I decided to store the credentials elsewhere, in Properties => Settings of my app and it has worked ever since.
Here's a code snippet of how the Rally API initialization looks like for me:
RallyRestApi restApi = new RallyRestApi(webServiceVersion: "v2.0");
string user = Properties.Settings.Default.username;
string pass = Properties.Settings.Default.password;
string rallyURL = Properties.Settings.Default.rallyURL;
restApi.Authenticate(user, pass, rallyURL, proxy: null, allowSSO: false);
Hope it helps!

Sharing Moments in GooglePlus from C#

Are there any libraries out there for C# that wrap the process of sharing moments to a user's Google+ account (or to their stream)? I'm looking for something that simply take your ClientId and ClientSecret, and maybe your apiKey along with the user's id to send some text that the user has decided to share with his/her friends.
If not, but you have an example of creating a WebRequest to accomplish the same thing, that would be much appreciated too!
I've reviewed this landing page: https://developers.google.com/+/quickstart/csharp
But I'm trying to integrate into an existing MVC5 application that already has the Auth for GooglePlus taken care of.
The correct client to be using for Google APIs is the Google .NET API Client library, available via NuGet. Additional libraries for specific APIs are required if you use more than the core library. For Plus, you need the Google.Apis.Plus.v1 package.
After you have added it to your projects and have configured an API client, writing app activities is as easy as:
/// <summary>The app activity type for ADD.</summary>
private const string ADD_ACTIVITY_TYPE = #"http://schemas.google.com/AddActivity";
// Construct your Plus Service, I'll assume a helper for here.
PlusService plusService = GetPlusService(credentials);
Moment addMoment = new Moment();
ItemScope target = new ItemScope()
{
Url = ContentUrl
};
addMoment.Type = ADD_ACTIVITY_TYPE;
addMoment.Target = target;
Moment response = null;
try
{
response = plusService.Moments.Insert(addMoment, "me",
MomentsResource.InsertRequest.CollectionEnum.Vault).Execute();
}
catch (System.AggregateException)
{
/* Occurs when the server can't be seen by Google. */
}
catch (Google.GoogleApiException)
{
/* Occurs when the server can't be seen by Google. */
}
How to authenticate a user and authorize your client for access to Google APIs in MVC can be found on this blog: ASP.NET MVC with OpenID and OAuth.
A final note, app activities require you to specify an app activities pseudo-scope (request_visible_actions) which is easier with the Sign-In button than via the framework. If you are getting 401 errors, this is the most likely culprit.

Issue with posting on business page of facebook using c# sdk

I have read many many articles tonight and still do not understood what I shoud do to post on business page of facebook. Here is my code:
string token = getHtml("https://graph.facebook.com/oauth/access_token?client_id=clientID&client_secret=secretKey&grant_type=client_credentials");
token = token.Replace("access_token=", "");
FacebookClient fbClient = new FacebookClient(token);
var args = new Dictionary<string, object>();
args["message"] = "Testing 12qwe3";
fbClient.Post("/pageID/feed", args);
It always says app not authorized. How to authorize it? I read so many articles, but still not able to do it.
I am posting this after totally failing from researching many articles. Kindly let me know whats wrong?
----UPDATE
I did the first part, by making myself the manager page and then creating an app and then providing that app the ability to manage pages and publish etc...but again another issue when i do so even using the above code i still get the same error.But when i use the tools (GRAPH API EXPLORER) portion of facebook site and select this app and generate a token .I than use that directly in app and it posts fine. Kinldy let me know whats wrong!

Google Calendar V3 2 Legged authentication fails

I'm trying to create web page that access the (business) private calendar of the company and insert events if the time slot is available. Still I'm facing an authentication problem.
The API manual states that I should use an API key and Oauth2LeggedAuthenticator, so I did all this and the request that is fired is quite okey (it has a oauth token and such) But still the response is an exception with Invalid Credentials; Easy to say is that my credentials are wrong, still clientID, clientSecret and API Key are valid; I doubt the 2 last params of the 2legged authenticater, is this correct?
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = ClientCredentials.ClientID;
provider.ClientSecret = ClientCredentials.ClientSecret;
var authenticator =
new OAuth2LeggedAuthenticator(ClientCredentials.ClientID, ClientCredentials.ClientSecret, "myworkusername", "workdomain.com");
Google.Apis.Calendar.v3.CalendarService service = new Google.Apis.Calendar.v3.CalendarService(authenticator);
service.Key = ClientCredentials.ApiKey;
var result = service.CalendarList.List().Fetch();
Assert.IsTrue(result.Items.Count > 0);
NB: At the time of writing you can only used 2-legged authentication with Google Apps for Business/Eduction, this won't work on personal accounts as there's no way to get an OAuth 1.0 key/secret pair, you will have to use online authentication at least once (but you can use the out-of-browser option so you don't have to create a dedicated page).
Your code is correct apart from you don't need the first three lines relating to the NativeApplicationClient. This is most likely failing because you haven't properly set the OAuth keys, this causes 401s.
The other thing that causes 401s is using "matt#example.com" instead of "matt" as the username, the username is without including your domain.
To setup OAuth follow the instructions in this article from Google.
The most important parts to note are "Allow access to all APIs" must be unchecked and you have to individually grant access to all the APIs. If this hasn't been done you will get a 401 Invalid Credentials error. You then also need to turn those services on in the api console. If the api console step hasn't been done you will get a different error of 403 Daily Limit Exceeded.
This will cause you problems if you were previously relying on the "Allow access to all APIs" to use various services, you will have to grant them all individually as far as I understand it to use the v3 APIs. This seems to have been confirmed by google (4th reply by Nicolas Garnier) and is supposedly a bug, but that is an old post so it looks as if it's here to stay.
For reference once this has been done, this code will work, which in essence is the same as yours:
var auth = new OAuth2LeggedAuthenticator(domainName, consumerSecret, usernameWithoutDomain, domainName); //domainName is presently used as the OAuth ConsumerKey for Google's 2legged OAuth
var service = new CalendarService(auth);
service.Key = serviceKey;
var results = service.CalendarList.List().Fetch();
Console.WriteLine(results.Items.Count);
So in summary:
In Google Apps "Manage this Domain" > "Advanced Tools"
Using "Manage OAuth domain key" enable key, generate secret, uncheck "Allow access to all APIs".
Using "Manage third party OAuth Client access" enable the APIs you want access to using your domain as "Client Name" and the APIs you want to access e.g. "http://www.google.com/calendar/feeds/" for the calendar.
Then finally create a project in the API console, use the APIKey as the serviceKey in the above example and turn on the APIs you need to access.
I am answering this as I kept hitting this question when I was trying to find out why my code was constantly returning 401s. Hope this helps someone as the Google instructions are awful and scattered all over the place at the moment.

Categories