Is there a field for knowing if the youtube channel is verified from the Youtube API? - youtube-api

I am using the Youtube data API and I needed to know if there is any way of finding that the youtube channel is a Verified one.

just ran into this today, and while the channelBranding of the V3 youtube API looks promising, I couldn't get it to return if the account/channel user id was verified or not
so I threw up a pretty lame php script that uses DOM model searching to examine the html directly.
to return true if the following element is present.
<a href="//support.google.com/youtube/bin/answer.py?answer=3046484&hl=en" class="qualified-channel-title-badge" target="_blank">
As of today (9/8/2014) a verified user will return true..
<?php
function isVerified($youtubeUser)
{
$youtubeUser = trim($youtubeUser);
$url = '\''."https://www.youtube.com/user/".$youtubeUser.'\'';
$url = "https://www.youtube.com/user/".$youtubeUser ;
$Verified = false;
echo "<BR>looking at $url ";
$ch = curl_init();
$timeout = 10;
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);
curl_close($ch);
$dom = new DOMDocument;
#$dom->loadHTML($html);
foreach ( $dom->getElementsByTagName('a') as $link ) {
$myVar = $link->getAttribute('class');
$search = "qualified-channel-title-badge";
$found=false;
$found = strpos($myVar, $search);
if ( $found !== false) {
$Verified = true; //echo "<BR><font color=green>TRUE</font>";
} else {
$Verified = false; //echo "<BR><font color=red>FALSE</font>";
}
}
if ( $Verified ) {
return true;
} else {
return false;
}
}
?>
Bye for now!

RE: mpgn's solution, note that there's a distinction between whether the G+ account is Verified and whether one or more of the accounts YouTube channels are Verified. It's possible for an account to have more than one channel, and each of those channels are verified independently, and for channels to be unverified even though the associated G+ account is verified.
As #Paul Blakely suggests, the current best way to do this is to check the status.longUploadStatus flag, per https://developers.google.com/youtube/v3/docs/channels

As of November, 2022, the YouTube Data API provides no method for determining whether or not a given YouTube channel is or is not verified. Instead, the current approach that yields reliable results is to scrape the channel, and parse a bit of JSON, and search the resulting structure.
We'll start by loading the server response for a given channel. Below I have a channel ID hard-coded in as the id variable:
const id = 'UCFNTTISby1c_H-rm5Ww5rZg';
const response = await needle( 'get', `https://www.youtube.com/channel/${id}` );
With our response object, we should now proceed to check that a 200 OK was received, indicating there were no issues retrieving the page data, and that it is safe to proceed:
if ( response.statusCode === 200 ) {
// proceed to search for verification status
}
Within the block following the condition is where we can start to retrieve the initial data for the YouTube page. When serving a channel page, YouTube will also serve initial data for the channel itself, presumably to speed up delivery among other reasons.
We'll look for this initial data, parse it as JSON, and sift through the results:
const json = response.body.match( /ytInitialData = (.*?);<\/script>/ )[1];
const parsed = JSON.parse( json );
With our data parsed, we'll turn our attention now to one piece of the resulting structure, the c4TabbedHeaderRenderer property. This is where badges for the page (such as a verification badge) are stored. We'll also define a verifiedLabel, to explain what it is we're seeking:
const header = parsed.header.c4TabbedHeaderRenderer;
const verifiedLabel = 'BADGE_STYLE_TYPE_VERIFIED';
Lastly we need to confirm that badges is an array (it may not be, in the event the channel has no badges to enumerate), and follow that up with a check for our verifiedLabel badge:
const verified = Array.isArray(header.badges) && header.badges.some( badge => {
return badge.metadataBadgeRenderer.style === verifiedLabel
});
At this point, verified is either true (if the channel is verified), or false. I hope this helps!

On verified channels, the class "has-badge" is present.
Work in 2018:
<?php
$key = 'has-badge';
$channel = file_get_contents('https://www.youtube.com/...');
if( stripos($channel, $key) !== FALSE )
echo "Verified";
else
echo "Not Verified";
?>

If may be possible to check infer the verified status of a youtube channel via the status.longUploadsStatus flag being either allowed or eligible, as currently this feature requires the associated youtube account to be verified.
source : https://developers.google.com/youtube/v3/docs/channels

Related

How to get the page Info.totalResults from the youtube api Search: list

Below is the code i have created so far, my goal is to use the youtube Search: list api to find streams for specific games and then publish how many streams there are for that game, I have a database for the game titles and this is my function below, my api link does work im just not able to get the Info.totalResults from it, any help would be great, Thank you for any help you can provide
function totalgamelist() {
global $wpdb;
$gamelistname = $wpdb->prefix . 'Games';
global $wpdb;
$getgames = $wpdb->get_results( 'SELECT * FROM '.$gamelistname , OBJECT );
if (empty($getgames)) {
//empty array
echo 'This is empty sorry!';
} else {
echo 'We Got Something!';
foreach ( $getgames as $getgame )
{
echo '<div class="gamename">'.$getgame->GameTitle;
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/search?part=snippet&eventType=live&type=video&videoCategoryId=20&regionCode=US&maxResults=50&q='.$getgame->GameTitle.'&key=[API KEY]");
$json_data = json_decode($JSON, true);
echo $json_data['totalResults'];
echo '</div>';
}
}
}
EDIT:
So with the help from johnh10, i was able to find out that it wasn't my ability to display the results although the echo johnh10 gave is correct :) it was also that my server was blocking access to the url i was asking to view. Below is the curl code i used to access the url, hope it helps others.
$urlgame = 'https://www.googleapis.com/youtube/v3/search?part=snippet&eventType=live&type=video&videoCategoryId=20&regionCode=US&maxResults=1&q='.$getgame->GameTitle.'&key=[API Key]';
$ch = curl_init($urlgame);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$json_data = json_decode($data, true);
if (!empty($json_data)) {
$streamnumber = $json_data['pageInfo']['totalResults'];
echo ' Streams:'.$streamnumber;
} else {
echo ' Streams: No Streams Found';
}
echo $json_data['pageInfo']['totalResults'];

Getting the price of Priority Mail Express in USPS shipping

I required to get the rate for standard post,priority mail as well as priority express mail.Using below code i am getting the price rates for priority mail and standard post but not for priority express mail.
When in service column i write the priority express mail then there was an error as given below(Priority mail express)
"The requested Mail Service is not available for the specified request attributes."
Code i am using is this:
{
$url = "http://Production.ShippingAPIs.com/ShippingAPI.dll";
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// parameters to post
curl_setopt($ch, CURLOPT_POST, 1);
$data = "API=RateV4&XML=<RateV4Request USERID=\"$userName\"><Package ID=\"1ST\"><Service>All</Service><ZipOrigination>$orig_zip</ZipOrigination><ZipDestination>$dest_zip</ZipDestination><Pounds>$weight</Pounds><Ounces>0</Ounces><Container/><Size>REGULAR</Size><Machinable>FALSE</Machinable></Package>
</RateV4Request>";
// send the POST values to USPS
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result=curl_exec ($ch);
$data = strstr($result, '<?');
//echo '<!-- '. $data. ' -->'; // Uncomment to show XML in comments
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (array_key_exists('attributes',$xml_elem)) {
list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
} else {
$level[$xml_elem['level']] = $xml_elem['tag'];
}
}
if ($xml_elem['type'] == 'complete') {
$start_level = 1;
$php_stmt = '$params';
while($start_level < $xml_elem['level']) {
$php_stmt .= '[$level['.$start_level.']]';
$start_level++;
}
$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
eval($php_stmt);
}
}
curl_close($ch);
//print_r($data);exit;
echo '<pre>'; print_r($params); echo'</pre>'; // Uncomment to see the full array
//echo $params['RATEV4RESPONSE']['1ST'][$servicecode]['RATE'];exit;
}
Priority Mail Express is not available for all types of shipments and it might be restricted in this case. Given that your request works for other mailclasses, there's a high likelihood that this is a shipping, not technical issue. It would help if you can share the specific parameters that you're sending.
If you want to play around with USPS shipping rates you can retrieve shipping rates for free with an easy UI or API at https://goshippo.com.

How to test file download in Behat

There is this new Export functionality developed on this application and I'm trying to test it using Behat/Mink.
The issue here is when I click on the export link, the data on the page gets exported in to a CSV and gets saved under /Downloads but I don't see any response code or anything on the page.
Is there a way I can export the CSV and navigate to the /Downloads folder to verify the file?
Assuming you are using the Selenium driver you could "click" on the link and $this->getSession()->wait(30) until the download is finished and then check the Downloads folder for the file.
That would be the simplest solution. Alternatively you can use a proxy, like BrowserMob, to watch all requests and then verify the response code. But that would be a really painful path for that alone.
The simplest way to check that the file is downloaded would be to define another step with a basic assertion.
/**
* #Then /^the file ".+" should be downloaded$/
*/
public function assertFileDownloaded($filename)
{
if (!file_exists('/download/dir/' . $filename)) {
throw new Exception();
}
}
This might be problematic in situations when you download a file with the same name and the browser saves it under a different name. As a solution you can add a #BeforeScenario hook to clear the list of the know files.
Another issue would be the download dir itself – it might be different for other users / machines. To fix that you could pass the download dir in your behat.yml as a argument to the context constructor, read the docs for that.
But the best approach would be to pass the configuration to the Selenium specifying the download dir to ensure it's always clear and you know exactly where to search. I am not certain how to do that, but from the quick googling it seems to be possible.
Checkout this blog: https://www.jverdeyen.be/php/behat-file-downloads/
The basic idea is to copy the current session and do the request with Guzzle. After that you can check the response any way you like.
class FeatureContext extends \Behat\Behat\Context\BehatContext {
/**
* #When /^I try to download "([^"]*)"$/
*/
public function iTryToDownload($url)
{
$cookies = $this->getSession()->getDriver()->getWebDriverSession()->getCookie('PHPSESSID');
$cookie = new \Guzzle\Plugin\Cookie\Cookie();
$cookie->setName($cookies[0]['name']);
$cookie->setValue($cookies[0]['value']);
$cookie->setDomain($cookies[0]['domain']);
$jar = new \Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar();
$jar->add($cookie);
$client = new \Guzzle\Http\Client($this->getSession()->getCurrentUrl());
$client->addSubscriber(new \Guzzle\Plugin\Cookie\CookiePlugin($jar));
$request = $client->get($url);
$this->response = $request->send();
}
/**
* #Then /^I should see response status code "([^"]*)"$/
*/
public function iShouldSeeResponseStatusCode($statusCode)
{
$responseStatusCode = $this->response->getStatusCode();
if (!$responseStatusCode == intval($statusCode)) {
throw new \Exception(sprintf("Did not see response status code %s, but %s.", $statusCode, $responseStatusCode));
}
}
/**
* #Then /^I should see in the header "([^"]*)":"([^"]*)"$/
*/
public function iShouldSeeInTheHeader($header, $value)
{
$headers = $this->response->getHeaders();
if ($headers->get($header) != $value) {
throw new \Exception(sprintf("Did not see %s with value %s.", $header, $value));
}
}
}
Little modified iTryToDownload() function with using all cookies:
public function iTryToDownload($link) {
$elt = $this->getSession()->getPage()->findLink($link);
if($elt) {
$value = $elt->getAttribute('href');
$driver = $this->getSession()->getDriver();
if ($driver instanceof \Behat\Mink\Driver\Selenium2Driver) {
$ds = $driver->getWebDriverSession();
$cookies = $ds->getAllCookies();
} else {
throw new \InvalidArgumentException('Not Selenium2Driver');
}
$jar = new \Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar();
for ($i = 0; $i < count($cookies); $i++) {
$cookie = new \Guzzle\Plugin\Cookie\Cookie();
$cookie->setName($cookies[$i]['name']);
$cookie->setValue($cookies[$i]['value']);
$cookie->setDomain($cookies[$i]['domain']);
$jar->add($cookie);
}
$client = new \Guzzle\Http\Client($this->getSession()->getCurrentUrl());
$client->addSubscriber(new \Guzzle\Plugin\Cookie\CookiePlugin($jar));
$request = $client->get($value);
$this->response = $request->send();
} else {
throw new \InvalidArgumentException(sprintf('Could not evaluate: "%s"', $link));
}
}
In project we have problem that we have two servers: one with web drivers and browsers and second with selenium hub. As result we decide to use curl request for fetching headers. So I wrote function which would called in step definition. Below you can find a function which use a standard php functions: curl_init()
/**
* #param $request_url
* #param $userToken
* #return bool
* #throws Exception
*/
private function makeCurlRequestForDownloadCSV($request_url, $userToken)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Content-Type: application/json',
"Authorization: Bearer {$userToken}"
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
$output .= "\n" . curl_error($ch);
curl_close($ch);
if ($output === false || $info['http_code'] != 200 || $info['content_type'] != "text/csv; charset=UTF-8") {
$output = "No cURL data returned for $request_url [" . $info['http_code'] . "]";
throw new Exception($output);
} else {
return true;
}
}
How you can see I have authorization by token. If you want to understand what headers you should use you should download file manual and look request and response in browser's tab network

how to get list of retweeters using streaming api

Is there a way to get the list of retweeters ids using streaming api
REST api has "GET statuses/:id/retweeted_by/ids" for getting the list of retweeters
Streaming api has a "statuses/retweet", but is not a generally available resources.
So the idea is to use "statuses/filter" and filter based on tweet ids.
Thank you
In the results returned by the streaming API, retweeters (if any) are listed here:
$retweeters = $tweet->{'retweeted_status'}->{'activities'}->{'retweeters'};
Here's a page which shows the ids of retweeters for a stream filtered with a search for the word 'love' — make sure to use your Twitter username and password. Note that the APIs only return the first 100 retweeters.
<html><body>
<?php
echo(str_pad("START<br>",2048));
#ob_flush();
flush();
$opts = array(
'http'=>array(
'method' => "POST",
'content' => 'track=love',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n"
)
);
$context = stream_context_create($opts);
$username = 'your_twitter_username';
$password = 'your_twitter_password';
while (1){
$instream = fopen('http://'.$username.':'.$password.'#stream.twitter.com/1/statuses/filter.json','r' ,false, $context);
while(! feof($instream)) {
if(! ($line = stream_get_line($instream, 20000, "\n"))) {
continue;
}else{
$tweet = json_decode($line);
$retweeters = array();
$retweeters = $tweet->{'retweeted_status'}->{'activities'}->{'retweeters'};
//We store the new post in the database, to be able to read it later
if (sizeof($retweeters) > 0) {
echo("<br><br>");
print_r($retweeters);
}
#ob_flush();
flush();
}
}
}
?>
</html></body>

google adwords api + getting all keywords

I'm using the google adwords api, I can retrieve all campaigns, group ads, ads,
but I have no idea on how to retrieve keywords related to an "group ads".
In the google adwords interface, when we select a group ads, we have two tabs, one for ads related to that group ads, and the second for keywords.
but programatily, right now I can only retrieve ads.
I'm using PHP, if some one knew how to do that in php or others programming languages or even a soap call.
To get the details of all the keywords of an adgroup you need the following to get the details of all the keywords.
require_once dirname(dirname(__FILE__)) . '/init.php';
// Enter parameters required by the code example.
$adGroupId = 'Enter your adgroup id';
/**
* Runs the example.
* #param AdWordsUser $user the user to run the example with
* #param string $adGroupId the id of the parent ad group
*/
function GetKeywordsExample(AdWordsUser $user, $adGroupId) {
// Get the service, which loads the required classes.
$adGroupCriterionService =
$user->GetService('AdGroupCriterionService', ADWORDS_VERSION);
// Create selector.
$selector = new Selector();
$selector->fields = array('KeywordText', 'KeywordMatchType', 'Id');
$selector->ordering[] = new OrderBy('KeywordText', 'ASCENDING');
// Create predicates.
$selector->predicates[] = new Predicate('AdGroupId', 'IN', array($adGroupId));
$selector->predicates[] =
new Predicate('CriteriaType', 'IN', array('KEYWORD'));
// Create paging controls.
$selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
do {
// Make the get request.
$page = $adGroupCriterionService->get($selector);
// Display results.
if (isset($page->entries)) {
foreach ($page->entries as $adGroupCriterion) {
printf("Keyword with text '%s', match type '%s', and ID '%s' was "
. "found.\n", $adGroupCriterion->criterion->text,
$adGroupCriterion->criterion->matchType,
$adGroupCriterion->criterion->id);
}
} else {
print "No keywords were found.\n";
}
// Advance the paging index.
$selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
} while ($page->totalNumEntries > $selector->paging->startIndex);
}
// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
return;
}
try {
// Get AdWordsUser from credentials in "../auth.ini"
// relative to the AdWordsUser.php file's directory.
$user = new AdWordsUser();
// Log every SOAP XML request and response.
$user->LogAll();
// Run the example.
GetKeywordsExample($user, $adGroupId);
} catch (Exception $e) {
printf("An error has occurred: %s\n", $e->getMessage());
}
In the Adwords API Keywords are dubbed as AdGroup Criteria. You can add or retrieve the keywords for a certain AdGroup by using the AdGroupCriterionService.
If you're using the PHP client library of the Adwords API check out GetAllAdGroupCriteria.php in the example files. (don't forget to enter the AdGroupId you want to get the keywords for first)

Resources