Getting email from LinkedIn Javascript API reliably - javascript

Keen to get at the user's email reliably, there doesn't appear to be anything in the API documentation about this from LinkedIn. I have the cod working which grabs the basic profile and I've tried what I can find on the web to get additional fields. But this doesn't return anything. Here is the code:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: 11111111111
onLoad: onLinkedInLoad
authorize: true
scope: r_basicprofile
</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() {
var fields = ['firstName', 'lastName', 'emailAddress'];
IN.API.Profile("me").fields(fields).result(onSuccess).error(onError);
}
</script>
and HTML:
<script type="in/Login"></script>
I do not know if it is possible with the current version to return the email or the email is user setting so varies with each user.

You are missing r_emailaddress to the scope:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: 11111111111
onLoad: onLinkedInLoad
authorize: true
scope: r_basicprofile r_emailaddress
</script>
Also be sure you are using the right syntax for the fields:
var fields = ['first-name', 'last-name', 'email-address'];
And finally check in your app setting on LinkedIn developer that you grant r_emailaddress access.

Related

Issue with Auth0 and javascript Lock v11

I'm trying to test a basic authentication module on my web app using auth0 and Lock v1 login form.
This is a snapshot of the code I'm using:
<script src="https://cdn.auth0.com/js/lock/11.23.1/lock.min.js"></script>
<script type="text/javascript" src="js/auth0variables.js"></script>
<script type="text/javascript" src="js/auth0app.js"></script>
<script>
$( document ).ready(function() {
console.log("start");
var lock = new Auth0Lock(AUTH0_CLIENT_ID, AUTH0_DOMAIN, {
auth: {
redirectUrl: 'undefined',
responseType: 'code',
params: {
scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
}
}
});
lock.show();
});
</script>
The problem is that I'm not able to get the auth0 modal since I'm getting the following error:
Uncaught TypeError: Cannot read property 'protocol' of null
at Object.getOriginFromUrl (auth0.min.esm.js:8)
at G.run (auth0.min.esm.js:8)
at $.checkSession (auth0.min.esm.js:8)
at nt.getSSOData (auth0.min.esm.js:8)
at t.getSSOData (p2_api.js:190)
at t.getSSOData (web_api.js:64)
at t.fetchFn (data.js:4)
at t.fetch (cache.js:17)
at t.get (cache.js:13)
at r (data.js:7)
I don't understand if I'm configuring in a wrong way my application on Auth0 dashboard, if I'm missing some configuration parameter calling the the Auth0Lock method or if the issue is somewhere else.
Can anybody help me with this? Thanks!
I found a workaround looking at the following discussion hosted on ath0 github repo:
https://github.com/auth0/lock/issues/1638
In order to avoid getLocationFromUrl returning null value I set the redirectUrl option in Auth0Lock constructor
<script src="https://cdn.auth0.com/js/lock/11.23.1/lock.min.js"></script>
<script type="text/javascript" src="js/auth0variables.js"></script>
<script type="text/javascript" src="js/auth0app.js"></script>
<script>
$( document ).ready(function() {
console.log("start");
var lock = new Auth0Lock(AUTH0_CLIENT_ID, AUTH0_DOMAIN, {
auth: {
redirectUrl: 'http://localhost',
//redirectUrl: 'file://',
responseType: 'code',
params: {
scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
}
}
});
lock.show();
});
</script>
Both redirectUrl: 'http://localhost' or redirectUrl: 'file://' options are working fine for my development purposes.

Why LinkedIn Social Login Not Returning Email Id With Newly Created App

When i am trying with old app then LinkedIn login returning email id with basic profile but when i am trying with new app it's returning only basic profile like (firstName, lastName etc....) but not email Id.
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: XXXXXXXXX
authorize: true
</script>
<script type="text/javascript">
function liAuth(){
window.IN.user.authorize().then(function(){
getProfileData();
});
}
function setLoginBadge(profile) {
if (!profile) {
profHTML = "<p>You are not logged in</p>";
}
document.getElementById("given_name").value =profile.firstName;
document.getElementById("family_name").value =profile.lastName;
document.getElementById("email").value = profile.emailAddress;
document.getElementById("verifyOauthRequestLinkedIn").submit();
}
function onError(error) {
console.log(error);
}
function getProfileData() {
IN.API.Profile("me")
.fields(["id", "firstName", "lastName", "pictureUrl",
"publicProfileUrl","email-address","headline"])
.result(function(result) {
setLoginBadge(result.values[0]);
})
.error(onError);
}
</script>
The javascript SDK is no longer supported, refer: [https://developer.linkedin.com/docs/getting-started-js-sdk]
So, the problem is that LinkedIN Api has changed its terms of service and you can no longer get the details like email ID
See available fields here [https://learn.microsoft.com/en-us/linkedin/shared/references/v2/profile/basic-profile?context=linkedin/consumer/context]
to get Full profile permission you will have to contact support and validate that your app provides additional functionality

API key not valid error when trying to get profile data

I'm trying to test Google login API. I want to retrieve some basic data after the client logs.
I created a Google API Console project and client ID (https://developers.google.com/identity/sign-in/web/devconsole-project)
Here is google official code (https://developers.google.com/api-client-library/javascript/samples/samples#LoadinganAPIandMakingaRequest):
<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: '5v2RzP7-xyQGNjxrD5suoPL9',
discoveryDocs: ["https://people.googleapis.com/$discovery/rest?version=v1"],
clientId: '298062822261-e5c09q8191mkho0o7n3n3obiq2eq2p3f.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'
}).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>
ClientId and apikey are from my google api.
I receive error 400
{
"error": {
"code": 400,
"message": "API key not valid. Please pass a valid API key.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.Help",
"links": [
{
"description": "Google developers console",
"url": "https://console.developers.google.com"
}
]
}
]
}
}
I don't understand what's wrong whit my api key. I followed all the steps from google documentation.
It seems you are using the client secret as API key. Isn't it?
To obtain an API key you must create it.
Under credentials (dev console) click on create credential, and then 'API Key'

How do you attach a picture to LinkedIn share from a blog post?

I have a blog that I want to make shareable via LinkedIn. The docs LinkedIn presents, while simply stated don't have enough detail for me to understand my use case. My use case requires me to dynamically put the picture and description in each blog post, which isn't being populated right now. This is an Angular project.
My current code:
post.html
<script>
delete IN;
$.getScript("https://platform.linkedin.com/in.js");
</script>
<script type="IN/Share" data-url={{webAddress}} data-counter="right"></script>
post.js
//I have all of my data in $scope variables in this area, which includes
// the picture and description I'd like to attach to the post.
Here is what the LinkedIn docs show as the right way to do this:
post.html
<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", shareContent);
}
// 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 share content on LinkedIn
function shareContent() {
// Build the JSON payload containing the content to be shared
var payload = {
"comment": "Check out developer.linkedin.com! http://linkd.in/1FC2PyG",
"visibility": {
"code": "anyone"
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
</script>
As I understand it, I need to populate the payload object with the right data/links. I have no clue how to do this based on what's in the docs.
Here are a few things I've tried/thought about along with where I'm currently stuck:
1) Get the data from post.js and put it in the payload object between the script tags in post.html. After doing some research, it is not possible to do this. Though I welcome being corrected if I'm wrong.
2) Bring the IN object into angular and populate the payload in post.js. This sounds really great but LinkedIn provides no html with which to call a function in post.js with Angular. Plus the LinkedIn code as presented takes care of formatting for the button and what comes after you click it.
3) Make an http call inside the script tags with JQuery. I rarely if ever use JQuery and have never used http for JQuery before. If this is even a feasible way to think of this problem, this is what I came up with:
<script type="IN/Share" data-url={{webAddress}} data-counter="right">
$.get( "https://public-api.wordpress.com/rest/v1.1/sites/myPost", function( response ) {
var post = _.first(_.filter(response.posts, function(n){return n.title.replace(/ /g,"-").replace(/[:]/g, "").toLowerCase() === $stateParams.id}));
var post1 = _.assign(post, {category: _.first(_.keys(post.categories)), pic: _.first(_.values(post.attachments)).URL, credit: _.first(_.values(post.attachments)).caption, linkCredit: _.first(_.values(post.attachments)).alt, fullStory: post.content.replace(/<(?!\s*\/?\s*p\b)[^>]*>/gi,'')});
**var image = post1.pic;**
**var title = post1.title;**
**var webAddress = window.location.href;**
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
function onSuccess(data) {
console.log(data);
}
function onError(error) {
console.log(error);
}
function shareContent(title, image, webAddress) {
var payload = {
"content": {
"title": title,
"submitted-image-url": image,
"submitted-url": webAddress
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
});
</script>
This solution did not result in a solution either. Where to go from here, I have no ideas. I'm sure this simple but idiosyncratic enough that I need a little hand holding.
Unfortunately, I have not worked with linkedin API.
Perhaps not all will be right in my example. But I've got to use a variable IN in angular and write about the call API wrapper.
An example of the use of plugins, see page LinkedIn Plugins.
Live example on jsfiddle.
//CallBackHell
function LinkedInServiceFunc(callback) {
callback && IN.Event.onDOMReady(callback);
}
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope, LinkedInService, ShareLinkedINService) {
console.log('ExampleController IN', IN);
console.log('ExampleController LinkedInService', LinkedInService);
LinkedInService.promise.then(function(LIN) {
console.log('Complete loading script for LinkedIn in ExampleController', LIN.Objects)
});
//Then you can interact with IN object as angular service. Like this
$scope.shareContent = function() { // Use the API call wrapper to share content on LinkedIn
// Build the JSON payload containing the content to be shared
var payload = {
"comment": $scope.comment,
"visibility": {
"code": 'anyone'
}
};
// 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);
}
console.log('shareContent', payload);
LinkedInService.promise.then(function(LIN) {
LIN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
});
}
$scope.shareContentService = function() {
//It's better way, i think
ShareLinkedINService.shareContent($scope.comment, 'anyone').then(function(data) {
console.log('success', data);
}).catch(function(data) {
console.err('error', data);
});
}
})
.service('LinkedInService', function($q) {
var defer = $q.defer();
LinkedInServiceFunc(function() {
defer.resolve(IN);
});
return {
promise: defer.promise
};
})
//You can create wrapper on IN API
.service('ShareLinkedINService', function(LinkedInService, $q) {
return {
shareContent: function(comment, visible) {
var defer = $q.defer();
var payload = {
"comment": comment,
"visibility": {
"code": visible
}
};
LinkedInService.promise.then(function(LIN) {
LIN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(defer.resolve)
.error(defer.reject);
});
return defer.promise;
}
}
})
.directive('linkedInShareButton', function(LinkedInService) {
return {
restrict: "E",
replace: false,
scope: {
shareUrl: "#",
counter:"#"
},
link: function(scope, elem, attr) {
var script = document.createElement('script');
script.setAttribute('type', 'IN/Share');
script.setAttribute('data-url', scope.shareUrl);
script.setAttribute('data-counter', scope.counter);
elem.append(script);
},
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript" src="//platform.linkedin.com/in.js">
authorize: false
onLoad: LinkedInServiceFunc
//I don't have api_key, because i delete it
// api_key: YOUR_API_KEY_HERE
// authorize: true
// onLoad: onLinkedInLoad
</script>
<body ng-app="ExampleApp">
<div>
<div ng-controller="ExampleController">
<input ng-model="comment">
<button ng-click="shareContent()">
shareContent
</button>
<button ng-click="shareContentService()">
shareContentService
</button>
<script type="IN/Share" data-url="www.mail.ru" data-counter="top"></script>
<linked-in-share-button share-url="www.mail.ru" counter="top"></linked-in-share-button>
</div>
</div>
</body>

How to get user email id using hello.js?

I am trying to login website with hello.js. I get the user name but I can't get user email id. How can I get this?
I am following this link.
This is my code :
<script src="hello.js" ></script>
<script>
hello.init({
google: "742850147964-r4pfusmgmp2mtfbngh387e30k3692p79.apps.googleusercontent.com"
}, {redirect_uri: 'index.php'});
hello.on('auth.login', function(auth) {
// Call user information, for the given network
hello(auth.network).api('/me').then(function(r) {
console.log("r.email = "+r.email);
console.log("r.name== = "+r.name);
});
});
</script>
I got my problem solved by simple changing in the hello.js.
for google :-
scope: {
basic: 'https://www.googleapis.com/auth/plus.me profile',
}
to
scope: {
basic: 'https://www.googleapis.com/auth/userinfo.email',
}
for facebook :-
scope: {
basic: 'public_profile',
}
to
scope: {
basic: 'public_profile,email',
}
First, please keep just one js file ref, you don't need both:
<script src="hello.js" ></script>
<script src="hello.min.js" ></script>
I tried adding the button for google and it worked, I think something is wrong with the configuration for Yahoo, check if the client id is correct.

Categories

Resources