Youtube API Retrieving Channel ID after authentication - php

I am using Google Youtube API and YoutubeAnalytics API, I read on their documentation that you need a CHANNEL_ID inorder for you to grab the user's videos.
I can now successfully Google authenticate the user in my application, I just wanted to ask if how can I get their CHANNEL_ID after they authenticate.
I am using PHP, I've been searching over the net but can't seem to find any example how to do that.
Your help will be greatly appreciated!
Thanks! :)

Since you're using PHP, I'm assuming you're using the PHP-based gapi-client? Here's the call to make:
$listResponse = $youtube->channels->listChannels('id', array(
'mine' => 'true',
))
The 'id' part returns the ID of the channel, and by passing the parameter "mine" as true, you're telling the API to return the data for the authenticated user.
If you're using a different client or rolled your own, you can also just hit this endpoint (passing the oAuth access token you have in the header or as another parameter to the request):
GET https://www.googleapis.com/youtube/v3/channels?part=id&mine=true&key={YOUR_API_KEY}

Related

Getting twitch channel feed forbidden

As per the API: https://github.com/justintv/Twitch-API/blob/master/v3_resources/channel_feed.md#get-feedchannelposts
I have tried using PHP and cUrl to get the latest channel feed comments. This is the URL I am polling:
https://api.twitch.tv/kraken/feed/:username/posts
Obviously with :username as my actual username. I am also passing:
"oauth_token" => "[MY OAUTH TOKEN]"
I know that this procedure normally works because I am using it to get normal info about the channel and followers info. Though trying it with the feed posts I get this message back (after JSON decoding it):
Array
(
[error] => Forbidden
[status] => 403
[message] => Channel feed is disabled
)
When I set up the authorization for the account using oauth I included the following scope for allows:
user_read user_blocks_edit user_blocks_read user_follows_edit channel_read channel_editor channel_commercial channel_stream channel_subscriptions user_subscriptions channel_check_subscription chat_login channel_feed_read channel_feed_edit
As far as I know that is everything so not sure why it's coming up as forbidden, and as I mentioned I am using other parts of the API so not sure whats wrong here... Any ideas or help is greatly appreciated :)
I am by no means an expert on twitch's API but I'll give it a shot. Looking through their github documentation it shows 3 ways of sending access token for authentication.
Is it possible you're sending the token in the HTTP body? It explicitly states that this won't work with GET and DELETE methods, which could be giving you an error when trying to GET channel feed posts. Hope this helps.
EDIT: Yousimply don't have channel feed enabled on your account. It's currently opt-in because it's in beta. See: http://help.twitch.tv/customer/portal/articles/2377877-how-to-use-channel-feed

YouTube API v3 keeps asking for authorisation every time

I am using the YouTube api v3 to retrieve a list of videos using the example at https://developers.google.com/youtube/v3/code_samples/php#retrieve_my_uploads
I open the page, the app asks for authorisation. I click the link to authorise, select my gmail account and I get the listing.
The problem is when i go back to the app even only a few seconds later, I have to authorise the app again.
I thought once the app was authorised you could exchange a token for a refresh token.
Is there anywhere that shows some code how to get a refresh token as the documentation or any reference to it online is very poor.
I really need some help getting this working as i've been trying for the last couple weeks and getting nowhere.
I have a long-winded answer, but it should be a big help. I had the same issue with the poor documentation and I am also trying to get a list of videos from a playlist for my project. The API v3 just magically started working for me after struggling for the past couple days, here is what I did.
First was actually getting the API key. I'm sure you've been in the Google Developers Console by now, but just in case here is what to do for this step:
Create a project in Google Developers Console
Enable the YouTube Data API v3 API
Under "Credentials", if you had the same issue as me, you can create a new Client ID but not an API key.
This is a major problem because you need an API key to make simple data requests without authorization, e.g., getting a list of videos from a playlist. To get an API key, go back to the "APIs" section, click on "YouTube Data API v3", and here is the screen with the loading indicator that never loads anything. However you can click on "Quota" here and it takes you to the older version of the Developers Console.
From this older version, you can go to "API Access" and add your Simple API Access keys (the API keys work on this older version, but not on the new version of Developers Console). I could be wrong about this but I think "Create new Server key..." is for server-side languages like PHP, and "Create new Browser key..." is for client-side languages like Javascript. There are also buttons for Android and iOS keys, but I assume you don't need those. Anyway, I'm using cURL in PHP and the Server key worked for me, I have it set to allow any referrers while my project is still in development.
Once you get your Key for server apps under Simple API Access, it might be a while before any requests using the key actually work. For me, my script didn't work for about 4-5 hours (I think Google is having real issues with their servers this week, which is also why I had to "trick" it into giving me an API key. And it's probably why the "Credentials" page doesn't load anything).
Now use the tool on https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.playlists.list to help create your GET request. Enter "snippet" in the part field and an integer for maxResults if necessary. Then get the ID of a playlist from the URL on Youtube. For example, Conan's "Clueless Gamer" series is https://www.youtube.com/playlist?list=PLVL8S3lUHf0RqD7TZ6hohWk8Sd3asaqnY, so the ID is PLVL8S3lUHf0RqD7TZ6hohWk8Sd3asaqnY. Then click Execute.
Now it will give you the GET Request, something like
GET https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=PLVL8S3lUHf0RqD7TZ6hohWk8Sd3asaqnY&maxResults=20&key={YOUR_API_KEY}
X-JavaScript-User-Agent: Google APIs Explorer
Just take the URL after the word GET and replace {YOUR_API_KEY} with your API key.
Now you can use this URL in a cURL request, like so, where $request_url is the URL from above with your API key in it:
//http://codular.com/curl-with-php
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $request_url,
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
Now $resp will hold a JSON string that you can parse through and get the data for that playlist's videos. I'll leave the JSON parsing up to you, but that's how you get data similar to the old gdata way in v2. And no authentication :)
It might report an error back that your API key isn't authorized, in which case you'll need to wait several hours. Again, I think Google has been having real server issues lately so be patient; it's not your script that doesn't work, it's Google ;)
I will note that
$resp = file_get_contents($request_url);
seems to work as well, but I honestly don't know which method is "better" between cURL and file_get_contents().
Took me ages to work this out as I couldn't find any examples on how to do this easily.
It turned out that I need to create a POST request to get an access code and refresh token and this was achieved with using Curlfrom the command line
url --data "code=AUHROISATON_CODE&client_id=CLIENT_ID.apps.googleusercontent.com&client_secret=CLINET_SECRET&redirect_uri=http://www.example.com&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token
After a few errors such as 'Missing grant_type', 'Invalid code' it now works.
I revoked access to the app, ran the following GET request (taken from https://developers.google.com/accounts/docs/OAuth2WebServer#formingtheurl) to get the code and was able to use the code in the above Curl statement
https://accounts.google.com/o/oauth2/auth?
scope=https://www.googleapis.com/auth/youtube&
state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&
redirect_uri=https%3A%2F%2Foauth2-login-demo.appspot.com%2Fcode&,
response_type=code&
client_id=812741506391.apps.googleusercontent.com&
approval_prompt=force

BigCommerce API OAuth server to server script

The latest specification for connecting to the BigCommerce API recommends using OAuth since the simple auth method will soon be deprecated.
I have been using the BigCommerce API within some PHP scripts that access the Store API for my store. These scripts do relatively simple things like update product names, update product prices, etc.
I'm confused as to how I transfer these scripts over to use the new OAuth system. Everything I am reading makes it seem like OAuth is based around developing an actual app that a user installs and authorizes to access their store. However, this is clearly not my use case, and has left me very confused.
A simple example would be a script to retrieve products from my store. I would simply run this code in a PHP file:
Bigcommerce::configure(array(
'store_url' => 'https://www.my-store.com',
'username' => 'my_username',
'api_key' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
));
Bigcommerce::setCipher('RC4-SHA');
Bigcommerce::verifyPeer(false);
Bigcommmerce::getProducts();
How can I achieve this same thing using OAuth? Is it even possible?
I would probably create a quick "app" to get a Client ID, Client Secret & Token. Then use those credentials for authentication externally. So you would install an "authentication app" but execute your code from outside of BC.
Note that this is not that different from how an installed app that is iframed in works.
PS, I have not actually tried this but in theory it should work.
I realize this may be a bit off-topic as I see you're using PHP and my experience has been with C# but thought I'd add my comments on the issue so maybe someone will benefit:
I've been working on this same type of oauth token issue and the docs haven't been much help, but once I got going I finally managed to get the app setup by creating my SSL callback page locally on my server. Once I specified that URL in the app settings I was all set. The caveat being I had to do perform the 'install' from the server itself since it wasn't a public URL while logged into BC as the store owner. I was then able to get the temporary token from the querystring and post back to https://login.bigcommerce.com/oauth2/token and obtain the permanent token from the response stream.
One thing their API rep did mention that may be of interest is that eventually you're going to need to refresh the 'permanent' token every 60-90 days or so once they get their end in order.
#developerscott is perfectly correct, but just to add on to your question on how to achieve the same thing as your code using oAuth with the BC PHP API SDK
Once you have an oAuth access token and the client_id of an app you created, you can use them to utilize oAuth in your PHP scripts. You just need to provide those credentials into the Bigcommerce::configure() method like so, instead of the username and api_key properties:
Bigcommerce::configure(array(
'store_hash' => 'abcdef',
'client_id' => '123xxxx321',
'auth_token' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
));
Bigcommerce::setCipher('RC4-SHA');
Bigcommerce::verifyPeer(false);
Bigcommmerce::getProducts();

Get Twitter userid from access token only

This may be duplicated with other articles, but I can't figure out how to do it after reading all of those.
I'm working on a back-end project in PHP and we are isolated from the front-end. According to the documentation from the front-end team, they will pass an access token and need the back-end to pull userid from Twitter's server.
Is there any way to do it? I could pull the data if I have oauth_signature and oauth_nonce, but they only give us the access_token.
I could pull the data if I have oauth_signature and oauth_nonce
That's not correct. oauth_signature is generated based on the application secret and request parameters. oauth_nonce is just a random string
So you need to get access_token and access_token_secret and perform a GET account/verify_credentials request
Further reading:
https://dev.twitter.com/docs/auth/implementing-sign-twitter
https://www.rfc-editor.org/rfc/rfc5849

Find YouTube username with YouTube / GooglePlus API

I'm fairly new to Stack Overflow, so if I am doing something wrong please tell me;
I have setup my website with the Google+ API - to log in, people click on a "Login With Google+" button and log in.
That's all fine and good, but I was wondering if I can integrate this login process with the YouTube API, so that when the user clicks the button to log in, I can also gather YouTube information.
I've already setup the YouTube Analytics and Data APIs on the Google API Console, I just need a code snippet to store the YouTube Username.
Expected Behavior:
User with URL 'youtube.com/some-user' logs in with Google+
Google+ Authentication Key is fed into some script
Script connects to YouTube API and returns username (eg $youtube_user = 'some-user')
My website takes this information and continues with the script
You can do this using the YouTube API. What you need to do is add an additional scope to your sign-in button. I would recommend you use the following scope:
https://www.googleapis.com/auth/youtube.readonly
Do this because you will not be managing anyone's YouTube account, just seeing their personal data (e.g. to pull in links or embed code for their YouTube videos).
Next, you need to perform an API call to YouTube using a client library. For experimentation, you can use the API explorer. To see your own information, authorize the request, set the part to "snippet" (no quotes) and then set mine to true.
Download the "youtube", "v3" static class from the PHP Google API client library, then make a call passing snippet as the part you want and "mine" set to true.
For listing the current user's videos, there is an example that ships with the PHP client library. The following change would list the user's activities:
// Exchange the OAuth 2.0 authorization code for user credentials.
$client->authenticate($code);
$token = json_decode($client->getAccessToken());
...
$activities = $youtube->activities->listActivities('snippet', array(
'mine' => 'true',
));
foreach ($activities['items'] as $activity) {
error_log(serialize($activity));
}
class's answer is spot on in terms of getting the OAuth 2 credentials to make the request. In terms of actual PHP code to work off of, you can use this example as a starting point (which uses this client library), and modify line 40 to read
$channelsResponse = $youtube->channels->listChannels('snippet', array(
'mine' => 'true',
));
And then you can access the channel's title via $channelsResponse['items'][0]['snippet']['title']. Note that it's possible to link a Google+ account and a YouTube channel, and if that's done, the channel's title will be equal to the Google+ account's display name. If this is an unlinked YouTube channel, then the legacy username of the channel will be returned instead.

Categories