Get linkedin Access Token with JavaScript SDK - javascript

I am working on that application allow user to connect to linkedin (using javascript). I want to store access token that I got from IN.ENV.auth.oauth_token because I will use it to post to user's timeline.
But when I use this access token to post to Linkedin, I got "Invalid access token" error.
Did I use correct access token? How's the correct way to get Access token?
Here's my code:
$("#linkedin-connect").on('click',function(e){
e.preventDefault();
IN.UI.Authorize().place();
IN.Event.on(IN, "auth", OnLinkedInAuth);
return false;
});
function OnLinkedInAuth() {
console.debug("oauth token:" + IN.ENV.auth.oauth_token);
}
JSFiddle Example

this event IN.Event.on(IN, "auth", OnLinkedInAuth); should pass some data to your function OnLikedInAuth as in shown in the documentation of the sdk.
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: YOUR_API_KEY_HERE
authorize: true
onLoad: onLinkedInLoad
</script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
IN.API.Raw("/people/~").result(onSuccess).error(onError);
}
As that example (available in docs) the getProfileData (similar to your OnLinkedInAuth) returns a Promise and when it's resolved will give you some data that you need to read. In that object you will find the token that you can store (LocalStorage) and use

Related

LinkedIn JavaScript SDK - Uncaught TypeError: Cannot read property 'apply' of undefined

It seems no matter what I try, I end up with this error. I have tried the default example:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: YOUR_API_KEY_HERE
authorize: true
onLoad: onLinkedInLoad
</script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
IN.API.Raw("/people/~:(firstName)?format=json").result(onSuccess).error(onError);
}
</script>
I'm just trying to console log the first name of the user as a test. I have also tried various function names, as well as removing the onLoad argument just to test. I always get the error: Uncaught TypeError: Cannot read property 'apply' of undefined.
It looks like you are trying to use onLinkedInLoad before it's defined, try swapping the <script> blocks order.

Google drive authentication showing error "idpiframe_initialization_failed"

I am trying to use google drive javascript API. I have set the OAuth consent also. But everytime its showing error
Not a valid origin for the client
and
"idpiframe_initialization_failed"
what is the problem actually? I have googled, googled and googled but no solution with that. I am trying on localhost by creating a virtual host.
I am using the sample from google doc
<html>
<head></head>
<body>
<script type="text/javascript">
function handleClientLoad() {
// Loads the client library and the auth2 library together for efficiency.
// Loading the auth2 library is optional here since `gapi.client.init` function will load
// it if not already loaded. Loading it upfront can save one network request.
gapi.load('client:auth2', initClient);
}
function initClient() {
// Initialize the client with API key and People API, and initialize OAuth with an
// OAuth 2.0 client ID and scopes (space delimited string) to request access.
gapi.client.init({
apiKey: 'APIKEY',
discoveryDocs: ["https://people.googleapis.com/$discovery/rest?version=v1"],
clientId: 'CLIENTID.apps.googleusercontent.com ',
scope: 'profile'
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
});
}
function updateSigninStatus(isSignedIn) {
// When signin status changes, this function is called.
// If the signin status is changed to signedIn, we make an API call.
if (isSignedIn) {
makeApiCall();
}
}
function handleSignInClick(event) {
// Ideally the button should only show up after gapi.client.init finishes, so that this
// handler won't be called before OAuth is initialized.
gapi.auth2.getAuthInstance().signIn();
}
function handleSignOutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
function makeApiCall() {
// Make an API call to the People API, and print the user's given name.
gapi.client.people.people.get({
'resourceName': 'people/me',
'requestMask.includeField': 'person.names'
}).then(function(response) {
console.log('Hello, ' + response.result.names[0].givenName);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
<button id="signin-button" onclick="handleSignInClick()">Sign In</button>
<button id="signout-button" onclick="handleSignOutClick()">Sign Out</button>
</body>
</html>
I had the same problem with Google Drive javascript API quick start example.
I cleared Google Chrome's cache from beginning of time and after that it worked...
Hope it helps! :)
You should provide the http calls and response so we can check.
However the message "Not a valid origin for the client" suggests that the URL you are serving your web page from is not one of those origins that you configrued in the API Console.

LinkedIn Login with basic example not working

I would like to add the possibility of LinkedIn login to my project. I followed the tutorial given on the LinkedIn developer page and ended up with the following code, really basic stuff from that tutorial:
<!-- linkedin login -->
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: [MY_API_KEY] {~n}
authorize: false {~n}
onLoad: onLinkedInLoad {~n}
</script>
<!-- linkedin login play -->
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
IN.API.Raw("/people/~").result(onSuccess).error(onError);
}
</script>
Don't mind the {~n} as I'm using dust.js to render the page and I need them to pass the arguments to the LinkedIn script.
So, the login button appears, this means that LinkedIn was able to connect to my API key correctly, but the Chrome console gives me the following error: Uncaught Error: Could not execute 'onLinkedInLoad'. Please provide a valid function for callback.. Since this is the example given on the tutorial page, I don't know what can be wrong with it. Even if I declare the block of LinkedIn login functions before the call to the LinkedIn in.js, I get the same error.
I think it is a very easy mistake to spot, but I cannot really tell what am I doing wrong.
This is happening cause you are calling onLinkedInLoad() in head section,and if you are working on multiple pages..it will be called on the every page even if it doesn't have data from API call(or simply you are not making any call on the page where this error is appearing).
Try this`
// Removing event listener by calling IN.Event.on() outside of onLinkedInLoad()
IN.Event.on(IN, "auth", getProfileData);
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
IN.API.Raw("/people/~").result(onSuccess).error(onError);
}
`
And Yes remove " onLoad: onLinkedInLoad {~n}" from first script call

Apply by LinkedIn Button, 400 error bad request

I'm trying to add an 'Apply by LinkedIn' button to an expressionengine site. I've created my app on LinkedIn and am using the JS SDK and have followed the guide in order to do so. My code is below:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: MY CLIENT ID
authorize: true
onLoad: onLinkedInLoad
</script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to request the member's profile data
function getProfileData() {
IN.API.Raw("/people/~:(id, first-name, skills, educations, languages, twitter-accounts)")
.result(onSuccess).error(onError);
}
</script>
I've added the button markup as suggested:
<script type="in/Login"></script>
SO the button is displayed and upon click I'm presented with my account to authorise the app, however, upon authenticating, the button disappears and I get the following error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
ObjecterrorCode: 0message: "Unknown field {_first-name} in resource {Person}"requestId: "LT59BVDVU2"status: 400timestamp: 1436259208629__proto__: Object
Thanks!
Use camelcasing instead of dashes:
IN.API.Raw("/people/~:(id, firstName, skills, educations, languages, twitter-accounts)")

Google Javascript API (gapi) - problems with .load

I am trying to use the Google plus API (via googie-api-javascript) implementation like so (omitting full code):
var clientId = '7454475891XxxxxxXom4c6n.apps.googleusercontent.com'; //fake client
var apiKey = '-uTH_p6NokbrXXXXXXXXXXXXX'; //Fake Key
var scopes = 'https://www.googleapis.com/auth/plus.me';
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 && !authResult.error) {
makeApiCall();
} else {
//handle user-approval
}
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
gapi.client.load('plus', 'v1', function() {
var o = gapi.client.plus;
alert(o);
});
}
The code works well upto the point of gapi.client.load (including the user allowing access) - this callback gets called but alert(o) will return undefined.
Upon inspecting the HTTP request I see the .load issues a request to:
https://content.googleapis.com/discovery/v1/apis/plus/v1/rpc?fields=methods%2F*%2Fid&pp=0&key=-uTH_p6NokbrXXXXXXXX
This returns HTTP 400 with the following message:
{"error":{"errors":[{"domain":"usageLimits","reason":"keyInvalid","message":"Bad Request"}],"code":400,"message":"Bad Request"}}
My question is - what do I need to change to make this work?
Is there some secret setting I need to enable ? Google+ is enabled in the google-developer-console under the APIs list.
Thanks for the help,
Alon
Problem:
.load issues a request to the google discovery service to load the .JS. The service will error out if the request it receives contains an api-key. (I don't know why the library works like this, it seems like a bug?)
Fix:
gapi.client.setApiKey(""); //NEW
gapi.client.load('plus', 'v1', function()
//re-add the key later if you need it
From Discovery Service docs:
requests you make to the Discovery Service API should not include an API key. If you do provide a key, the requests will fail.
Weird... :P
A little update & more of an explanation. The current Discovery Service page is a little more specific now. They indicate that if the app has an Oauth2 token, then the API Key value is not required. However, I also found that if I have an authenticated user and thus an Oauth2 token (access_token) present, the Discovery Service fails with the error noted in the OP. This seems to contradict the documentation.
You can see the token in the developer tools console with:
console.log(gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse());
Embed that somewhere in a <script>...</script>in your HTML or in a .js file that is called otherwise. Must be after gapi.load(...). It'll stop the script if executed before gapi.load(...) is called.
To get a current user this has to be after the user is authenticated, of course. It does return an object if a user has not been authenticated however. If you are in Chrome, you can expand The Object in the developer tools console window to get a nice outline format of all the stuff in the auth response.
Note that currentUser is undefined prior to a successful authentication. Since this 'fails silently' you should use a conditional statement to verify either the sign in status or that a current user exists in your real code.
For completeness the object instantiation process in my app goes like this, at a high level:
1.) gapi.load(...) - After this gapi.client, gapi.auth2 and other objects are available.
2.) gapi.client.setApiKey("") would be called to 'clear' the api key if it had been set previously for some other purpose.
3.) gapi.auth2.init(...) - After this the auth instance is available via gapi.auth2.getAuthInstance .
4.) Then the login is kicked off using the .signIn() method of the auth instance. The auth instance would be instantiated with something like auth_instance = gapi.auth2.getAuthInstance(); If that's how you do it then the sign in would be auth_instance.signIn().
(...) - means there are several parameters needed.
I also found the Google tictactoe example useful as an example and a simple base for further work.
I hope this is helpful to someone!
you need to call the method
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false} handleAuthResult);
return false;
}
function makeApiCall() {
gapi.client.load('plus', 'v1', function () {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function (resp) {
'method ajax with you application'
});
});
}
you can see what this do here

Categories

Resources