Getting List of YouTube Channel Subscriptions using YouTube Data API V3 in JavaScript - youtube

I have been trying to get the list of subscriptions of my channel but unfortunately I get errors every time I run my code, I am describing each step below:
Step 1: I created this channel: My YouTube Channel
Step 2: I enabled the YouTube Data API V3 in Google Developer Console
Step 3: I created API Key and Google OAuth 2.0 Client ID, you can see the following screenshot:
Step 4: I checked the YouTube API Reference and checked some parameters here and got a successful response with all the subscriptions of my channel: YouTube API Reference for my Channel
Step 5: I copied the following code from the YouTube API Reference and placed my own API Key and Google OAuth 2.0 Client ID after I got a successful response for my channel:
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for youtube.subscriptions.list
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/code-samples#javascript
*/
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("YOUR_API_KEY");
return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.youtube.subscriptions.list({
"part": [
"subscriberSnippet,contentDetails"
],
"channelId": "UCLlE_JEV7I0pQ7fhY4BIrrQ"
})
.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"});
});
Step 6: Then I added the following buttons in my HTML code:
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
Step 7: When I execute the code, I get the following error messages:
Error 1:
"You have created a new client application that uses libraries for user authentication or
authorization that will soon be deprecated. New clients must use the new libraries instead;
existing clients must also migrate before these libraries are deprecated. See the [Migration
Guide](https://developers.google.com/identity/gsi/web/guides/gis-migration) for more
information."
Step 8: Then I click the authorize and load button and sign in to my channel and allow any requested rights. After that, when I click the execute button, then I get the following error:
"The requester is not allowed to access the requested subscriptions."
This is worth mentioning that this is my own channel, I login when required and I allow any rights that are requested. I also use my own Google Developer Console account, my own API Key and my own OAuth 2.0 Client ID. I have enabled the YouTube Data API V3 and I have set up everything properly. I can get the proper result from the YouTube API reference but I can't get it using JS.
Any help is appreciated in advance.

error one.
You have created a new client application that uses libraries for user authentication or
authorization that will soon be deprecated. New clients must use the new libraries instead;
existing clients must also migrate before these libraries are deprecated. See the Migration
Guide for more
information.
The code you are using is using the old google sign-in. You need to change this and use the new Google authorization library Authorizing for Web
Error two:
The requester is not allowed to access the requested subscriptions.
This error is a little harder to understand. First off when the authorization request pops up it should be asking you to pick a user and then a channel Make sure you select the channel that maps to the channel id you are selecting UCLlE_JEV7I0pQ7fhY4BIrrQ The YouTube data api is channel based you only have access to the single channel.
You are also using the "https://www.googleapis.com/auth/youtube.readonly" scope and the subscriptions list method documentation says it needs https://www.googleapis.com/youtube/v3/subscriptions which doesnt exist so I used https://www.googleapis.com/auth/youtube, but i would expect a different error message if this was the issue.
Notes:
I login when required and I allow any rights that are requested.
Make sure its to the correct channel.
I also use my own Google Developer Console account, my own API Key and my own OAuth 2.0 Client ID. I have enabled the YouTube Data API V3 and I have set up everything properly.
This has nothing to do with your access the client id, and api key just identify your application to Google they dont grant it access to anything. Thats what authorization is doing.
YouTube data api QuickStart for Authorizing for Web
Here is my QuickStart for this api.
<!DOCTYPE html>
<html>
<head>
<title>YouTube Data API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<p>YouTube Data API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
<button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
/* exported gapiLoaded */
/* exported gisLoaded */
/* exported handleAuthClick */
/* exported handleSignoutClick */
// TODO(developer): Set to client ID and API key from the Developer Console
const CLIENT_ID = '[Redacted]';
const API_KEY = '[Redacted]';
// Discovery doc URL for APIs used by the quickstart
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest';
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
const SCOPES = 'https://www.googleapis.com/auth/youtube';
let tokenClient;
let gapiInited = false;
let gisInited = false;
document.getElementById('authorize_button').style.visibility = 'hidden';
document.getElementById('signout_button').style.visibility = 'hidden';
/**
* Callback after api.js is loaded.
*/
function gapiLoaded() {
gapi.load('client', initializeGapiClient);
}
/**
* Callback after the API client is loaded. Loads the
* discovery doc to initialize the API.
*/
async function initializeGapiClient() {
await gapi.client.init({
apiKey: API_KEY,
discoveryDocs: [DISCOVERY_DOC],
});
gapiInited = true;
maybeEnableButtons();
}
/**
* Callback after Google Identity Services are loaded.
*/
function gisLoaded() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '', // defined later
});
gisInited = true;
maybeEnableButtons();
}
/**
* Enables user interaction after all libraries are loaded.
*/
function maybeEnableButtons() {
if (gapiInited && gisInited) {
document.getElementById('authorize_button').style.visibility = 'visible';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick() {
tokenClient.callback = async (resp) => {
if (resp.error !== undefined) {
throw (resp);
}
document.getElementById('signout_button').style.visibility = 'visible';
document.getElementById('authorize_button').innerText = 'Refresh';
await listSubscriptions();
};
if (gapi.client.getToken() === null) {
// Prompt the user to select a Google Account and ask for consent to share their data
// when establishing a new session.
tokenClient.requestAccessToken({prompt: 'consent'});
} else {
// Skip display of account chooser and consent dialog for an existing session.
tokenClient.requestAccessToken({prompt: ''});
}
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick() {
const token = gapi.client.getToken();
if (token !== null) {
google.accounts.oauth2.revoke(token.access_token);
gapi.client.setToken('');
document.getElementById('content').innerText = '';
document.getElementById('authorize_button').innerText = 'Authorize';
document.getElementById('signout_button').style.visibility = 'hidden';
}
}
/**
* Print metadata for first 10 Albums.
*/
async function listSubscriptions() {
let response;
try {
response = await gapi.client.youtube.subscriptions.list({
'pageSize': 10,
'part' :[ "snippet,subscriberSnippet,contentDetails" ],
"channelId": "UCyqzvMN8newXIxyYIkFzPvA",
'fields': 'items(id,snippet(title))',
});
} catch (err) {
document.getElementById('content').innerText = err.message;
return;
}
const subscriptions = response.result.items;
if (!subscriptions || subscriptions.length == 0) {
document.getElementById('content').innerText = 'No subscriptions found.';
return;
}
// Flatten to string to display
const output = subscriptions.reduce(
(str, subscription) => `${str}${subscription.snippet.title} (${subscription.id}\n`,
'albums:\n');
document.getElementById('content').innerText = output;
}
</script>
<script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
<script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
</body>
</html>

Related

Microsoft Graph API Unauthorized Error 401

I am new to MS graph api. I am learning this API and I followed this tutorial https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-nodejs-console and it works fine for me when retrieving the user. here is the code
async function main() {
try {
// here we get an access token
const authResponse = await auth.getToken(auth.tokenRequest);
console.log("get auth reespones ", authResponse)
const options = {
method: 'get',
headers: {
Authorization: `Bearer ${authResponse}`
}
};
// call the web API with the access token
const users = await fetch.callApi(auth.apiConfig.uri, options);
console.log("get users ", users)
} catch (error) {
console.log("error here",error);
}
};
But I am trying to call other API and I have a problem accessing the calendar API.
here is the new function I use to call the calendar api in ms graph.
async function getcalendar() {
try {
// here we get an access token
const authResponse = await auth.getToken(auth.tokenRequest);
const options = {
method: 'get',
headers: {
Authorization: `Bearer ${authResponse}`,
Prefer: `outlook.timezone="Pacific Standard Time"`
}
}
// call the web API with the access token
const users = await fetch.callApi('https://graph.microsoft.com/v1.0/me/calendar', options);
console.log("get users ", users)
} catch (error) {
console.log("error is here ",error);
}
};
in my application in azure I already set all the permissions
I have no idea why it keeps saying unauthorized.
Any help is appreciated. Thank you
Try to set Calendars.Read, Calendars.ReadWrite for Delegated permission type instead of Application type.
getSchedule api doesn't support personal Microsoft account.
You cannot use personal accounts to hit the me/calendar/getschedule because this is not supported.
The permissions works only for work or school accounts or with App token.
As you are using Application context you need to make the call something like below.
/users/{id|userPrincipalName}/calendar/getSchedule as there is no meaning for me if there is no user involved.

msal.js cannot get the refresh_token even though offline_access is available and I can see it in the return call

I use msal.js to get access to the Microsoft Graph Api and I have gotten it working for the post part.
As you can see on the images I get the refresh_token in the response payload but not in the actual output when I console log it, how do I do this ?
Then thing is I need this refresh_token as the the place they auth their microsoft account is not the same place as the data is actually shown.
Let me explain
We are a infoscreen company and we need this to show the calendar of the people who authed when they have inserted it on the presentation.
so the flow is as follows:
They install the app and login with their Microsoft 365 account to give us access to this data. (this is the part that returns the refresh token and access Token).
They go to the presentation and insert the app in the area they want to show it.
on the actual monitor that could stand anywhere in the world the calendar would now show up.
But after 1 hour the session would expire so we need to generate a new access_token and for this we need the refresh_token.
At the step of loginPopup I can see there is a refreshToken
but when I use the data it is gone, I also tried to request token silently
Also I updated to the newest version of msal-browser.min.js version 2.1 that should support it.
async function signInWithMicrosoft(){
$(".notification_box", document).hide();
$("#table_main", document).show();
const msalConfig = {
auth: {
clientId: '{CLIENTID}',
redirectUri: '{REDIRECTURI}',
validateAuthority: false
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: false,
forceRefresh: false
},
};
const loginRequest = {
scopes: [
"offline_access",
"User.Read",
"Calendars.Read",
"Calendars.Read.shared"
],
prompt: 'select_account'
}
try {
const msalClient = new msal.PublicClientApplication(msalConfig);
const msalClientLoggedIn= await msalClient.loginPopup(loginRequest).then((tokenResponse) => { console.log(tokenResponse); });
msalClientAccounts = msalClient.getAllAccounts();
var msalInsertAccount = true;
var tableMainAsText = $("#table_main", document).text();
if(typeof msalClientLoggedIn.idTokenClaims !== 'undefined'){
if(tableMainAsText.indexOf(msalClientLoggedIn.idTokenClaims.preferred_username)>-1){
msalInsertAccount = false;
}
if(msalInsertAccount){
var tableRow = "<tr>"+
"<td>"+msalClientLoggedIn.idTokenClaims.name+" ("+msalClientLoggedIn.idTokenClaims.preferred_username+") <span style='display: none;'>"+msalClientAccounts[0].username+"</span><input type=\"hidden\" name=\"app_config[exchange_online][]\" class=\"exchange_online_authed_account\" value=\""+msalClientLoggedIn.idTokenClaims.preferred_username+","+msalClientLoggedIn.idTokenClaims.name+"\" /></td>"+
"<td class=\"last\">Fjern adgang</td>"+
"</tr>";
$("#table_body", document).append(tableRow);
$("#table_foot", document).hide();
}
}
}catch(error){
$(".notification_box", document).show();
}
}

use YouTube Data API (v3) to update a video via API keys got a 401 error

In my java back-end app ,I want to use quartz job to change my youtube videos status from public to private every week, it is a scheduled job. So I use YouTube Data API (v3)'s Videos Update to do this work.
See YouTube
Data API
Reference Videos: update and Code Samples Resource>videos,Method>update.
According to Obtaining authorization credentials,there are two ways to obtain authorization credentials ,one is OAuth 2.0 the other is using API Keys.I choose to use API Keys because it is simpler than oauth2.
I have already retrieved API Keys from Google API Console , I run the code samples copied from youtube's documentation Resource>videos,Method>update and run them ,they both got 401 error.
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"errors": [
{
"message": "Login Required.",
"domain": "global",
"reason": "required",
"location": "Authorization",
"locationType": "header"
}
],
"status": "UNAUTHENTICATED"
}
}
I do not why i can not work by using API Keys to call the videos.update. I dont want to use OAuth2, I think use API Keys is the better way.Because, it is impossible to open a browser window and make the user to do a oauth login and authorization in a quartz job, can anybody tell me what is the problem and how to do?
the code samples are as below
Java Based
/**
* Sample Java code for youtube.videos.update
* See instructions for running these code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#java
*/
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Video;
import com.google.api.services.youtube.model.VideoLocalization;
import com.google.api.services.youtube.model.VideoSnippet;
import com.google.api.services.youtube.model.VideoStatus;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
public class ApiExample {
// You need to set this value for your code to compile.
// For example: ... DEVELOPER_KEY = "YOUR ACTUAL KEY";
private static final String DEVELOPER_KEY = "...";
private static final String APPLICATION_NAME = "API code samples";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/**
* Build and return an authorized API client service.
*
* #return an authorized API client service
* #throws GeneralSecurityException, IOException
*/
public static YouTube getService() throws GeneralSecurityException, IOException {
final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
return new YouTube.Builder(httpTransport, JSON_FACTORY, null)
.setApplicationName(APPLICATION_NAME)
.build();
}
/**
* Call function to create API service object. Define and
* execute API request. Print API response.
*
* #throws GeneralSecurityException, IOException, GoogleJsonResponseException
*/
public static void main(String[] args)
throws GeneralSecurityException, IOException, GoogleJsonResponseException {
YouTube youtubeService = getService();
// Define the Video object, which will be uploaded as the request body.
Video video = new Video();
// Add the id string property to the Video object.
video.setId("9BByHcBGMP4");
// Add the localizations object property to the Video object.
HashMap<String, VideoLocalization> localizations = new HashMap<>();
VideoLocalization esLocalization = new VideoLocalization();
esLocalization.setDescription("Esta descripcion es en español.");
esLocalization.setTitle("no hay nada a ver aqui");
localizations.put("es", esLocalization);
video.setLocalizations(localizations);
// Add the snippet object property to the Video object.
VideoSnippet snippet = new VideoSnippet();
snippet.setCategoryId("22");
snippet.setDefaultLanguage("en");
snippet.setDescription("This description is in English.");
String[] tags = {
"new tags",
};
snippet.setTags(Arrays.asList(tags));
snippet.setTitle("There is nothing to see here.");
video.setSnippet(snippet);
// Add the status object property to the Video object.
VideoStatus status = new VideoStatus();
status.setPrivacyStatus("private");
video.setStatus(status);
// Define and execute the API request
YouTube.Videos.Update request = youtubeService.videos()
.update("snippet,status,localizations", video);
Video response = request.setKey(DEVELOPER_KEY).execute();
System.out.println(response);
}
}
Javascript Based
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for youtube.videos.update
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#javascript
*/
function loadClient() {
gapi.client.setApiKey("...");
return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded before calling this method.
function execute() {
return gapi.client.youtube.videos.update({
"part": [
"snippet,status,localizations"
],
"resource": {
"id": "9BByHcBGMP4",
"snippet": {
"categoryId": "22",
"defaultLanguage": "en",
"description": "This description is in English.",
"tags": [
"new tags"
],
"title": "There is nothing to see here."
},
"status": {
"privacyStatus": "private"
},
"localizations": {
"es": {
"title": "no hay nada a ver aqui",
"description": "Esta descripcion es en español."
}
}
}
})
.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");
</script>
<button onclick="loadClient()">load</button>
<button onclick="execute()">execute</button>
</body>
</html>
According to the official doc you yourself quoted, for to invoke the Videos.update API endpoint, you need to be properly authorized:
Authorization
This request requires authorization with at least one of the following scopes (read more about authentication and authorization).
Scope
https://www.googleapis.com/auth/youtubepartner
https://www.googleapis.com/auth/youtube
https://www.googleapis.com/auth/youtube.force-ssl
Consequently, there's no way you can avoid using OAuth 2.0 authentication/authorization flow within you app. Note that API keys are used and useful for reading-only public data.
For the part of your question that says:
[...] it is impossible to open a browser window and make the user to do a oauth login and authorization in a quartz job [...]
the API has solutions. Do read the following two docs: OAuth 2.0 for Mobile & Desktop Apps and Using OAuth 2.0 for Web Server Applications.
A brief, top-level description of what you'll have to do is provided by the answer I gave recently to a similar question. That answer may help you understand more easily the way to attain a solution to your problem.

How do I update my google sheet in v4?

I am new in google sheets v4 and I just want to know how can I update my google sheet in v4. I am using Nodejs and following is the code sample link which I am using Method: spreadsheets.values.update
You can use the sample script of the link. In you case, combining Quickstart and the sample script may be useful for you. The sample script is as follows.
In this sample script, the text of sample text is imported to the cell a1 of Sheet1.
Sample script :
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Google Sheets API.
authorize(JSON.parse(content), valuesUpdate);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* #param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
function valuesUpdate(auth) {
var sheets = google.sheets('v4');
var request = {
// The ID of the spreadsheet to update.
spreadsheetId: 'my-spreadsheet-id', // TODO: Update placeholder value.
// The A1 notation of the values to update.
range: 'Sheet1!a1:a1', // TODO: Update placeholder value.
// How the input data should be interpreted.
valueInputOption: 'RAW', // TODO: Update placeholder value.
resource: {'values': [['sample text']]},
auth: auth,
};
sheets.spreadsheets.values.update(request, function(err, response) {
if (err) {
console.error(err);
return;
}
// TODO: Change code below to process the `response` object:
console.log(JSON.stringify(response, null, 2));
});
}
IMPORTANT :
Please modify my-spreadsheet-id to yours in above script.
This sample script supposes that the script of Quickstart works fine.
After run the script of Quickstart, please remove sheets.googleapis.com-nodejs-quickstart.json once, before run the above sample script. After remove the file, please run the above script. By this, the refresh token with the new scopes is retrieved and it is used for updating values.
If you want to use this script, please use googleapis v24 or less. Because the latest version doesn't work. Because the following error occurs, even if valueInputOption is set.
Error: 'valueInputOption' is required but not specified
I believe that this error will be modified in the near future.
If I misunderstand your question, I'm sorry.

Meteor acounts add info from Twitter accounts

I'm trying to figure out how I can add additional information from a user's Twitter account to the created account on a Meteor installation.
In particular I am trying to access the user's bio via Twitter Api v 1.1 and am not successful in doing so.
Therefore I am trying to extend Accounts.onCreateUser(function(options,user) {}); with the Twitter bio. How do I do that? And then access this data from a template?
Here's a perfect answer for returning data from Github, however I've had trouble porting this approach over to Twitter as the authenticating service: Meteor login with external service: how to get profile information?
You could do it on this way:
Accounts.onCreateUser(function (options, user){
user.profile = options.profile || {};
//Twitter returns some useful info as the username and the picture
if(user.services.twitter){
user.profile.picture= user.services.twitter.profile_image_url_https;
user.profile.username= user.services.twitter.screenName;
}
return user;
});
For getting the data from the Twitter API I´m using the node package oauth:
OAuth = Npm.require('oauth');
oauth = new OAuth.OAuth(
'https://api.twitter.com/oauth/request_token',
'https://api.twitter.com/oauth/access_token',
'consumerKey',
'secretKey',
'1.0A',
null,
'HMAC-SHA1'
);
getTwitterUserData: function (id) {
var accountUser = AccountsUserCollection.findOne({_id: id});
var url = "https://api.twitter.com/1.1/users/show.json?screen_name="+accountUser.screen_name;
oauth.get(url, 'accessToken', 'accessSecret', function (err, data, response) {
if(err){
console.log(err);
}
if(data){
Fiber(function () {
AccountsUserCollection.update({_id: accountUser._id}, {$set: {dataTwitter: JSON.parse(data)}});
}).run();
}
if(response){
Log.info(response);
}
});
}

Resources