How to get top 10 videos from your channel with the views count included in the response - api

So I have a ouath web app that connects to youtube. I use the youtube analytics calls to get information like number of subscribers from my channel. But right now I try to make a top 10 videos from my channel with the views count for every video included in the response. I use this documentation:
Top videos for subscribed or unsubscribed viewers
My call looks like this:
$command = 'curl -H "Authorization: Bearer ' . $access_token . '" "https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DMINE&start-date=' . date('Y-m-d', strtotime('-31 days')) . '&end-date=' . date('Y-m-d', strtotime('today')). '&metrics=views&dimensions=video&sort=views"';
But I get an error message as a response:
"The query is not supported. Check the documentation at https://developers.google.com/youtube/analytics/v1/available_reports for a list of supported queries."
I also tried this call with YoTube data API:
$videos_url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&forMine=true&order=viewCount&type=video&access_token=' . $access_token;
But it provides this response:
["kind"]=>
string(26) "youtube#searchListResponse"
["etag"]=>
string(57) ""######""
["nextPageToken"]=>
string(112) "#######"
["pageInfo"]=>
object(stdClass)#267 (2) {
["totalResults"]=>
int(1)
["resultsPerPage"]=>
int(5)
}
["items"]=>
array(1) {
[0]=>
object(stdClass)#270 (4) {
["kind"]=>
string(20) "youtube#searchResult"
["etag"]=>
string(57) ""#####""
["id"]=>
object(stdClass)#269 (2) {
["kind"]=>
string(13) "youtube#video"
["videoId"]=>
string(11) "####"
}
["snippet"]=>
object(stdClass)#273 (6) {
["publishedAt"]=>
string(24) "2016-09-14T14:49:49.000Z"
["channelId"]=>
string(24) "#####"
["title"]=>
string(12) "My Slideshow"
["description"]=>
string(87) "I created this video with the YouTube Slideshow Creator (http://www.youtube.com/upload)"
This response provides no views count. I need for every video to get the views count as well.
Any ideas on how to accomplish this? Any help is welcomed! Thank you all for your time!

The issue with your youtube analytics api request is sort parameter. Try using value -views instead of views. You can double check the API link you provided. Also set the max-results
Example URL :
https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3Dmine&start-date=2016-05-01&end-date=2016-09-01&metrics=views&dimensions=video&max-results=10&sort=-views&key={YOUR_API_KEY}

Related

How to break string data coming from Api response in Laravel

This my data coming from Api : "TAX_BREAKUP": "ab=4835,ay=1400,at=852,cb=4835,cy=1400,ct=852"
#foreach(explode(',', $data['TAX_BREAKUP']) as $amt)
Adult Priceā‚¹ {{$amt}}
Tax{{$amt}}
#endforeach
An this is code which I am trying to break the string.
If I understand your question, what you want is :
$Tax_arr = explode(',', $data['TAX_BREAKUP']);
foreach($Tax_arr as $amt){
$amt_arr = explode('=', $amt);
echo $amt_arr[0]." is ".$amt_arr[1]."<br>";
}
$amt_arr[0] is the attribute name and $amt_arr[1] is the value

Yodlee REST API - addItemForContentService1

Could you please provide a JSON sample of how you would post an addItemForContentService1 for a bank with a FieldInfoMultiFixed field. An example is Sallie Mae, content service ID #3805
Thanks
I wrote this in python. Replace some of the values such as cobrand_session_token, content_service_id with the actual values:
Most of the below is directly from this documentation.
payload = {"cobSessionToken": cobrand_session_token, "userSessionToken": session["user_session_token"], "contentServiceId": content_service_id, "shareCredentialsWithinSite": True, "startRefreshItemOnAddition": True, "credentialFields.enclosedType": "com.yodlee.common.FieldInfoMultiFixed",\
"credentialFields[0].valueIdentifier":"LOGIN",\
"credentialFields[0].displayName":"UserID",\
"credentialFields[0].isEditable":True,\
"credentialFields[0].isEscaped":False,\
"credentialFields[0].name":"LOGIN",\
"credentialFields[0].helpText":5112,\
"credentialFields[0].fieldType":"TEXT",\
"credentialFields[0].valueMask":"LOGIN_FIELD",\
"credentialFields[0].maxlength":40,\
"credentialFields[0].size":20,\
"credentialFields[1].valueIdentifier":"PASSWORD",\
"credentialFields[1].displayName":"Password",\
"credentialFields[1].isEditable":True,\
"credentialFields[1].isEscaped":False,\
"credentialFields[1].name":"PASSWORD",\
"credentialFields[1].helpText":4530,\
"credentialFields[1].fieldType":"IF_PASSWORD",\
"credentialFields[1].valueMask":"LOGIN_FIELD",\
"credentialFields[1].maxlength":40,\
"credentialFields[1].size":20, "credentialFields[0].value":"content_account_username", "credentialFields[1].value":"content_account_password"}

PayPal Adaptive Payments - Error 520009 - Account is restricted

Apologies in advance if this is a silly question. I did try digging around, but couldn't find an answer.
I'm trying to set up a chained payment (at the sandbox environment), but am getting error 520009 (Account is restricted). Tried several email addresses, and they all give me this error. The email addresses are not registered with Paypal, but as far as I know this shouldn't be an issue as the adaptive payments module doesn't require the receivers to have Paypal accounts in advance (though they will need accounts to actually get the money, of course).
What am I doing wrong?
I did set the fee payer to EACHRECEIVER (as suggested on some threads), but the error remains.
This is what I get back:
ERROR Code: 520009
ERROR Message: Account someone1#gmail.com is restricted
Here's my code:
// Config
$endpoint = trim("https://svcs.sandbox.paypal.com/AdaptivePayments/Pay");
$API_UserName = "MY_USERNAME_FROM_SANDBOX";
$API_Password = "MY_PASSWORD_FROM_SANDBOX";
$API_Signature = "MY_SIGNATURE_FROM_SANDBOX";
$API_AppID = "APP-80W284485P519543T";
$API_RequestFormat = "NV";
$API_ResponseFormat = "NV";
// Create request payload with minimum required parameters
$bodyparams = array (
"requestEnvelope.errorLanguage" => "en_US",
"actionType" => "PAY_PRIMARY",
"cancelUrl" => 'http://www.beta.com/cancel',
"returnUrl" => 'http://www.beta.com/return',
"currencyCode" => 'USD',
"feesPayer" => "EACHRECEIVER",
"actionType" => "PAY_PRIMARY",
"receiverList.receiver[0].email" => 'someone1#gmail.com',
"receiverList.receiver[0].amount" => '10',
"receiverList.receiver[0].primary" => 'true',
"receiverList.receiver[1].email" => 'someone2#gmail.com',
"receiverList.receiver[1].amount" => '5',
"receiverList.receiver[1].primary" => 'false',
);
// Convert payload array into url encoded query string
$body_data = http_build_query($bodyparams, "", chr(38));
try
{
//create request and add headers
$params = array("http" => array(
"method" => "POST",
"content" => $body_data,
"header" =>
"X-PAYPAL-SECURITY-USERID: " . $API_UserName . "\r\n" .
"X-PAYPAL-SECURITY-SIGNATURE: " . $API_Signature . "\r\n" .
"X-PAYPAL-SECURITY-PASSWORD: " . $API_Password . "\r\n" .
"X-PAYPAL-APPLICATION-ID: " . $API_AppID . "\r\n" .
"X-PAYPAL-REQUEST-DATA-FORMAT: " . $API_RequestFormat . "\r\n" .
"X-PAYPAL-RESPONSE-DATA-FORMAT: " . $API_ResponseFormat . "\r\n"
));
//create stream context
$ctx = stream_context_create($params);
//open the stream and send request
$fp = #fopen($endpoint, "r", false, $ctx);
//get response
$response = stream_get_contents($fp);
//check to see if stream is open
if ($response === false) {
throw new Exception("php error message = " . "$php_errormsg");
}
//close the stream
fclose($fp);
//parse the ap key from the response
$keyArray = explode("&", $response);
foreach ($keyArray as $rVal){
list($qKey, $qVal) = explode ("=", $rVal);
$kArray[$qKey] = $qVal;
}
//print the response to screen for testing purposes
If ( $kArray["responseEnvelope.ack"] == "Success") {
foreach ($kArray as $key =>$value){
echo $key . ": " .$value . "<br/>";
}
}
else {
echo 'ERROR Code: ' . $kArray["error(0).errorId"] . " <br/>";
echo 'ERROR Message: ' . urldecode($kArray["error(0).message"]) . " <br/>";
}
}
catch(Exception $e) {
echo "Message: ||" .$e->getMessage()."||";
}
Thanks!
EDIT: I could solve the problem by removing the "feesPayer" param, which needs to be the default value (i.e., EACHRECEIVER) in case of a unilateral payment.
I'm stuck with this issue, too.
I wonder how I could achieve a "unilateral payment", which is described by PayPal as follows:
You can use the Pay API operation to make unilateral payments under
limited circumstances. A unilateral payment is a payment that is made
to a receiver who does not have a PayPal account. Unilateral payments
can be used with simple or parallel payments that are implicit or
preapproved. Unilateral payments are not designed to be used with
chained payments or payments that require manual approval through the
web flow. When you send a unilateral payment, you send a payment
request that includes an email address for a receiver, and this email
address is not linked to a registered PayPal account. The receiver
receives an email notifying the receiver to create an account and
claim the payment. PayPal holds a payment to a receiver whose email
address is not yet registered or confirmed until the receiver creates
a PayPal account and confirms the email address. If a refund specifies
a receiver whose email address is not yet registered or confirmed, the
payment to the receiver is canceled.
Anyone having an idea what parameter-setting using NVP is required to achieve this without getting ERROR Code: 520009 ERROR Message: Account someone1#gmail.com is restricted
Any hint is highly appreciated!
"but as far as I know this shouldn't be an issue as the adaptive
payments module doesn't require the receivers to have Paypal accounts
in advance "
That's incorrect. For Adaptive Chained Payments, all receivers must have an active and verified Personal, Premier or Business PayPal account.

Youtube api get latest upload thumbnail

I am looking to returning the video-thumbnail of the latest uploaded video from my channel, and display it on my website.
Anyone know how I can do a minimal connection trough api and get only the thumbnail?
Thanks!
-Tom
REVISED!!
Using Cakephp, this is how I did it (thanks dave for suggestions using zend);
controller:
App::import('Xml');
$channel = 'Blanktv';
$url = 'https://gdata.youtube.com/feeds/api/users/'.$channel.'/uploads?v=2&max-results=1&orderby=published';
$parsed_xml =& new XML($url);
$parsed_xml = Set::reverse($parsed_xml);
//debug($parsed_xml);
$this->set('parsed_xml',$parsed_xml);
View;
$i=0;
foreach ($parsed_xml as $entry)
{
echo '<a href="/videokanalen" target="_self">
<img width="220px" src="'.$entry['Entry']['Group']['Thumbnail'][1]['url'] .'">
</a>';
}
Now the only thing remaining is to cache the feed call someway.. Any suggestions???
-Tom
here is a quick dirty way of doing it without really touching the api at all.
I'm not suggesting it's best practice or anything and I'm sure there are smarter ways but it definitely works with the current Youtube feed service.
My solution is PHP using the Zend_Feed_Reader component from Zend Framework, if you need a hand setting this up if you're not familiar with it let me know.
Essentially you can download version 1.11 from Zend.com here and then make sure the framework files are accessible on your PHP include path.
If you are already using Zend Framework in an MVC pattern you can do this in your chosen controller action:
$channel = 'Blanktv'; //change this to your channel name
$url = 'https://gdata.youtube.com/feeds/api/users/'.$channel.'/uploads';
$feed = Zend_Feed_Reader::import($url);
$this->view->feed = $feed;
Then you can do this in your view:
<h1>Latest Video</h1>
<div>
<?php
$i=0;
foreach ($this->feed as $entry)
{
$urlChop = explode ('http://gdata.youtube.com/feeds/api/videos/',$entry->getId());
$videoId = end($urlChop);
echo '<h3>' . $entry->getTitle() . '</h3>';
echo '<p>Uploaded on: '. $entry->getDateCreated() .'</p>';
echo '<a href="http://www.youtube.com/watch?v=' . $videoId .'" target="_blank">
<img src="http://img.youtube.com/vi/' . $videoId .'/hqdefault.jpg">
</a>';
$i++;
if($i==1) break;
}
?>
</div>
otherwise you can do:
<?php
$channel = 'Blanktv'; //change this to your channel
$url = 'https://gdata.youtube.com/feeds/api/users/'.$channel.'/uploads';
$feed = Zend_Feed_Reader::import($url);
?>
<h1>Latest Video</h1>
<div>
<?php
$i=0;
foreach ($feed as $entry)
{
$urlChop = explode ('http://gdata.youtube.com/feeds/api/videos/',$entry->getId());
$videoId = end($urlChop);
echo '<h3>' . $entry->getTitle() . '</h3>';
echo '<p>Uploaded on: '. $entry->getDateCreated() .'</p>';
echo '<a href="http://www.youtube.com/watch?v=' . $videoId .'" target="_blank">
<img src="http://img.youtube.com/vi/' . $videoId .'/hqdefault.jpg">
</a>';
$i++;
if($i==1) break;
}
?>
</div>
With the latter method you'll likely need to use a php require statement for the Zend_Feed_Reader files etc....
Hope this helps, like I say let me know if you need a hand.
All the best,
Dave
UPDATE: In response to your comments about caching
Hi Tom, here is another quick and dirty solution which doesn't use cache but may be very quick to implement.
The reason I didn't go with a caching component is because I figured a simple db solution would suffice under the circumstances. I also thought having to pull the feed to compare whether it was new or not wouldn't be the most economical for you.
You could automate this process to be run automatically at specified times but if you don't want to automate the process and don't mind clicking a link to update the video manually you could trigger it that way.
My solution is again based on ZF but since you were ok hacking it into something useful with cakephp you should have no problem doing the same here.
First set up a new table (assuming a MySQL db):
CREATE TABLE `yourdbname`.`latestvid` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique identifier',
`videoId` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Video id',
`videoTitle` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Video title',
`uploadDate` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Video upload date'
) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_general_ci;
INSERT INTO `yourdbname`.`latestvid` (`id`, `videoId`, `videoTitle`, `uploadDate`) VALUES (NULL, '--', '--', '--');
This will create a table for your latest video info for use in your template however the default values I've set up will not work with your template for obvious reasons.
You could then do something similar to this:
public function updateAction()
{
$this->_helper->viewRenderer->setNoRender(); // disable view
$this->_helper->layout()->disableLayout(); // disable layout
$user = 'Blanktv'; // insert your channel name
$url = 'https://gdata.youtube.com/feeds/api/users/'.$user.'/uploads';
$feed = Zend_Feed_Reader::import($url);
if(!$feed)
{
die("couldn't access the feed"); // Note: the Zend component will display an error if the feed is not available so this wouldn't really be necessary for ZF
}
else
{
$i=0;
foreach ($feed as $entry)
{
$urlChop = explode ('http://gdata.youtube.com/feeds/api/videos/',$entry->getId());
$videoId = end($urlChop);
$videoTitle = $entry->getTitle();
$uploadDate = $entry->getDateCreated();
// use your preferred method to update the db record where the id = 1
$i++;
if($i==1) break;
}
}
}
Maybe have a go and let me know how you get on?
You'd just need to tweak the template so you'd get the variables from the database instead of Youtube with the exception of the thumbnail.
I suppose you could always take that approach further and actually store images etc since the thumbnail is still being pulled from Youtube and may slow things down.
You could set up a script to copy the thumbnail to your own server and store the path in the db or use a standard thumbnail if you are running a series of videos for which you require standard branding - anyway hope it helps.
:-D
Dave

Can you view a friendship relationship's data (the "You and a friend" page) via the Facebook API? [duplicate]

How can I get a friendship detail for two people? So for example in the web it will be:
http://www.facebook.com/<my_id>?and=<friend_id>
Is there any way I can do this in Graph API? Furthermore can I get specific items such as photos together, wall posts between us, etc? (Not documented AFAIK, but many Graph API features aren't anyway...)
EDIT: I think it should be possible with Graph API. For example getting family details (brother, sister, parents, etc) is not documented yet I still able to do it.
You can simulate a friendship query by doing multiple FQL queries. For example, to get all the photos between two friends A and B, you can:
Get all photos (p) from A
Get all tags of B in p (query on the photo_tags table)
Get all comments made by B on p (query on the comments table)
Repeat, this time selecting photos from B.
You can apply the same concept on other things such as posts, likes, videos etc.
Yes, I think you can also do the same thing phillee answered with the Graph API instead of FQL:
Get user's photos https://graph.facebook.com/USERID/photos
Get each photo's tags https://graph.facebook.com/PHOTOID/tags
Sort through the list of photo tags, and grab all photos with the Friend in them
Get each photo's comments https://graph.facebook.com/PHOTOID/comments
Sort through the list of photo comments, and grab all comments left by the friend
As the other answer also said: rinse and repeat for all data you want
https://graph.facebook.com/USERID/feed
https://graph.facebook.com/USERID/posts
etc etc, see all connections here: http://developers.facebook.com/docs/reference/api/user/
For the interests, movies, activities, etc just make an API call for both (https://graph.facebook.com/ONEUSER/music and https://graph.facebook.com/OTHERUSER/music) and find the intersection of the two sets of data (loop through each list and save all matches to a separate list of mutual Likes)
There are no specific API calls for friendships though, so you will have to build your own. My guess is that Facebook is doing exactly this on their Friendship pages :)
It should be just as easy with FQL as with the REST API... maybe even easier with FQL since you can add WHERE conditions and get back just the data you need (SELECT * FROM comments WHERE fromid = FRIENDID), instead of sorting through the big list returned by the API (unless there is a way to add conditions to API request URLs?).
If I understand properly you want to "View Friendship"
This type of query is not directly possible using the Graph API (at the moment). You would need to gather the information from each resource endpoint and then do some relating on your own part to "View Friendship"
This is what I have been using:
<?php
function main()
{
global $Fb;
$Fb = new Facebook(array('appId'=>FB_API_ID,'secret'=>FB_API_SECRET));
$logoutUrl = $Fb->getLogoutUrl();
$loginUrl = $Fb->getLoginUrl();
$user = fb_loguser($Fb);
if ($user)
{
$txt .= "<p align=\"center\">Logout</p>";
$txt .= "<h3 align=\"center\">You</h3>";
$access_token = $Fb->getAccessToken();
$user_profile = $Fb->api('/me');
$txt .= "<p align=\"center\">
<img src=\"https://graph.facebook.com/".$user."/picture\"></p>";
$txt .= fb_friends_list($user_profile,$access_token);
}
}
function fb_loguser($facebook)
{
global $Fb;
$Fb = $facebook;
$user = $Fb->getUser();
if ($user)
{
try
$user_profile = $Fb->api('/me');
catch (FacebookApiException $e)
{
error_log($e);
$user = null;
}
}
return($user);
}
function fb_friends_list($access_token)
{
global $Sess,$Fb;
$friends = $Fb->api('/me/friends'); // return an array [data][0 to n][name]/[id]
$siz = sizeof($friends['data']);
$txt = "<h3>Your FRIENDS on FACEBOOK</h3>";
$txt .= "<table>";
for ($i=0; $i<$siz; $i++)
{
$fid = $friends['data'][$i]['id'];
$src = "http://graph.facebook.com/".$fid."/picture";
$txt .= "<tr><td><img src=\"".$src."\" /></td>";
$txt .= "<td>".$friends['data'][$i]['name'] . "</td>";
$txt .= "<td>" . $fid . "</td></tr>";
}
$txt .= "</table>";
return($txt);
}
?>
Call main()!
Getting the photos where two (or more) users are tagged in:
SELECT pid, src_big FROM photo
WHERE pid IN(
SELECT pid FROM photo_tag WHERE subject=me())
AND pid IN(
SELECT pid FROM photo_tag WHERE subject=FRIEND_ID)
AND pid IN(
SELECT pid FROM photo_tag WHERE subject=ANOTHER_FRIEND_ID)
...
http://bighnarajsahu.blogspot.in/2013/03/facebook-graph-api-to-get-user-details.html
This is the complete code to get the friendlist in Fb.