Linkedin API SignUp Button - I am a beginner - javascript

I am making a website for the first time. I am sorry for any dumb question but I really have no background. However, I am trying to learn.
I developed the website on Weebly (www.i2i.network) and I am trying to include a LinkedIn SignUp button through their API service to monitor the people who are using the website.
So far I copied and pasted what I have found on the LinkedIn SDK guide
<script type="in/Login"></script>
<script type="text/javascript" src="//platform.linkedin.com/in.js">
IN.User.logout(callbackFunction, callbackScope);
api_key: [API] //I put my API key here
authorize: true
onLoad: onLinkedInLoad
lang: [LANG_LOCALE]
</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);
}
</script>
The button appeared the first time and it opens the connection to my LinkedIn profile. That's exciting! :D (Geek)
At this point I still don't know if I retrieve any data from the LinkedIn API service and if "yes" how to manage them and possibly include them in Intercom.io.
As far as I understood I should receive from LinkedIn API the following:
{
"firstName": "Frodo",
"headline": "Jewelery Repossession in Middle Earth",
"id": "1R2RtA",
"lastName": "Baggins",
"siteStandardProfileRequest": {
"url": "https://www.linkedin.com/profile/view?id=…"
}
}
Do I actually receive the answer? How do I read it? How do I use it in the following Intercom.io script?
<script>
window.intercomSettings = {
app_id: "k9sz4pfb",
name: "Nikola Tesla", // Full name
email: "nikola#example.com", // Email address
created_at: 1312182000 // Signup date as a Unix timestamp
};
</script>
<script>(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',intercomSettings);}else{var d=document;var i=function(){i.c(arguments)};i.q=[];i.c=function(args){i.q.push(args)};w.Intercom=i;function l(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/k92zopfb';var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s,x);}if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})()</script>
I know this might be a very basic question but I am starting from zero and I like to learn by practicing...
Furthermore, if you have any suggestion about website or tutorial where I could learn step-by-step it will be really appreciated.
Thank you for your help,
Giacomo

Double check the syntax but this should get you started.
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
var dataOutput =
// I added the callback event DONE. This assures the data method is called when the this API call is successful and complete.
var dataOutput = IN.API.Raw("/people/~").result(onSuccess).error(onError).done( {
if (dataOutput != null) {
DoSomethingWithYourData(dataOutput);
}
});
}
function DoSomethingWithYourData(dataOutput) {
console.log(dataOutput);
// Parse your data or assign it to a control. do whatever here.
}
And to answer your other question, you can add this to a JS script file and reference it on other pages, but you would have to keep any control IDs/class names added to this script file the same, so my tip would be to keep this file very generic so that it does not depend on anything else and only deals with working with LinkedIn's data.
I recommend these links for further reading so that you can expand on your code.
Jquery Parse JSON
JQuery AJAX
JQuery Callbacks

Related

JavaScript and Google API troubles

I'm trying to adapt a simple search script from this question. However, I'm trying to determine why the method loadApi is undefined. I'm also having trouble tracking down the source of the problem, because the JS supplied by Google is... difficult to read.
Here is the script, once again:
<script>
googleApiClientReady=function() {
loadApi() = function() {
return new Promise(function(resolve,reject){
gapi.client.setApiKey('<redacted>');
gapi.client.load('youtube', 'v3', resolve);
});
};
loadApi().then(function() {
var q = 'pink floyd';
var request = gapi.client.youtube.channels.list({
part: 'statistics',
forUsername : 'GameSprout'
});
request.execute(function(response) {
var str = JSON.stringify(response.result);
alert(str);
});
});
};
</script>
And here is the error in question:
It may not require authentication to preform a search but your application still needs to be reregistered and you will need to at the very least use an API key.
Kindly note I a not a JS dev I just copied this example from the documentation. There are several that show how to access public apis.
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
...
}).then(...)
Note: channels.list is a part public part private method as far as I can see. Some of the parameters will only work if you are authenticated .
mine boolean
This parameter can only be used in a properly authorized request. Set this parameter's value to true to instruct the API to only return channels owned by the authenticated user.

Google Execution API with Simple Access API key to access AUTHORS spreadsheet?

From what I understand, deploying a Google Script as a Google Execution API allows me to call each function from my script separately as and when I need it.
I have a webpage with some buttons and forms that I want to run the functions within my script on.
I have a Google Script with some (example) functionality:
function addPlayer(name,email,group) {
//name email group
var ss = SpreadsheetApp.openById(SHEET_ID); //Sheet belonging to me, script author.
var sheet = ss.getSheetByName("Players");
sheet.appendRow(new Date(),name,email,group);
}
function updatePlayer() {
//update player row with new data
//name email group
}
function anotherFunction() {
//store some data in another sheet within spreadsheet.
}
function listPlayers()
{
//return data from sheet
}
And a sample webpage which wants to run functions from that script:
function OnLoadCallback() { //on gapi load
gapi.client.setApiKey(API_KEY); //developer dashboard generated browser API key
// Create execution request.
var request = {
'function': 'addPlayer',
'parameters': [name,email,group],
'devMode': true
};
// Make the request.
var op = gapi.client.request({
'root': 'https://script.googleapis.com',
'path': 'v1/scripts/' + scriptId + ':run',
'method': 'POST',
'body': request
});
}
I get a 401 UNAUTHENTICATED error at the moment saying I do not have valid auth credentials.
Is it possible for this webpage to use the API without requiring each webpage visitor to oAuth (which doesn't make sense to me as it's not THEIR data/sheet I am trying to access but my own? I know if I deploy as web app I can set it to execute AS me, but is there any similar equivalent for the Execution API?
I chose to use execution script as I need to be able to run several different functions, and as a webapp my only option would be the doPost() which wouldn't let me differentiate adding to sheets/updating sheets/reading from sheets easily?
Am I missing something completely here? If this is entirely the wrong approach I would be super grateful if someone could point me in the right direction.
Thanks!
Based on this SO question, by adding SpreadsheetApp calls, you've modified the authentication scope required for your script. You need to update your scope to include Spreadsheets.
To use the API, you must supply a valid OAuth token that covers all the scopes used by the script. To find the correct scopes to include in the authentication token, open the project in the script editor, then select File > Project properties and click the Scopes tab.
Here is the link for the list of OAuth scope.
Check also this SO question for more information.

Authorizing xAPI interactions through Javascript triggers against my LRS

I've constructed a course in Storyline2, and defined several triggers via javascript as xAPI (tincan) activities.
I have an LRS endpoint link and authorization token, but I'm yet to understand where these credentials should be embedded in order for the whole thing to function properly.
I was given this at another message board:
var tincan = new TinCan({url: window.location.href});
Which of these needs to be replaced by one of the above mentioned? I'm guessing another should be added via "+" after "href".
That example code (which I guess you got from the article I wrote here: http://tincanapi.com/share-statements-between-courses/ ) is envisaging that you will launch the Storyline content from something like an LMS. In that case you will enter the endpoint and authorization details in the LMS settings, and the LMS will pass those to Storyline.
See: http://tincanapi.com/share-statements-between-courses/
If you want to put the details directly in the package, see the example code here: http://rusticisoftware.github.io/TinCanJS/
(included below for convenience)
var lrs;
try {
lrs = new TinCan.LRS(
{
endpoint: "https://cloud.scorm.com/tc/public/",
username: "<Test User>",
password: "<Test Password>",
allowFail: false
}
);
}
catch (ex) {
console.log("Failed to setup LRS object: " + ex);
// TODO: do something with error, can't communicate with LRS
}

How to access Google Translate API

<html>
<head>
<script>
function appendResults(text) {
var results = document.getElementById('results');
results.appendChild(document.createElement('P'));
results.appendChild(document.createTextNode(text));
}
function makeRequest() {
var request = gapi.client.urlshortener.url.get({
'shortUrl': 'http://goo.gl/fbsS'
});
request.then(function(response) {
appendResults(response.result.longUrl);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
}
function init() {
gapi.client.setApiKey('*My API key*');
gapi.client.load('urlshortener', 'v1').then(makeRequest);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>
</head>
<body>
<div id="results"></div>
</body>
</html>
This is the sample code from getting started page to use Google Translate API here. I used it exactly as instructed, and I already changed the "API key" part with my API key. Can anyone tell me why this code doesn't work? Is there any other library that I need to import to this .html ?
How to get access to the Google Translate API? How to get an API Key?
1. Sign Up for Free RapidAPI Account:
To begin using the Google Translate API, you’ll first need to sign up for a free RapidAPI developer account. With this account, you get a universal API Key to access all APIs hosted in RapidAPI.
RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and a community of over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps.
2. Subscribe to Google Translate API:
Once signed in, log in to your RapidAPI account and access the API console. Click on the “Pricing” tab and opt-in for the basic subscription that gives you 50 free API calls to Google Translate API per day.
3. Test Your API Subscription:
Let’s test your Google Translate API subscription. Select the “POST Translate” endpoint within the API console. The default values of parameters indicate that we are going to translate the text “Hello, world!” to Spanish (with language code ‘es’). Trigger the API, and you should see the translated text in the API response (JSON format).
So, “Hello, world!” in Spanish translates to “Hola Mundo!”.
You can also check language translator javascript code for website
The referenced page provides an example of a Translation API call, whose core lines are:
// Executes an API request, and returns a Promise.
// The method name language.translations.list comes from the API discovery.
return gapi.client.language.translations.list({
q: 'hello world',
source: 'en',
target: 'de',
});
Your sample code does not seem to include an API call.

How to set access token on analytics API?

i was wondering, the documentation has tutorials for implementing use of the Analytics API in several languages.
Now in PHP they show how to store the access token and maintain it , now i assume the JS somehow mentains it in some sort of local storage but i don't wish the user to authenticate each time he visitis so my plan is to save the access & refresh token in my database and simply applying it to the client-side instead of going through the all pop up procress.
According to tutorial this :
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, result);
Fires the popup which returns the access token but i'll say again i'm intrested in submiting token from database.
How can that be done?
is there some gapi.auth.setToken(token) method which after i could make calls to Core Reporting API?
I arrived here looking for a solution using this after having already written PHP to do the auth using google's PHP client libraries. I wanted to share the stored token as you mentioned, and be able to use javascript without re-authenticating, and/or triggering the popup (there may be a solution to this using the .init(callback) method, see docs/links at end).
Is there some gapi.auth.setToken(token) method
It turns out you can, there is the exact setToken(token) function you mention, and, you can even share the auth token generated earlier in PHP. What I'm not sure about yet, is if we should do it :)
I'm using PHP to do the initial auth, but presumeably in the javascript client you'd be able to call setToken() on something that you'd stored with getToken() in the same manner as this example. There may also be better approaches to this, like CORS (see links at end) mentioned in the API Authentication docs that I haven't had a chance to investigate any of these yet, but, I can give an example to answer the question, and might be useful to others needing the same behaviour
I first found Google developer Dan Holevoet's blog post with some sample JS code.
http://googleappsdeveloper.blogspot.com.au/2011/12/using-new-js-library-to-unlock-power-of.html
It's great to be able to query the API directly with javascript, and dynamically load lists etc, but the thing that worried me about this of course was storing clientid etc in js..
// Snippet from Dan's post
var clientId = 'YOUR_CLIENT_ID';
var apiKey = 'YOUR_API_KEY';
var scopes = 'https://www.googleapis.com/auth/calendar';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
checkAuth();
}
But, according to Dan in an answer to the same question:
The apiKey is used in conjunction with designated referrers, which you
must declare in the APIs Console. If the key is sent from an
unauthorized referrer, it will not work. You should make your accepted
referrer list as limited as possible to ensure that others do not use
your apiKey for their own requests.
Now, my example is for the calendar API, but it all seems pretty consistent with the other APIs as well.
Note: This snippet was for proof-of-concept purposes only, and probably shouldn't be used in production. I assume the referrer protection mentioned makes something like this OK to do, but more thought needs to be given. It could be done by hidden input, AJAX call etc.. But in the end, they're all going to be visible in the javascript.
What I did to test the concept was to:
Authenticate via PHP client libs, using the same script/URL as callback (see [API console][2] for these callbacks)
On sucessful auth, in callback, set a global javascript variable in the page to the stored PHP auth token
Once page is loaded, on your first click event to use the javascript (or even in document ready), call authMe() to set the token
Then proceed as normal, calling any javascript API methods that you have given scope to in the initial PHP authentication process (in this case makeApiCall())
Like so:
In the php callback routine, regardless of whether authenticated yet (assuming that your callback URL is the same script), make this var global
<script type="text/javascript">
// A place to stick PHP's auth token once the auth dance is done
var dodgey_global_access_token = {};
</script>
Now, in php callback routine once we've checked that we're authenticated, and $_SESSION['token'] = $client->getAccessToken(); has been called (IE storing the auth token somewhere for later), or at least $client->getAccessToken() has something meaningful:
<script type="text/javascript">
// Set the js var via PHP here.. Yeck... Note json encode in php and parse in jquery
dodgey_global_access_token = $.parseJSON (<?php echo json_encode ($client->getAccessToken() ); ?>);
// dodgey_global_access_token now contains the auth token structure
// Removed auth-related functions in Dan's code - we'll already have a token
// Dan's orig function to list events in 'primary' calendar
function makeApiCall() {
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary'
});
request.execute(function(resp) {
for (var i = 0; i < resp.items.length; i++) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(resp.items[i].summary));
document.getElementById('events').appendChild(li);
}
});
});
}
// My function to setToken with the token injected from PHP authentication
function authMe () {
// Stuff the token into the gapi object
gapi.auth.setToken( dodgey_global_access_token );
// Now call the original 'makeAPICall' function now that we're 'authenticated'
makeApiCall();
}
</script>
Note: I used jquery in my example to quickly parse the JSON, we're already using it in the project, but if not, you'll have to find another library to do so
Relevant/useful docs:
// Sorry, as a new poster I can only post 2 hyperlinks,
// so embedding this in code snippet
//
// http://code.google.com/p/google-api-javascript-client/wiki/ReferenceDocs#gapi
// http://code.google.com/p/google-api-javascript-client/wiki/Authentication
// http://code.google.com/p/google-api-javascript-client/issues/detail?id=22
// http://code.google.com/p/google-api-javascript-client/wiki/CORS
// https://code.google.com/apis/console
Let me know if anything's unclear, and can post a working sample to demo.
Google API documentation has changed a bit from when this answer was first provided. google-api-javascript-client is no longer the recommended library for accessing google api libraries and Google suggests using discovery documents to load specific libraries.
As a result, the workflow that you are looking for in order to load all the libraries and set the access token would look like this:
var token = 'someaccesstokenfromoauth2'
gapi.load('client:auth2', function(){
gapi.client.load(
'https://analyticsreporting.googleapis.com/$discovery/rest',
'v4'
).then(function(){
gapi.auth.setToken({ access_token: token })
// business logic with gapi.client.analyticsreporting()
})
})
Load gapi with:
<script src="https://apis.google.com/js/api.js"></script>

Categories

Resources