Google Analytics API fails to login with bad request and invalidKey - authentication

I´m trying to get some data from analytics, but can´t get authorized. It returns the following error:
I renewed my credentials at google console several times.
The code I´m using:
var clientId = '*****************0m1fnmuae00abaaq.apps.googleusercontent.com';
var apiKey = '********fB9eVMVfQ0oR6';
var scopes = 'https://www.googleapis.com/auth/analytics.readonly';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth, 1);
}
function checkAuth() {
gapi.auth.authorize({
client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
if (authResult) {
gapi.client.load('analytics', 'v3', handleAuthorized);
} else {
handleUnauthorized();
}
}
function handleAuthorized() {
var authorizeButton = document.getElementById('authorize-button');
var runDemoButton = document.getElementById('run-demo-button');
authorizeButton.style.visibility = 'hidden';
runDemoButton.style.visibility = '';
runDemoButton.onclick = makeApiCall;
outputToPage('Click the Run Demo button to begin.');
}
function handleUnauthorized() {
var authorizeButton = document.getElementById('authorize-button');
var runDemoButton = document.getElementById('run-demo-button');
runDemoButton.style.visibility = 'hidden';
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
outputToPage('Please authorize this script to access Google Analytics.');
}
function handleAuthClick(event) {
gapi.auth.authorize({
client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
When I run the code, it returns the following error:
error: {errors:[{domain:usageLimits, reason:keyInvalid, message:Bad Request}], code:400, message:Bad Request}
code: 400
errors: [{domain:usageLimits, reason:keyInvalid, message:Bad Request}]
0: {domain:usageLimits, reason:keyInvalid, message:Bad Request}
domain: "usageLimits"
message: "Bad Request"
reason: "keyInvalid"
message: "Bad Request"
Someone can help with this issue?

Find the error.
In Google Console, you have to create the OAuth ID and the Public API Access ID.
Take the cliendId from the first and the APIKey from the second.
I think it´s very confuse, and it could be more explicit in documentation.

Related

How to call Azure function from Kotlin

I currently have deployed an Azure function used to get an AD token.
Function:
https://getadtokennet.azurewebsites.net/api/getadtokennet
Request header:
x-functions-key = {key}
How can I call this function from my Kotlin app?
This is the way I call it from Javascript
function getTokenAzure(onsuccess, onerror) {
var tokenUrl = 'https://getadtokennet.azurewebsites.net/api/getadtokennet';
$.ajax(tokenUrl, {
method: 'GET',
beforeSend: function (request) {
request.setRequestHeader("x-functions-key", "function key");
},
success: function (data) {
onsuccess(data);
console.log('token: ' + data.token);
},
error: function (xhr, status, error) {
var failureMessage = "GetToken error: " + status + " - " + error;
onerror(failureMessage);
console.log(failureMessage);
}
});
}
In IntelliJ IDEA, select Create New Project.
In the New Project window, select Maven from the left pane.
Select the Create from archetype check box, and then select Add Archetype for the azure-functions-kotlin-archetype.
In the Add Archetype window, complete the fields as follows:
GroupId: com.microsoft.azure
ArtifactId: azure-functions-kotlin-archetype
Version: Use the latest version from the central repository
Select OK, and then select Next.
Enter your details for current project, and select Finish.
For complete information refer to the below links which has same information.
Kotlin Function and Running Kotlin in Azure Functions
I found the way, here it is.
fun getToken(): String {
val tokenUrl = URL("https://getadtokennet.azurewebsites.net/api/getadtokennet")
val connection = tokenUrl.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.setRequestProperty("x-functions-key", "function key")
connection.doOutput = true
val responseCode = connection.responseCode
if (responseCode == HTTP_OK) {
val readerIn = BufferedReader(InputStreamReader(connection.inputStream))
var inputLine = readerIn.readLine()
val response = StringBuffer()
do {
response.append(inputLine)
} while (inputLine.length < 0)
readerIn.close()
// Return token
return response.toString()
} else {
val responseError = Error(code = "BadRequest", message = "There was an error getting the token.")
throw IOException(responseError.toString())
}
}

Linkedin API: Exchange JSAPI Token for REST API OAuth Token

I'm having some difficulty exchanging my JSAPI token for a REST API token. I'm using this for reference:
https://developer-programs.linkedin.com/documents/exchange-jsapi-tokens-rest-api-oauth-tokens
I've: set up a self signed SSL cert locally, so Linkedin's secure cookie works properly; given my app r_basicprofile and r_emailaddress permissions.
Here's my front end code:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: **MY_CLIENT_ID**
authorize: true
credentials_cookie: true
</script>
...
$('.linkedin-signin').click(function(e) {
IN.User.authorize( function () {
IN.API.Raw("/people/~").result(function(data) {
$.post(location.origin+'/api/account/create/linkedin', { 'lId': data.id } ).done(function(result) {
console.log(result);
});
});
});
return false;
});
And here is my PHP code, which is almost exactly as in their docs:
$consumer_key = '**MY_CLIENT_ID**';
$consumer_secret = '**MY_CLIENT_SECRET**';
$cookie_name = "linkedin_oauth_${consumer_key}";
$credentials_json = $_COOKIE[$cookie_name];
$credentials = json_decode($credentials_json);
$access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken';
$oauth = new OAuth($consumer_key, $consumer_secret);
$access_token = $credentials->access_token;
// swap 2.0 token for 1.0a token and secret
$oauth->fetch($access_token_url, array('xoauth_oauth2_access_token' => $access_token), OAUTH_HTTP_METHOD_POST);
Everything looks good, but on $oauth->fetch, I get the error:
OAuthException(code: 401): Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)
Which leads me to believe that the token is invalid... but it's taken directly from the cookie, so how could it be invalid? Any ideas?
Today we got the weird 401 error too, apperently linkedin was broken, because after an hour it worked again without any changes on our side.
I found this site though and eventhough it's a really old post, i tought i'd share how we fixed it, which works.
JS Front-end
var AppConfig = {
linkedin : {
onLoad : "linkedinLibInit",
api_key : 'YOUR_API_KEY',
authorize : false,
credentials_cookie: true
}
};
window.linkedinLibInit = function ( response ) {
// post init magic
// cleanup window callback function
delete window.linkedinLibInit;
}
$.getScript( "//platform.linkedin.com/in.js?async=true", function success() {
IN.init( AppConfig.linkedin );
} );
function connectToLinkedIn() {
if ( IN.User.isAuthorized() ) {
_linkedinAuthorized();
}
else {
IN.User.authorize( _linkedinAuthorized );
}
}
function _linkedinAuthorized() {
IN.API.Profile( "me" )
.fields( 'id', 'first-name', 'last-name', 'location', 'industry', 'headline', 'picture-urls::(original)', 'email-address' )
.result( function ( response ) {
var accessToken = JSON.parse( $.cookie( 'linkedin_oauth_' + AppConfig.linkedin.api_key ) );
// performApi Call to backend
} )
.error( function ( err ) {
// render error
} );
}
PHP Backend using PECL oAuth
function offlineAuthLinkedIn($accessToken, $linkedinConfig) {
$oAuth = new \OAuth( $linkedinConfig['app_id'], $linkedinConfig['app_secret'] );
$oAuth->fetch(
'https://api.linkedin.com/uas/oauth/accessToken',
array('xoauth_oauth2_access_token' => $accessToken),
OAUTH_HTTP_METHOD_POST
);
$response = null;
parse_str($oAuth->getLastResponse(), $response);
$oAuth->setToken($response['oauth_token'], $response['oauth_token_secret']);
$oAuth->fetch(
'http://api.linkedin.com/v1/people/~:(id,first-name,last-name,formatted-name,headline,location,picture-url,picture-urls::(original),public-profile-url)',
array(),
OAUTH_HTTP_METHOD_GET,
array('x-li-format' => 'json')
);
$profile = json_decode($oAuth->getLastResponse(), true);
$profile['user_id'] = $profile['id'];
if (true == isset($profile['pictureUrl']))
{
$profile['profile_image'] = $profile['pictureUrl'];
unset($profile['pictureUrl']);
}
return $profile;
}

QuickBlox create user issue (bad request) without any error message

I want to create an user using the rest API. Rest API returns an error (bad request), when I made the request. There are not any other error messages.
JSON:
Required Parameters : login, password, email
http://quickblox.com/developers/Users#API_User_Sign_Up
{
"user":
{
"login":"user123456",
"password":"User11#2015",
"email":"xxx#ccc.com.tr",
"blob_id":null,
"external_user_id":null,
"facebook_id":null,
"twitter_id":null,
"full_name":null,
"phone":null,
"website":null,
"custom_data":null,
"tag_list":null
}
}
Rest API Result:
Response Status Code : BadRequest.
Response Content is empty. No error message.
I do not understand the error. Can you help me?
Code :
public NotificationUser CreateUser(string token, NotificationUser notificationUser)
{
var user = new QuickbloxUser()
{
email = notificationUser.Email,
password = notificationUser.Password,
login = notificationUser.Login
};
var jsonBody = JsonConvert.SerializeObject(user);
var request = new RestRequest("users.json", Method.POST);
request.AddHeader("QB-Token", token);
request.AddParameter("user", jsonBody);
var response = _restClient.Execute<RootUser<QuickbloxUserResponse>>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
notificationUser.Id = response.Data.user.id;
notificationUser.Email = response.Data.user.email;
notificationUser.Login = response.Data.user.login;
return notificationUser;
}
return null;
}

Goodreads Connect - url for user to grant my application access to their account

What is the url that I can direct a user so they can grant my application access to their goodreads account? I have sourced the goodreads docs at https://www.goodreads.com/api and maybe overlooking something I just cant figure it out.
I require the goodreads' user id to 'Get the books on a members shelf'
https://www.goodreads.com/api#shelves.list
My first obstacle is to enable the dialogue to pop up where the users signs into their goodreads account which effectively grants my application access to their goodreads data.
.....
continuation from question - last parse function "TypeError: Cannot read property 'parse' of undefined"
Meteor.methods({
getGoodreads: function () {
var oauth = { callback: 'http://localhost:3000/profile/',
consumer_key: 'keyxkeyx',
consumer_secret: 'secreckeyxxsecreckeyxx'
},
url = 'http://www.goodreads.com/oauth/request_token';
request.post({url:url, oauth:oauth}, function (e, r, body) {
var req_data = qs.parse(body);
var uri = 'http://www.goodreads.com/oauth/authorize'
+ '?' + qs.stringify({oauth_token: req_data.oauth_token});
var auth_data = qs.parse(body),
oauth =
{ consumer_key: 'keyxkeyx'
, consumer_secret: 'secreckeyxxsecreckeyxx'
, token: auth_data.oauth_token
, token_secret: req_data.oauth_token_secret
, verifier: auth_data.oauth_verifier
},
url = 'http://www.goodreads.com/oauth/access_token';
console.log(auth_data); // this successfully prints the oauth_token and oauth_token_secret
request.post({url:url, oauth:oauth}, function (e, r, body) {
var perm_data = new qs.parse(body), // "TypeError: Cannot read property 'parse' of undefined"
oauth =
{ consumer_key: 'keyxkeyx'
, consumer_secret: 'secreckeyxxsecreckeyxx'
, token: perm_data.oauth_token
, token_secret: perm_data.oauth_token_secret
},
url = 'https://www.goodreads.com/topic.xml',
qs = {user_id: perm_data.user_id,
key: 'keyxkeyx'};
request.get({url:url, oauth:oauth, json:true}, function (e, r, user) {
console.log(user)
});
});
});
}
});
The authorization URL for Goodreads is:
http://www.goodreads.com/oauth/authorize
You can review a (Ruby) code example here https://www.goodreads.com/api/oauth_example

vline add remote stream for callee fail

I am trying to use your api in a custom app with imported users.
Everything works fine (auth_token, login, call initiation) , but when the callee should get a response and add the remotestream nothing happens. no errors get shown in the console.
I would appreciate if someone takes a look at the code and tells me what i m missing.
I tried the vline demo at https://freeofcinema.vline.com and it worked with the same browsers and conditions between the two computers. In my app it is a http , but i tried it also with https, and the same problem came up. This is some simplified code i used to test the api.
var Streams = [];
var Vsession = null;
var Vline = (function(){
var Client;
var authToken;
var service_id = 'freeofcinema';
var profile = null;
var Person;
var Calls = [];
var onMessage = function(event){
//alert('message');
var msg = event.message, sender = msg.getSender();
console.log(sender.getDisplayName() +'sais: '+ msg.getBody());
console.log(event);
}
var onMediaSession = function(event){
console.log(event);
var mediaSession = event.target;
InitSession(mediaSession);
}
function Call(mediaSession) {
mediaSession.
on('change', alert_info);
}
function alert_info(b){
console.log(b);
}
function InitSession(mediaSession){
mediaSession.on('mediaSession:addRemoteStream', function(event) {
alert('addRemoteStream');
});
mediaSession.on('mediaSession:addLocalStream', function(event) {
alert('addLocalStream');
});
mediaSession.on('mediaSession:removeLocalStream mediaSession:removeRemoteStream', function(event) {
console.log('removedStream');
});
Calls.push(new Call(mediaSession));
}
return {
init : function(){
if(profile){
return;
}
profile = {
"displayName" : //some getusrname function...
};
$.post('vtoken.php',{//get auth token
id : Comm.Voip_user().id
},function(data){
authToken = data;
Client = vline.Client.create({
"serviceId": service_id,
"ui" : true
});
Client.on('recv:im', onMessage , this);
Client.on('add:mediaSession', onMediaSession, this);
Client.on('login', function(e) {
Vsession = e.target;
//alert('loged in');
});
Client.login(service_id, profile, authToken);
});
},
getPerson : function(id){//id of user to call
if(Vsession){
Vsession.getPerson(id).
done(function(person){
Person = person;
Vsession.startMedia(id);
});
}
}
}
}());
Thank you for your response.
I tried with one user from the app, and another from the https://freeofcinema.vline.com, and the same problem occured. Also the call (in pending state) gets terminated after a short while..
When passing ui:true when creating the client, you do not have to handle the media sessions yourself. Just comment the line Client.on('add:mediaSession', onMediaSession, this); and it should just work.