Getting started with the YouTube Analytics API? - php

How can I "link" a person's youtube account to an account on my website? I am trying to get Analytics from videos, how much money they have made, etc. I know i am supposed to be using the YouTube Analytics API, but I see tons of different documentation and it gets SO confusing. Are there any PHP libraries I can use to get this data and to link the user's account to my web application? I am also confused on where I get an OAuth Key.
Here are some sites i have looked at:
1) Site One
2) Site Two
On site two, I looked at the examples, but nothing really helped me understand even how to start.

A lot of the relevant info you'll need can be found in this document:
https://developers.google.com/youtube/analytics/authentication
Basically, it outlines the following 4 steps:
1) Register your web app in the Google Cloud Console
This is needed so you can get a client secret and client ID, which your server-side PHP code will need in order to do the oAuth flow (and get the right scope to be able to query analytics data for the user that's authenticating). See here for more info on how to do this:
https://developers.google.com/youtube/analytics/registering_an_application
The most important things to do as your register your app are to turn on the YouTube Analytics API and create a new client ID for your web application.
2) When a user visits your page, you'll need some way (i.e. a login button, for example) to trigger the start of the oAuth flow. When this is triggered, you'll want to redirect the browser to this URL:
https://accounts.google.com/o/oauth2/auth?client_id=[YOUR CLIENT ID]&redirect_uri=[THE URL YOU WANT THE USER TO BE DIRECTED TO AFTER AUTHENTICATION]&scope=https://www.googleapis.com/auth/yt-analytics.readonly&response_type=code&access_type=offline
This will present them with a window asking them if they want to give permission to your app to read their analytics. Note that the client id parameter is the same that you received when you registered your app in step 1. That registration process also will require you to set the allowed redirect URIs, so here you must pass one you set in the registration.
3) The redirect URL will be requested, from step two, by Google's servers with a "code" parameter attched. So when it is requested, it should immediately do a POST to another URL (i.e. with cURL or something similar), that looks like this:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=[CODE THAT CAME IN AS A GET PARAMETER] &client_id=[YOUR CLIENT ID]&client_secret=[YOUR CLIENT SECRET]&redirect_uri=[THE REGISTERED REDIRECT URI]&grant_type=authorization_code
If you do it as a POST with cURL, then the response will be a JSON packet that has an access token and a refresh token.
4) Your php page can store these both (in your DB, for example), note that the user should be treated as logged in at this point, and you can use the access token in the header of all API requests send to the analytics API.
https://developers.google.com/youtube/analytics/authentication#OAuth2_Calling_a_Google_API
IT'll expire in an hour, so with each request you should be checking its age (i.e. when you stored it in the DB, you could store the expiry time, for example), and when you're getting close you can use the refresh token to get a new access token.
https://developers.google.com/youtube/analytics/authentication#OAuth2_Refreshing_a_Token
You can now redirect them to wherever your app needs them to be to start interfacing with the API.
Seems like a lot? It can be, but once you get the paradigm down it's pretty simple. And you asked about a client for PHP, and thankfully there is one:
https://github.com/google/google-api-php-client
It's got simple handlers for the whole oAuth2 flow, and also has a YouTube analytics service object that sets the access token automatically for you as it's making its various calls.

Related

Native login with Instagram API

I've been working on an app for IG, and was looking at other websites which use the IG API. I came across this website which allows the user to login by entering their username and password directly into the site. It is then able to access the IG API and fetch things like follower count, however without the user authenticating an IG API Client as would normally be required. The app can even perform functions such as liking pictures using your account, which as far as I know also requires you to authenticate an app with elevated privileges.
My question is, how is this app able to login users without using OAUTH which appears to be the only method of authentication?
They probably use a web automation framework like Selenium to take actions like auto-linking content by actually logging in to the Instagram web site with the accounts credentials and simulating mouse clicks, etc. to get the job done. In other words their "script" just looks like a very active user to Instagram because it's all coming from interactions between a web browser and their site.
They definitely are not using the API. Several reasons you can know this:
no OAuth flow to get an access_token
they don't appear in the authorized applications section if you log in and manage your profile
what they are doing is a violation of the API Terms of Use. See the following under "shall not"
Use the Instagram APIs to post automated content to Instagram, including likes and comments that were not initiated and entered by an Instagram user.
I'm no lawyer and I have no inside information, however it seems clear enough to me that Instagram does not want this type of "bot" activity.
They claim that they have the timing set up in a way that they go undetected, but I think it's a safe bet that there are algorithms at Instagram trying to detect and prevent this type of activity and if they do, accounts would be at risk of being disabled, etc. I have not inside knowledge here, just speculation.
The Instagram application that you use from your cellphone uses HTTP/HTTPS communication with their application server. The link that you provided on the question uses to simulate those http calls to mimic as an Instagram application.
You can redirect your cell phone's Internet connection through the proxy(your own proxy server). From your proxy server catch the web requests those are being sent by the Instagram application when you are doing login, liking, etc.
It will be easy for you if the requests are through http channel. But if its through the https, then it will be really difficult to capture those. You can try with Fidler or some sort of similar softwares for this.
What I THINK is happening is the following:
They are logging your PHPSESSID and using that so you have the ability to like pictures and whatnot. They are doing all of the back-end work directly in index.php.
If you track the requests that are being sent to index.php through the Network tab in Chrome, you will see that "Cookie:_ instamacro_advcontent=1; PHPSESSID=" on the index.php file "Headers" tab.
I'm doing the same with my website that uses Vine's API(not public, btw). In a PHP file I created called api.php, I use Vine's API to perform actions. I do not use OAUTH at all. I simply use the users "x-vine-session" cookie.

The redirect URI piece of oauth2 when using client-side authentication for YouTube API browser-based has extra fields in it

I am trying to setup an automatic way to upload videos to YouTube using the YouTube API. The application needs the videos to be uploaded for some processing by YouTube. Currently, I am setting up the oauth2.0 piece and I am able to redirect the user to login with their information. However, when the user is then redirected back to my site with my specified redirect uri, I need to be able to accept custom fields on the end of the URL. Right now, the web server just redirects the user to the page I want, but strips off all of the information returned by YouTube about authentication. I do not know much PHP at all, but think that it might be the way to solve this problem. Essentially, I want to be able to redirect the user to a page on the website where the extra information is retained so that I can use it. Thanks for your help.
http://ocf.berkeley.edu/~gregory/youtubeTestCode/indexRedirect#access_token=ya29.AHES6ZS8kOZN2T59fKpoUE0t7roUXqTPWDAwTMvrhZ5TjlZO57JZNQ&token_type=Bearer&expires_in=3600
The format of the redirect is http://ocf.berkeley.edu/~gregory/youtubeTestCode/indexRedirect followed by #access_token=ya9232.jdfka7327293&token_type=Bearer&expires_in=3600
However, I have no page with this specific URL..
There are two authentication methods for YouTube - client-side and server-side. (Actually there are more, but I've never used the others).
Documentation is https://developers.google.com/youtube/2.0/developers_guide_protocol_oauth2 but I'l try to paraphrase the bits you need.
"client-side" is what you are using - you basically send the user over the a URL and let google do the work and get the access token back.
"server-side" is what you'll need (as you guessed). To convert, as opposed to sending the user off to a url that ends "&response_type=token", change this bit to "&response_type=code& access_type=offline"
When you get the call back, you have ?code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf - hopefully you can read this as it's before the #
You then use a POST to send this code to the Google servers and it sends back the token in JSON. Taken from that page before:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf&
client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com&
client_secret=hDBmMRhz7eJRsM9Z2q1oFBSe&
redirect_uri=http://localhost/oauth2callback&
grant_type=authorization_code
and response is:
{
"access_token" : "ya29.AHES6ZTtm7SuokEB-RGtbBty9IIlNiP9-eNMMQKtXdMP3sfjL1Fc",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "1/HKSmLFXzqP0leUihZp2xUt3-5wkU7Gmu2Os_eBnzw74"
}
So "relatively" simply change, but you need the PHP part to do the POST as it requires your secret key (which you don't want to reveal through Javascript).
I'll leave you to Google on how to:
read parameters in PHP (hint - use $_GET['paramter name'])
send a POST message to Google using CURL.
An alternative is to check out YouTube SDK for PHP - these are pre-written libraries that contain the POST and the GET bits for you. But this uses something called "Zend" which can get complex. https://developers.google.com/youtube/2.0/developers_guide_php

Fetching album cover photo

I'm using the Graph Api on PHP to fetch the albums for an user.
As I display them, I would like to also show the cover photo for each album. I do get the [cover_photo] attribute on each album, but I would like to show that picture without having to make a new request for each photo to get the source URL for all of them.
Is there any way to do this?
I tried (without success) to fetch the photos doing the following:
<img src="//graph.facebook.com/<?=$album['id'] ?>/picture">
I read a post about it where the solution is:
https://graph.facebook.com/<id>/picture?type=album&access_token=<token>
But I can't just put the access_token inside an img src publicly... can I?
It is very conscientious of you to do this. But you need not worry, as any graph api call that uses an access token automagically requires the request to be https.
Another approach: you can log out of your facebook session at the end of the script which will invalidate the access token.
On a related note, facebook does not mention this as being a security risk. They had a problem with leaked access tokens caused by including them in the HTTP request, and also not using HTTPS. Both of these holes are fixed, and non-expriing tokens have also been removed.
https://developers.facebook.com/blog/post/497/
Here is a good article explaining the security of the access token since Facebook switched to Oauth 2.0
http://www.sociallipstick.com/?p=239
If you make your access_token public, you want to take precautions such that the user doesn't unknowingly give it to someone else.
Make sure your app communicates across HTTPS, otherwise if your user is browsing your website on public wifi, someone can snoop your traffic and get the access_token. The hack is similar to how Firesheep worked.
If a malicious 3rd party gets the user's access_token, he can query Facebook with requests as if he is your app. This could get very nasty if your app has the publish_stream or manage_friendslists permissions.
As long as your user is aware of this, it's fine. The main thing you don't want the user to have is your app's secret key. During the authentication process, your app tells the user's browser to goto Facebook and come back with a "code". Your server then directly connects to facebook (the user's browser doesn't know), and sends that code along with your app's secret key. Facebook comes back to your server with the access token.

PHP: How to upload videos to YouTube without using a login?

I have a site and I want to upload videos onto YouTube without a login. Is it possibe? If yes, how can do this?
Create an account and use its credentials all the time, for all users of your site. You simply can't upload a video without a user account 'responsible' for it. #Pekka: ask for forgiveness, not for permission? ;)
Google at least has a youtube API (with uploading capabilities and PHP examples) right here: http://code.google.com/apis/youtube/2.0/developers_guide_php.html#Uploading_Videos
It is not possible to upload Video to YouTube without logging in.
That said, I wouldn't be surprised if even automated uploading with a login would be forbidden by YouTube's Terms and Conditions.
There is a way to do that without zend client library. Its in core php (PHP4).
https://github.com/techie28/YouTubeUploadPHP.
Note: AuthSub is deprecated now.Please refer to Google Deprecated policy for details.
EDIT:
Because codershelpingcoders.com now points to godaddy's parking page and the original link zendtutorials.wordpress.com has an empty article linking to codershelpingcoders.com, I found the original article via the archive: http://web.archive.org/web/20130123044500/http://codershelpingcoders.com/ and have tried to replicate it's contents in this answer for future reference (NOTE: I have no idea if this info still works).
This tutorial describes the direct browser based upload technique using AuthSub.
AuthSub is the Authorization module of the YouTube that lets your application interact with the YouTube for specific purposes such as Uploading videos etc on user’s behalf.
It is same like Auth and a cousin of oAuth.
A user grants the privilege to your site application and you can do the job on his behalf as simple as that.
We will go through the way to upload a video using AuthSub.
It goes as follows and can be really done in following 4 simple steps:
To allow the application run on user behalf a user must have
authorized it first.
So our first step to implement is to get the app Authorized by the user.
We do it by simply redirecting user to the authorization page the url
is as follows:
$nextUrl = urlencode(‘http://www.xxxx.com’)
$scope = urlencode(‘http://gdata.youtube.com’);
https://www.google.com/accounts/AuthSubRequest?next=’.$nextUrl.’&scope=’.$scope.’&session=1&secure=0
The nextUrl here is the url of the your application where the user
will be redirected after authorization procedure.
scope is to tell the YouTube about the scope of the process which is google
data youtube in this case.
So if user has not authorized your app yet he must be redirected to
the above mentioned authorization page once the user has approved
your application it needs not to follow the step one ever again until
and unless the user revokes the access to you app from the users
control panel of his account.
On successful completion of the authorization process user will be
redirected to your application and this complete the first step of
AuthSub.
If from the first step the user authenticates your application
YouTube will redirect him back to your application with a token in the url.
You are going to use this token and here is where the actual AuthSub process
comes into play you are going to use this token to obtain an entity called
AuthSubSessionToken which will allow you to interact your app to YouTube
on the user behalf who has just approved your application.
In PHP you do it by issuing a curl request. The details are as follows:
Issue a curl GET request to https://www.google.com/accounts/AuthSubSessionToken
with the token you received just after the authorization step.
Remember to turn ON the curl’s response gathering status as you gonna need that.
If everything went well till now you would be responded from YouTube with
the AuthSubSessionToken.
BINGO :-)
Now when you have received the AuthSubSessionToken you are gonna use
that to get an upload token which will actually upload the data
related to your video to YouTube i.e.title,description,category and
keywords. This is kinda reverse process as in AuthSub you upload the
data related to the video to YouTube first and then upload the video
itself. The uploading of video data also referred as MetaData will be
done by feeding XML to the YouTube,the xml will be:
title goes here
description goes here
category goes here
Keyword goes here
and again curl has business to do you will upload this by issuing another curl call:
url:http://gdata.youtube.com/action/GetUploadToken
headers:AuthSub token=”Your AuthSubSession token goes here”
GData-Version:2
‘X-GData-Key: key=”Your Api key goes here”
Content-length: length of the xml you formed above goes here
Content-Type:application/atom+xml; charset=UTF-8
POSTFIELDS: the xml itself that you formed
If the step 3 completes successfully then its time to upload the
video actually on your successful last curl execution you will be
reverted back by the YouTube with a url an a token.
Now you will create a form which will have this url as its action and token
as a hidden field something like this.
Just select the video and click submit and your video will get uploaded.
On successful submission you will be redirected back with status 200.
The github link for the Sample code is here.

How can I build an API in PHP

Hello I am looking to build a basic API and application/apps system on my social network something like Facebook or other sites have, my site is in php/mysql. Here are some questions.
1)
Basically what I want to do is give a user a API key and secret. After I have these how can I use them in my php app to authenticate a user request which would come from there server?
2)
I can basically build an API to send a request to my server with CURL and get the result back to the page in XML or JSON or whatever, the problem is when sending the request the user would have to know the user ID they want to send to lookup data against, this is fine for an API but I am wanting to have an Apps section where the user's app site would be using the API and would be loaded into my site in the app section with an iframe, the problem is, I need to find a good way to make it where a logged in user on my site can go to the app section and go to an app and there username should be available to that page loaded in the iframe. Facebook and myspace do this somehow and many other sites; I am lost how to get around this hurdle.
Any help on any of this is really appreciated, thank you
Update:
I just had an idea, if I require a cookie to be set when a user visit's my site, then they would have a cookie and it could hold there User ID, then my API script could look for that cookie to exist and grab it's value?
If you plane on using an IFRAME, then no, your API hosted on a separate website (the website inside the IFRAME) would not be able to grab the cookie. The cookie is only visible on the website that it was set for.
I have only used Facebook API with the FBML (not the IFRAME,) but all they do their is basically replace what's in the page with the info that the "tag" is calling. I'm not sure if there is a better way, but you could possibly call a page on the app's server (say the app is hosted at http://example.com/app/, and you called http://example.com/app/?id=28318&name=John%20Maguire,) and have your API code handle it and turn it into a variable?
Maybe you should look into the source code of the Facebook API client.

Categories