Insert event with Google Calendar API in Chrome Extension keeps failing - google-chrome-extension

I'm having trouble getting the format right for a chrome extension using the Google Calendar API. I have an OAuth2 access token (which is valid, I can test that with tokenInfo), but am having trouble. I'm using a proprietary framework to build the extension, which complicates things, but maybe you could help me find out what information I'm missing:
var eventParams = e.data,
request = {
'method' : 'POST',
'async' : true,
'url': 'https://www.googleapis.com/calendar/v3/calendars/'+CAL_ID + '/events',
'headers': {
'Authorization' : TOKEN
},
'params': eventParams
};
My token looks like this:
{↵ "issued_to": "831101123055-874tukfvuvkma6s0l7m70iqlc3lirnkc.apps.googleusercontent.com",↵ "audience": "831101123055-874tukfvuvkma6s0l7m70iqlc3lirnkc.apps.googleusercontent.com",↵ "scope": "https://www.googleapis.com/auth/calendar",↵ "expires_in": 3600,↵ "access_type": "offline"↵}
The error I'm getting is:
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "dailyLimitExceededUnreg",
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"extendedHelp": "https://code.google.com/apis/console"
}
],
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
}
I'm not really sure why that's the case, because my request is authenticated. Am I not passing the token correctly? Someone has suggested that I need to include an API key, but my understanding is that API keys are only for apps requiring public access and don't need access to user data, and that OAuth2 takes the place of an API key.
I'd appreciate any help you guys can offer! Thank you!

Turns out the error was kind of anomalous, the problem turned out to be with the data type. The correct syntax was:
var eventParams = e.data,
request = {
'method' : 'POST',
'async' : true,
'url': 'https://www.googleapis.com/calendar/v3/calendars/' + CAL_ID + '/events',
'headers': {
'Authorization' : TOKEN_TYPE+' '+ TOKEN,
'Content-Type': 'application/json'
},
'contentType': 'json',
'params': JSON.stringify(eventParams)
};

Please make sure that you have calendar API enabled in the developers console:
https://console.developers.google.com

Related

Change entertainment area via Hue Sync Box API

I am leveraging the Hue Sync Box API and I am able to control the settings like sync mode, and intensity. However, I am unable to change hueTarget to change the entertainment area in use.
This is my request:
PUT https://hue_sync_box_ip/api/v1/execution
Headers:
'Content-Type': 'application/json; charset=utf-8'
'Authorization': 'Bearer <token>'
Body:
{"hueTarget": "/groups/c5cecc67-52e8-4f48-9d8d-433634daa9a1"}
The response I get is a 400 error with this body
{"code":15,"message":"Invalid Value"}
As per documentation, this is the problem:
The key exists and the value type matches, but it is not according to the specified format or range.
The documentation on hueTarget is this:
hueTarget
Get, Put
string, enum
Currently selected entertainment area (/groups/ for entertainment group on bridge api v1, and entertainment configuration in UUID format for bridge api v2)
The method is put, the key is valid as per error message, the value type matches string, and I am following the /groups/<id> that is required on v1.
These are my groups. The id I've used matches the "Streaming" which is the group (entertainment area) to which I was trying to change.
...
"hue": {
"bridgeUniqueId": "001788FFFE6A3B07",
"bridgeIpAddress": "<redacted>",
"groupId": "ef023ba4-71bc-4b8b-a7ad-f86dd68356a4",
"groups": {
"ef023ba4-71bc-4b8b-a7ad-f86dd68356a4": {
"name": "Living Room TV",
"numLights": 5,
"active": false
"active": true
},
"c5cecc67-52e8-4f48-9d8d-433634daa9a1": {
"name": "Streaming",
"numLights": 3,
"active": false
}
},
"connectionState": "connected"
},
...
I have also tried leveraging the hue endpoint with the same results:
This is my request:
PUT https://hue_sync_box_ip/api/v1/hue
Headers:
'Content-Type': 'application/json; charset=utf-8'
'Authorization': 'Bearer <token>'
Body:
{
"groups":
{
"c5cecc67-52e8-4f48-9d8d-433634daa9a1": {
"active": true
}
}
}
The response I get is a 400 error with this body
{"code":15,"message":"Invalid Value"}
This matches the documentation: groups/<id>/ active Get, Put boolean.
I am also able to set the entertainment area manually on the app.
Any thoughts on what could be the issue here? I do think this code used to work at some point, but I am not sure as to confirm it for certain.
I've managed to make it work. Instead of sending /groups/<id> as per documentation, you should only send <id>.
In other words, the body of the first call should be:
{"hueTarget": "c5cecc67-52e8-4f48-9d8d-433634daa9a1"}
instead of the original
{"hueTarget": "/groups/c5cecc67-52e8-4f48-9d8d-433634daa9a1"}

Getting connect ETIMEDOUT for Axios HTTP Get Request

So I have an Azure Function that calls Microsoft Maps API and it works (sometimes). However at times it throws this error during the request. Please advise.
My Code:
const options =
{
host: 'atlas.microsoft.com', //added this later
headers: { 'x-ms-client-id': client_id }
}
//url to get lat/long
let url = 'https://atlas.microsoft.com/search/fuzzy/json?api-version=1.0&subscription-key=' + subscription_key + '&query=' + address + ' USA'
//make req
let res = await axios.get(url, options)
Response/Error:
{
"error": {
"message": "connect ETIMEDOUT XX.XXX.XX.XX:XXX",
"name": "Error",
"stack": "Error: connect ETIMEDOUT XX.XXX.XX.XX:XXX\n at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)",
"config": {
"url": "https://atlas.microsoft.com/search/fuzzy/json?api-version=1.0&subscription-key=myKey&query=myQuery",
"method": "get",
"headers": {
"Accept": "application/json, text/plain, */*",
"x-ms-client-id": myClientID,
"User-Agent": "axios/0.19.2"
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"host": "atlas.microsoft.com"
},
"code": "ETIMEDOUT"
}
}
The solution to my timeout problem was adding
host:'atlas.microsoft.com
into my headers for all of my calls. 99% of the connection errors went away. I also reached out to Mircosoft support and they said it doesn't matter if you're using S0 or S1 there is no throttling so that shouldn't make a difference. Currently support is investigating why adding the host part into request headers made such a difference. Will update later with their response.
I asked a similar question and figured out here some additional details.
I saw your request url has subscription-key, and I think you don't need options any more.
According to my test, your problem is not reproduced. The pricing tiers of my Azure Maps service is S1. So I guess the possible reason for your problem.
1. pricing tiers.
Suggest: You can change your pricing tiers.
2. The service of Azure Map is abnormal.
Suggest: It is recommended to raise a support ticket in portal, ask if there is any abnormal service in this area, and check your service log.
Below are my test results.
I tested it and my test url like https://atlas.microsoft.com/search/fuzzy/json?api-version=1.0&query=seattle&subscription-key=WCzM8k*******nnSYn4. I just request via chrome browser and get response.
And I also test by axios and it works fine.

Translator Text API endpoint returning 404 code with message "Resource not found" as a JSON Object

After creating a service for Text Translator of Azure service, the end point when tried with the one of the keys provided returns a json object with 404 error code and Message "Resource not found"
{
"error": {
"code": "404",
"message": "Resource not found"
}
}
Postman Parameters used are:
URL:
https://agro.cognitiveservices.azure.com/translate?api-version=3.0&to=ta,en
Body JSON:
{
[
"Text" : "Hello World"
]
}
With Ocp-Apim-Subscription-Key parameter in header, is that which was given as the subscription key for cognitive service of Azure when registering.
NOTE: HTTP POST Method used.
Please suggest a solution to resolve the problem and THANK YOU for this.
Screenshot Shared below as link:
enter image description here
Looking at Microsoft docs, your endpoint seems to be invalid. See https://learn.microsoft.com/en-us/azure/cognitive-services/translator/quickstart-translate?pivots=programming-language-javascript
HTTP POST Endpoint: https://api.cognitive.microsofttranslator.com/?api-version=3.0&to=ta,en
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
}
Body:
body: [{
'text': 'Hello World!'
}]

amazon product advertising api node js sdk request throtteling issue

I am getting this error in response when calling amazon product advertising api from nodejs sdk.
Error calling PA-API 5.0!
Printing Full Error Object:
{
"status": 429,
"response": {
"req": {
"method": "POST",
"url": "https://webservices.amazon.com/paapi5/getitems",
"data": {
"ItemIds": [
"B075LRK2QK"
],
"PartnerTag": "raassnabct-21",
"PartnerType": "Associates",
"Condition": "New",
"Resources": [
"Images.Primary.Medium"
]
},
"headers": {
"user-agent": "paapi5-nodejs-sdk/1.0.0",
"authorization": "AWS4-HMAC-SHA256 Credential=MY_KEY/20191215/us-east-1/ProductAdvertisingAPI/aws4_request, SignedHeaders=content-encoding;content-type;host;x-amz-date;x-amz-target, Signature=030b9f07a2336302a6d8855e216e602589960bf919dc9e700daac6155dcce1a2",
"content-encoding": "amz-1.0",
"content-type": "application/json; charset=utf-8",
"host": "webservices.amazon.com",
"x-amz-target": "com.amazon.paapi5.v1.ProductAdvertisingAPIv1.GetItems",
"x-amz-date": "20191215T111055Z",
"accept": "application/json"
}
},
"header": {
"server": "Server",
"date": "Sun, 15 Dec 2019 11:10:54 GMT",
"content-type": "application/json",
"content-length": "193",
"connection": "close",
"x-amzn-requestid": "0ada8ea0-944f-47a2-bbef-acc0f5d984a9",
"vary": "Accept-Encoding,X-Amzn-CDN-Cache,X-Amzn-AX-Treatment,User-Agent",
"content-encoding": "gzip",
"x-amz-rid": "JTD0DAVWEB1CMXK1F5BW"
},
"status": 429,
"text": "{\"__type\":\"com.amazon.paapi5#TooManyRequestsException\",\"Errors\":[{\"Code\":\"TooManyRequests\",\"Message\":\"The request was denied due to request throttling. Please verify the number of requests made per second to the Amazon Product Advertising API.\"}]}"
}
}
Status Code: 429
Error Object: "{\"__type\":\"com.amazon.paapi5#TooManyRequestsException\",\"Errors\":[{\"Code\":\"TooManyRequests\",\"Message\":\"The request was denied due to request throttling. Please verify the number of requests made per second to the Amazon Product Advertising API.\"}]}"
And the code is
var ProductAdvertisingAPIv1 = require('./src/index');
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
defaultClient.accessKey = 'accessKey';
defaultClient.secretKey = 'secretKey';
defaultClient.host = 'webservices.amazon.com';
defaultClient.region = 'us-east-1';
var api = new ProductAdvertisingAPIv1.DefaultApi();
var getItemsRequest = new ProductAdvertisingAPIv1.GetItemsRequest();
getItemsRequest['PartnerTag'] = 'raassnacbt-21';
getItemsRequest['PartnerType'] = 'Associates';
getItemsRequest['ItemIds'] = ['B075LRK2QK'];
getItemsRequest['Condition'] = 'New';
getItemsRequest['Resources'] = ['Images.Primary.Medium', 'ItemInfo.Title', 'Offers.Listings.Price'];
function parseResponse(itemsResponseList) {
var mappedResponse = {};
for (var i in itemsResponseList) {
mappedResponse[itemsResponseList[i]['ASIN']] = itemsResponseList[i];
}
return mappedResponse;
}
try {
api.getItems(getItemsRequest, callback);
} catch (ex) {
console.log("Exception: " + ex);
}
I am getting "too many requests" error even when making just one. also tried to run this on server just in case it had something to do with localhost. there is no manual modification, it is just the sdk code with my credentials. any idea what might be the issue?
This is a very common problem people face while using Amazon product API. Amazon works on a very different algorithm. It allocates API threshold/ usage limit based on the commission you have earned through amazon. Once your allocated limit is exhausted, you will receive such errors.
To fix this, ask your friend to buy through your affiliate link. You will get some threshold.
Old topic, but maybe can be useful. I realized this error is also shown when authentication failed. So it is necessary to take into account that associate IDs are only active in a concrete region and also that new generated API Keys can take until 72h to be really active, so check these points if necessary apart from the quota stuff the other users mentioned.

Microsoft graph return "access token is empty"

I post this request:
POST https://login.microsoftonline.com:443/{my-tennant-here}/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id={client id here}
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_secret={client secret here}
&grant_type=client_credentials
This returns:
{
"token_type": "Bearer",
"expires_in": 3599,
"ext_expires_in": 0,
"access_token": "eyJ0eX......
}
I have decoded the token using jwt.io and it definitely is not empty. It contains 14 claims. aud, iss, tid etc...
I then use the access token in this request
GET https://graph.microsoft.com/v1.0/users
Athorization: Bearer eyJ0eX...
I then get a 401 Unauthorized with this body:
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token is empty.",
"innerError": {
"request-id": "",
"date": "2018-08-14T15:41:44"
}
}
}
Expected result was a 200 Ok with a body containing a list of users
Does this simply mean that my app is Unauthorized, and the error message is just misleading (access token is empty)?
Or have I done something wrong?
Update:
I have noted that the although the token does contain claims it does not have a scope claim which seems a bit weird to me. I would assume that it had the User.Read.All scope. The application (client id/client secret) should have this permission.
The claims in the token I receive have the following claims:
aud: "https://graph.microsoft.com",
iss: "https://sts.windows.net/my tennant id",
iat: timestamp
nbf: timestamp
exp: timestamp
aio: looks like some kind of signature
app_displayname: "the expected app name"
appid: "the expected appid"
appidacr: "1"
idp: "https://sts.windows.net/...."
oid: "GUID"
sub: "GUID"
tid: "my tennant id"
uti: "value"
ver: 1.0
The Authorization header was misspelled.
So "Access token is empty" probably actually meant not present or even "No authorization header in request".
For me, my issue was that I had put a linebreak between the request url and the Authorization header, making it the body instead.
Wrong:
GET https://graph.microsoft.com/v1.0/users
Authorization: Bearer {{token}}
Correct:
GET https://graph.microsoft.com/v1.0/users
Authorization: Bearer {{token}}
A stupid mistake, but easy to overlook - if you get to this post you have probably done a silly mistake like OP (typo) or this. Look through your request syntax again!
One URL works while the other doesn't.
This works:
endpoint = "https://graph.microsoft.com/v1.0/reports/getOffice365ActiveUserDetail%28period%3D%27D7%27%29"
headers = {"Authorization": 'Bearer ' + access_token_gmc}
response = requests.get(endpoint, headers=headers)
But this one doesn't:
endpoint = "https://graph.microsoft.com/v1.0//users/myuserid/calendars"
headers = {"Authorization": 'Bearer ' + access_token_gmc}
response = requests.get(endpoint, headers=headers)
Please make sure the spellings are correct.
I was getting the same error in my angular application where I use MSAL.
And it was all because of the wrong API scope provided in the MSALAngularConfigFactory. I was having the environment as preceding.
export const environment = {
production: false,
clientId: 'clientid',
redirectUrl: 'http://localhost:4200',
graphApiUrl: 'https://graph.microsoft.com/v1.0',
graphGetUserImage: '/me/photo/$value',
protectedResourceMap: [
['http://localhost:65498/api', ['api.access']],
['https://graph.microsoft.com/beta', ['user.read']]
] as [string, string[]][],
authority: 'https://login.microsoftonline.com/organizations'
};
As you can see that I have given https://graph.microsoft.com/beta in the protectedResourceMap, which is wrong. Instead, we should give https://graph.microsoft.com/v1.0/. So here is the correct environment.
export const environment = {
production: false,
clientId: 'clientid',
redirectUrl: 'http://localhost:4200',
graphApiUrl: 'https://graph.microsoft.com/v1.0',
graphGetUserImage: '/me/photo/$value',
protectedResourceMap: [
['http://localhost:65498/api', ['api.access']],
['https://graph.microsoft.com/v1.0/', ['user.read']]
] as [string, string[]][],
authority: 'https://login.microsoftonline.com/organizations'
};
And I use it in the app.module.ts as below.
function MSALAngularConfigFactory(): MsalAngularConfiguration {
return {
popUp: false,
protectedResourceMap: environment.protectedResourceMap,
};
}
For User.Read.All scope you can't have a user consent. It must be admin consent. It looks like you may have missed consenting your app using an admin account.
To do this hit:
GET https://login.microsoftonline.com/{tenant}/adminconsent
?client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345
&redirect_uri=http://localhost/myapp/permissions
Then get an access token and you should get the scopes the admin has consented users for.

Resources