Error : Invalid AppID and AppCode for China map - unauthorized

While accessing the China Map Rest API's in postman using the app_id and app_code generated (Free Trial Plan), below response if receieved.
URL: https://2.base.maps.hereapi.cn/maptile/2.1/maptile/newest/normal.day/13/6744/3104/256/png8?app_id=<>&app_code=<>
{
"error": "Unauthorized",
"error_description": "This is not a valid app_id and app_code pair. Please verify that the values are not swapped between the app_id and app_code and the values provisioned by HERE (either by your customer representative or via http://developer.here.com/myapps) were copied correctly into the request."
}
We are blocked with testing China Map . Please let me know what other information is required to be provide to analyse the issue.
Thank you
Regards
Sri Vidhya

Related

API Graph Instagram, Insights, get count likes for user

I want to get the total of like for a user profile, to do this I'm using this endpoint : https://developers.facebook.com/docs/instagram-api/reference/ig-user/insights#lecture:~:text=GET%20/%7Big%2Duser%2Did%7D/insights
I know this metrics is not available in the documentation but when I call the endpoint with a bad metric, the reponse show metrics available and here is the response:
"message": "(#100) metric[0] must be one of the following values: impressions, reach, follower_count,
email_contacts, phone_call_clicks, text_message_clicks, get_directions_clicks, website_clicks,
profile_views, audience_gender_age, audience_locale, audience_country, audience_city, online_followers,
accounts_engaged, total_interactions, likes, comments, shares, saved, replies, engaged_audience_demographics,
reached_audience_demographics, follower_demographics, follows_and_unfollows, profile_links_taps"
https://graph.facebook.com/{ig-user-id}/insights?access_token={access-token}&metric=bad&period=lifetime
As you can see likes is available.
So when I call the endpoint with the metric likes, I get a new error:
"message": "(#100) The following metrics (likes) should be specified with parameter metric_type=total_value"
https://graph.facebook.com/{ig-user-id}/insights?access_token={access-token}&metric=likes&period=lifetime
Then I add the parameter metric_type with value total_value, and I get a new error:
"message": "(#100) Param metric_type on field insights: This param is not valid"
https://graph.facebook.com/{ig-user-id}/insights?access_token={access-token}&metric=likes&period=lifetime&metric_type=total_value
If someone know what i'm doing wrong, it will be a pleasure to get the solution.
Thank's for your responses !

Get ACCESS_TOKEN_SCOPE_INSUFFICIENT error migrating to People API

I have a desktop Java app that I am migrating from Google Contacts API to People API. I have some of it working. For example, I can retrieve contact information. But when I tried to create a new contact, I get the following error:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
POST https://people.googleapis.com/v1/people:createContact
{
"code" : 403,
"details" : [ {
"#type" : "type.googleapis.com/google.rpc.ErrorInfo",
"reason" : "ACCESS_TOKEN_SCOPE_INSUFFICIENT"
} ],
"errors" : [ {
"domain" : "global",
"message" : "Insufficient Permission",
"reason" : "insufficientPermissions"
} ],
"message" : "Request had insufficient authentication scopes.",
"status" : "PERMISSION_DENIED"
}
Here's the relevant code:
protected void createContact() throws Exception {
Credential credential = authorize(PeopleServiceScopes.CONTACTS, "people");
PeopleService service = new PeopleService.Builder(
httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
Person contactToCreate = new Person();
List<Name> names = new ArrayList<Name>();
names.add(new Name().setGivenName("John").setFamilyName("Doe"));
contactToCreate.setNames(names);
Person createdContact = service.people().createContact(contactToCreate).execute();
System.out.println("CREATED Contact: " + createdContact.getNames().get(0).getDisplayName());
}
protected Credential authorize(String scope, String subDir) throws Exception {
File dataStoreDir = new File(System.getProperty("user.home"), ".store/myapp/" + cfg.dataStore + "/" + subDir);
// initialize the transport
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
// initialize the data store factory
dataStoreFactory = new FileDataStoreFactory(dataStoreDir);
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(SyncMgr.class.getResourceAsStream("/client_secrets.json")));
if (clientSecrets.getDetails().getClientId().startsWith("Enter")
|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
System.out.println(
"Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar "
+ "into /client_secrets.json");
System.exit(1);
}
// set up authorization code flow
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets,
Collections.singleton(scope)).setDataStoreFactory(dataStoreFactory).build();
// authorize
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(cfg.gUser);
}
When I first ran it, I had the scope set to CONTACTS_READONLY. And I got the consent screen. But then I changed the scope to CONTACTS when I added the code to create a new contact. And that's when I got the ACCESS_TOKEN_SCOPE_INSUFFICIENT error.
I saw in another post that I need to force your app to reauthorize the user when you change the scope, so that you get the consent screen again. But I'm not sure how to do that. Any suggestions?
Thanks.
UPDATE 1/4/22
I tried Gabriel's suggestion of removing access to the application. After removing access, I ran the application again. This time I got this error on the execute() call:
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
POST https://oauth2.googleapis.com/token
{
"error" : "invalid_grant",
"error_description" : "Token has been expired or revoked."
}
And even the execute() statement that worked before to retrieve contacts is giving the same error now.
My application also used the Calendar API. I didn't touch that code. But when I try to use it, I get the same "invalid_grant" error. What do I do now?
You appear to be using the People.createContact method. If we take a look at the documentation we will see that this method requires a consent to the following scope of permissions from the user
Now if we check your code you apear to be using
Credential credential = authorize(PeopleServiceScopes.CONTACTS, "people");
Which is the exact scope needed. But you oringally had readonly there. So when your code ran the first time the user authorized to the read only scope and not the full contacts scope and your stuck.
The key here is this section of code.
// set up authorization code flow
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets,
Collections.singleton(scope)).setDataStoreFactory(dataStoreFactory).build();
// authorize
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(cfg.gUser);
Kindly note I am not a Java developer I am a .net developer. The libraries are very close and i have been helping with questions this in both languages for years.
dataStoreFactory is where the consent from the user is stored. There should be a json file some where in your directory structure with the users name associated with it this is how your system reloads it. When your code runs it will look for a file in that directory with cfg.gUser name.
There should be a way in the Java client library to force it to rerequest authorization of the user. prompt type force. But i will have to look around to see how to do it in java.
The easiest solution now would be to find that directory and delete the file for the user or just change the users name cfg.gUser to cfg.gUser +"test" or something this will cause the name to change and the file name as well. Forcing it to prompt the user for authorization again.
This time when it requests consent take note which scope of permissions it asks for.
Token has been expired or revoked.
This is probably due to the fact that your refresh tokens are expiring. When your application is in the testing phase the refresh tokens are expired or revoked automatically by google after seven days.
This is something new and something that Google added in the last year or so. Unfortunately the client libraries were not designed to request access again if the refresh token was expired in this manner.
If you are looking to retrieve the consent screen again you can remove access to your application from your account settings by following the steps in this documentation and then try to authorize the app again. As you mentioned, the error received is due to the scope that was granted with authorization was CONTACTS_READONLY instead of CONTACTS when checking the authorization scope for this specific create contacts method.

Getting the OAuth Token from FedEx to use for Track API

I'm trying to get the OAuth Token to get auth access to some of the FedEx APIs ( like Track API for tracking shipments ), but I get a
401 (NOT.AUTHORIZED.ERROR -> "The given client credentials were not valid. Please modify your request and try again") error.
(At the moment, I'm using Postman to try and test the APIs.)
Here is the url I'm using, found provided by FedEx:
https://apis-sandbox.fedex.com/oauth/token
I've followed ( to my understanding ) how the body and headers should be set:
Headers: Content-Type: application/x-www-form-urlencoded
Body: x-www-form-urlencoded (Postman option):
grant_type: client_crendentials
client_id: ***PROJECT_API_KEY
client_secret: ***PROJECT_SECRET KEY
After sending, I only get the error message above. I checked / doubled-checked my API keys, but I can't seem to get it to go through.
Any ideas?
postman settings:
POST - URL https://apis-sandbox.fedex.com/oauth/token
Headers - Content-Type: application/x-www-form-urlencoded
Body - x-www-form-urlencoded:
grant_type: client_credentials
client_id: *******
client_secret: *******
(information gotten from https://developer.fedex.com/api/en-us/catalog/authorization/v1/docs.html)
The sandbox API credentials are not immediately usable when creating a new account. It took >1 hour for me to get a registration complete email from FedEx after which the sandbox credentials became valid.

Cloud Endpoints Authentication

I am using App Engine Standard with the Python 2 runtime and Endpoints Frameworks.
When making a request, the app just returns "Successful" if the request was completed. I am trying to implement authentication so unauthenticated users are not able to complete the request. I've done the following:
Modified my main.py decorator to include issuers and audience:
issuers={'serviceAccount': endpoints.Issuer('[MYSERVICEACCOUNT]', 'https://www.googleapis.com/robot/v1/metadata/x509/[MYSERVICEACCOUNT]')},
audiences={'serviceAccount': ['[MYSERVICENAME]-dot-[MYPROJECT].appspot.com']}
Modifed my main.py method to check for a valid user:
user = endpoints.get_current_user()
if user is None:
raise endpoints.UnauthorizedException('You must authenticate first.')
Regenerated and redeployed my openAPI document. It now has security and securityDefinitions sections.
Updated my app.yaml to reference that Endpoints version.
Redeployed my app
To make an authorized request to my app, I have done the following:
I gave the service account the Service Consumer role on my Endpoints service.
Generate a signed jwt using the generate_jwt function from Google's documentation. I am passing in credentials using the service account's json key file.
payload = json.dumps({
"iat": now,
"exp": now + 3600,
"iss": [MYSERVICEACCOUNT],
"sub": [MYSERVICEACCOUNT],
"aud": [MYSERVICENAME]-dot-[MYPROJECT].appspot.com
})
Make the request using make_jwt_request function from Google's documentation.
headers = {
'Authorization': 'Bearer {}'.format(signed_jwt),
'content-type': 'application/json'}
I am getting 401 Client Error: Unauthorized for url error. Am I missing something?
Your audiences don't match; in your code, you are requiring an audience of [MYSERVICEACCOUNT], but when generating the JWT, your audience is [MYSERVICENAME]-dot-[MYPROJECT].appspot.com. These need to match.
There are few details, which might be worth checking:
The list of allowed audiences should contain the value of aud claim of a client-generated JWT token. This is what Rose has pointed out.
All of the JWT claims presented in sample client documentation are present. Your code is missing the email claim in the JWT payload dictionary.
The method you're accessing requires no specific OAuth scopes. The scopes are set as the scopes field of #endpoints.method decorator.
After opening a support ticket with Google, it turns out Google's documentation was incorrect. The main.py function needs to check for an authenticated user in the below manner:
providers=[{
'issuer': '[YOUR-SERVICE-ACCOUNT]',
'cert_uri': 'https://www.googleapis.com/service_accounts/v1/metadata/raw/[YOUR-SERVICE-ACCOUNT]',
}]
audiences = ['[YOUR-SERVICE-NAME]-dot-[YOUR-PROJECT-NAME].appspot.com']
user = endpoints.get_verified_jwt(providers, audiences, request=request)
if not user:
raise endpoints.UnauthorizedException
After making that change, I got the following error when trying to make an authenticated request:
Encountered unexpected error from ProtoRPC method implementation: AttributeError ('unicode' object has no attribute 'get')
This was caused by how I was generating the payload with json.dumps(). I generated without json.dumps() like below:
payload = {
"iat": now,
"exp": now + 3600,
"iss": [MYSERVICEACCOUNT],
"sub": [MYSERVICEACCOUNT],
"aud": [MYSERVICENAME]-dot-[MYPROJECT].appspot.com
}
These two changes fixed my issue.

facebook graph API company page URL?

I am working on some data analysis regarding beverage manufacturers in the US and would like to grab posts from the company facebook pages to mine some data using the standard facebook graph API. I am new to the facebook API and I am hoping to get some clarifications here that I can't find in the developer docs.
For a simple example lets look at 2 companies FB pages:
https://www.facebook.com/CocaColaUnitedStates
https://www.facebook.com/BellsBreweryInc
Now per the API documentation, I should be able to retrieve the posts on those public company pages via a URL as follows:
https://graph.facebook.com/COMPANYFBNAMEHERE/feed?access_token=MYTOKEN
or
https://graph.facebook.com/v2.5/COMPANYFBNAMEHERE/feed?access_token=MYTOKEN
This works for CocaCola: https://graph.facebook.com/v2.5/CocaColaUnitedStates/feed?access_token=MYTOKEN
This returns data as I would expect:
{
"data": [
{
"message": "The French \"yes! yes! yes!\" sounds like \"we! we! we!\" (lettered \"oui.\") \"C'est la vie\" sounds like (homonym) \"say LOVIE\" (like lovie dovie).\n\nSong of (rather than \"by\") Robbie Nevil: C'est La Vie\nhttp://www.youtube.com/watch?v=CGtf9QfITQw",
"created_time": "2016-02-06T02:52:17+0000",
"id": "820882001277849_452698638250376"
},
etc....
However when I try this for Bell's: https://graph.facebook.com/v2.5/BellsBreweryInc/feed?access_token=MYTOKEN
I get this:
{
"error": {
"message": "Unsupported get request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",
"type": "GraphMethodException",
"code": 100,
"fbtrace_id": "AWTxWye6vub"
}
}
I am not understanding why I am getting an error on Bell's page? It's a publicly available company FB page, so I can't imagine it's a restriction, but I can't understand why it wouldn't be returning the posts like CocaCola?
It sounds like the owner of the token you are using is below the legal drinking age. BellsBreweryInc is a page in the alcohol category so no data will be returned for users under the legal age. This is something BellsBreweryInc would have set in their page settings.
Age restircted websites require a user access token from a user account that meets the page requirements. I was using an app access token which is why it didn't work.
I needed to log into my account and generate a user access token and use that token in the URL.
Also, just realized that token expires in a couple hours. Anyone wanting to do this may also want to read this: How to extend facebook access token in python