Soundcloud ajax response not reached - javascript

I'm executing this query to get an user in SoundCloud.
I can see that the call is correctly done in Chrome network tab, after a click, however, it doesn't reach the javascript alert. So I can't retrieve the JSON response and add it to the DOM.
<script src="https://connect.soundcloud.com/sdk/sdk-3.1.2.js"></script>
<script>
SC.initialize({
client_id: '067320efe29b7da263fd8bb093911116',
redirect_uri: 'trofeosbalbino.com/beonerecords'
});
$("#embedTrack").click(function() {
SC.get('/users', {q: 'beonerecords'}, function (users) {
alert(users);
});
});
</script>

When using the SoundCloud API in a client side web application, you should use the SC.connect() method to authenticate the application. Try something such as the following:
SC.initialize({
client_id: '067320efe29b7da263fd8bb093911116',
redirect_uri: 'http://trofeosbalbino.com/beonerecords'
});
$("#embedTrack").click(function() {
SC.connect().then(function(){
SC.get('/users', {q: 'beonerecords'}, function (users) {
return users;
});
}).then(function(users){
alert(users);
});
});

Related

Google javascript client api : how to fetch profile name?

I am trying to implement SignIn with Google with redirect approach. I am following this link
My code looks like below
<script src="https://apis.google.com/js/platform.js?onload=startGoogleApp" async defer></script>
<script>
var startGoogleApp = function () {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: '#googleClientId',
ux_mode: 'redirect',
redirect_uri: '#googleRedirectUri',
fetch_basic_profile: true
});
auth2.signIn();
});
}
</script>
But issue is in Google's id_token is not having the name even though I have passed fetch_basic_profile: true I also tried with scope: 'profile'.
I want to fetch name along with email. don't know what am I doing wrong here.
I want it in part of token as it is mentioned in documentation I am following. I don't want fetch name with additional api call. Is it possible?
id_token looks like this
{
"iss": "accounts.google.com",
"azp": "*********",
"aud": "***********",
"sub": "*********",
"hd": "***.com",
"email": "*****#***.com",
"email_verified": true,
"iat": 1599717107,
"exp": 1599720707,
"jti": "*******"
}
Googles Id token is not guaranteed to return all of the profile claims on ever response.
If you want the users profile information then you should go though the Google People API. people.get
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.people.people.get({
"resourceName": "people/me",
"requestMask.includeField": "addresses",
"sources": [
"READ_SOURCE_TYPE_PROFILE"
]
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "YOUR_CLIENT_ID"});
});
Code ripped from the try me found on people.get

ADAL.js - acquire token for Graph API resources

I'm developing a SPA app in React that needs to integrate with AzureAD and the GraphAPI (implicit flow).
My question is very similar to: ADAL.js - Obtaining Microsoft Graph Access Token with id_token ... but the answer doesn't show me enough code to get me on my way.
So far, using just adal.js (v1.0.14), I can login & get an id_token, but I can't figure out how to use it to get access to make Graph API calls.
UPDATE: I know I'm correctly registered with the Azure portal, because I was able to login and get recent docs without adal.js or any lib ... just using home-made ajax calls.
Here's my code, which does the login/redirect, and then tries to get my recent docs:
// Initial setup
var adalCfg = {
instance : 'https://login.microsoftonline.com/',
tenant : 'common',
clientId : 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
postLogoutRedirectUri : window.location.origin,
extraQueryParameter : 'scope=Mail.ReadWrite+Files.Read+Files.ReadWrite+User.ReadBasic.All' // Is this the proper way to specify what resources I need access to?
};
var authContext = new Adal(adalCfg);
if(!authContext.getCachedUser()) {
authContext.login(); // redirects MS login page successfully
}
// Check For & Handle Redirect From AAD After Login
var isCallback = authContext.isCallback(window.location.hash); // Checks if the URL fragment contains access token, id token or error_description.
if(isCallback) {
authContext.handleWindowCallback(); // extracts the hash, processes the token or error, saves it in the cache and calls the registered callbacks with the result.
}
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST); // redirects back to /
}
// Try to get my recent docs - FAILS with InvalidAuthenticationToken error
// UDPATED authContext.acquireToken(authContext.config.clientId, function (error, token) {
authContext.acquireToken('https://graph.microsoft.com', function (error, token) {
$.ajax({
url: 'https://graph.microsoft.com/v1.0/me/drive/recent',
headers:{'authorization':'Bearer '+ token},
type:'GET',
dataType:'json'
}).done(function(res) {
console.log(res['value']);
});
});
What have I got wrong?
Update 2: I changed acquireToken per Fei's answer, but now when adal silently gets an access token for my resource, it fails to pass it to my API call.
Updated code:
adalCfg.endpoints.graphApiUri = "https://graph.microsoft.com";
authContext.acquireToken(adalCfg.endpoints.graphApiUri, function (errorDesc, token, error) {
console.log('errorDesc = ' + errorDesc)
console.log('token = ' + token)
console.log('error = ' + error)
$.ajax({
url: adalCfg.endpoints.graphApiUri + '/v1.0/me/drive/recent',
headers:{'authorization':'Bearer '+ token},
type:'GET',
dataType:'json'
}).done(function(res) {
console.log(res['value']);
});
});
And console output:
Token not being captured
The image shows the req for a token, which appears to succeed, because the next GET contains the access_token in the hash. However, acquireToken passes a null token to my Graph API call.
However, if I manually grab the access token out of the hash, I can successfully make the Graph API call.
Why doesn't adal pass the access token to my API call? It came back and is valid.
To call the Microsoft Graph, we need to get the specific token for this resource. Based on the code you were acquire the token using the authContext.config.clientId.
If you register the app on Azure portal, to get the access token for the Microsoft Graph, you need to replace authContext.config.clientId with https://graph.microsoft.com.
And to call the REST sucessfully, we need to make sure having the enough permission. For example, to list recent files, one of the following scopes is required:Files.Read,Files.ReadWrite,Files.Read.All,Files.ReadWrite.All,Sites.Read.All,Sites.ReadWrite.All(refer here).
Update
<html>
<head>
<script src="\node_modules\jquery\dist\jquery.js"></script>
<script src="node_modules\adal-angular\lib\adal.js"></script>
</head>
<body>
<button id="login"> login</button>
<button id="clickMe">click me</button>
<script>
$(function () {
var endpoints = {
"https://graph.microsoft.com": "https://graph.microsoft.com"
};
window.config = {
tenant: 'xxxx.onmicrosoft.com',
clientId: 'xxxxxxxxxxxxxxxxx',
endpoints: endpoints
};
window.authContext = new AuthenticationContext(config);
$("#login").click(function () {
window.authContext.login();
});
$("#clickMe").click(function () {
var user = window.authContext.getCachedUser();
console.log(user);
window.authContext.acquireToken('https://graph.microsoft.com', function (error, token) {
console.log(error);
console.log(token);
$.ajax({
url: 'https://graph.microsoft.com/v1.0/me/',
headers:{'authorization':'Bearer '+ token},
type:'GET',
dataType:'json'
}).done(function(res) {
console.log(res['userPrincipalName']);
});
});
}
);
function init(){
if(window.location.hash!="")
window.authContext.handleWindowCallback(window.location.hash);
}
init();
});
</script>
</body>
</html>

Getting at LinkedIn returned data from Javascript SDK

What I'd like to do is get at the returned data from the LinkedIn API named data from the function named getProfileData. How can I access the data that contains the information such as firstName and lastName but in getProfileData and not just in the function onSuccess?
<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);
// I want to see the profile data in here.
}
</script>
You must fix something in your code :
IN.API.Raw("/people/~:(id,first-name,last-name,location,positions)?format=json").result(onSuccess).error(onError);

Cannot authorize with LinkedIn

I'm trying to get the first name, surname and email from a user on my website with LinkedIn. This is what I've done:
In my LinkedIn App I've set the Default Scope (OAuth User Agreement) to:
r_basicprofile
r_contactinfo
w_share
r_emailaddress
I've correctly added my domain to Javascript API Domains. I didn't add a link to OAuth 2.0 Redirect URLs. But I don't know if that's mandatory (and which path to insert)?
I've also copied my API Key (Consumer Key).
Now in my HTML I have:
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
lang: en_US
api_key: myapikey
scope: r_basicprofile r_emailaddress
</script>
<input class="apply-with-linkedin" type="button" value="Apply with LinkedIn" id="btn-linkedin-apply">
<script type="text/javascript">
jQuery('#btn-linkedin-apply').click(function (e) {
e.preventDefault();
e.stopPropagation();
IN.User.authorize(function ()
{
IN.API.Profile('me').fields([
'firstName',
'lastName',
'emailAddress'
]).result(function (profiles)
{
var me = profiles.values[0];
if (me.hasOwnProperty('firstName')) {
jQuery('#apply-form #input-firstname').val(me.firstName);
}
if (me.hasOwnProperty('lastName')) {
jQuery('#apply-form #input-lastname').val(me.lastName);
}
if (me.hasOwnProperty('emailAddress')) {
jQuery('#apply-form #input-email').val(me.emailAddress);
}
});
});
});
</script>
But I always get the javascript error Cannot read property 'authorize' of undefined when I click the button. The IN.User is undefined.
What could be wrong with this? ...
UPDATE:
The javascript code where I specify my API Key, ... I've copied from the "Getting Started with the JavaScript SDK" from LinkedIn.
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: [API_KEY]
onLoad: [ONLOAD]
authorize: [AUTHORIZE]
lang: [LANG_LOCALE]
</script>
It seems likely that you are just experiencing problems with the asynchronicity of the library. I've modified the sample code from the Sign in with LinkedIn Javascript example slightly for you, but I think your issue will be solved with paying more attention to the callbacks so that you know a) the library is loaded, and b) the API call has successfully completed - before attempting to access any of the resulting data:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: YOUR_API_KEY_HERE
authorize: true
scope: r_basicprofile r_emailaddress
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) {
// Pre-populate your form fields here once you know the call
// came back successfully
}
// 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,lastName,emailAddress)").result(onSuccess).error(onError);
}
</script>

Google Analytics API Javascript: 403 Forbidden Error

For the love of Bob, someone please help me out...
I'm trying to use the Google Analytics API (Javascript Library) to get some Analytics info. I've registered the my app and set up the oauth2 stuff. I can return the access token jsut fine, but when i try to send a request to actually grab Analytics info, it returns a 403 forbidden error. Here's my code:
function auth() {
var config = {
'client_id': '[my_client_id]',
'scope': 'https://www.googleapis.com/auth/analytics.readonly'
};
gapi.auth.authorize(config, function() {
var retObj = gapi.auth.getToken();
makeRequest(retObj.access_token);
});
}
function makeRequest(accessToken) {
var restRequest = gapi.client.request({
'path': '/analytics/v3/data/ga',
'params': {
'access_token': accessToken,
'ids': 'ga:[table_number]',
'metrics': 'ga:pageviews,ga:uniquePageviews',
'start-date': '2011-11-01',
'end-date' : '2011-12-01'
}
});
restRequest.execute(function(resp) { console.log(resp); });
}
The auth() function is executed via a button click and like I said, getting the access token is not the issue. It's when I execute the makeRequest function that I get the 403 error. Anyone have any clue as to what the deal is here?
Thanks to anyone who answers in advance!!
In my case I was getting 403 Forbidden because in my browser I was logged into Google with an account that didn't have permission to the GA profile I was trying to access. Before discovering that issue, I was having trouble with the tableID for which Aksival posted the solution above.
Here's my working code for your reference:
<script type="text/javascript">
//GET THESE HERE https://code.google.com/apis/console/
var clientId = 'YOURCLIENTIDHERE';
var apiKey = 'YOURAPIKEYHERE';
//GET THIS HERE http://code.google.com/apis/analytics/docs/gdata/v3/gdataAuthorization.html
var scopes = 'https://www.googleapis.com/auth/analytics.readonly';
//INITIALIZE
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) {
makeApiCall();
} else {
requestAuth();
}
}
function requestAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
}
function makeApiCall() {
gapi.client.load('analytics', 'v3', function() {
var request = gapi.client.analytics.data.ga.get({
'ids':'ga:YOURTABLEIDHERE', 'start-date':'2012-01-01', 'end-date':'2012-02-01', 'metrics':'ga:visits', 'metrics':'ga:visits', 'start-index':1, 'max-results':1000
});
request.execute(function(resp) { console.log(resp.totalsForAllResults); });
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
I had the same issue. Turns out I was passing in the wrong [table_number].
You need to query
accounts/[account-id]/webproperties/[webproperties-id]/profiles
and use the 'id' field of the appropriate property. (I was using the internalWebPropertyId from the webproperties query at first, which is why it was failing.)
Works like a charm now.

Categories