I've attempted to use the YouTube service API V3 and have run into an issue I'm unsure of how to proceed.
I'm calling my script through Jquery's Ajax. Nothing crazy.
Passing in an id for the video I want and away I go.
The script is as such:
session_start();
$return_msg = array();
// ===================================
// Require Google libraries
// ===================================
set_include_path("../../includes/");
if(!(#require_once('Google/Client.php')))
{
$return_msg['error'] = 'Unable to includes Google Client Library:<br>'.$e->getMessage();
return $return_msg;
}
if(!(#require_once('Google/Service/YouTube.php')))
{
$return_msg['error'] = 'Unable to includes Google YouTube Library:<br>'.$e->getMessage();
return $return_msg;
}
// ===================================
// Include Global settings
// ===================================
if(!(#require_once('Global-Settings.php')))
{
$return_msg['error'] = 'Unable to includes site settings:<br>'.$e->getMessage();
return $return_msg;
}
$globals = new Globals();
// Set API key
$api_key = $globals->youtube_key;
if(!isset($data['id']))
{
$return_msg['error'] = 'Unable to determine the video you are attempting to find.';
return $return_msg;
}
// ===================================
// Create Client
// ===================================
try
{
$client = new Google_Client();
$client->setApplicationName("YouTube_Test");
$client->setDeveloperKey($api_key);
}catch(Exception $e){
$return_msg['error'] = 'Error creating Google client:<br>'.$e->getMessage();
return $return_msg;
}
// ===================================
// Get video
// ===================================
try
{
$service = new Google_Service_YouTube($client);
$response = $service->videos->listVideos('id,snippet,contentDetails', array(
"id" => $data['id']
));
$return_msg['results'] = $response;
foreach($response->items as $video)
{
$item = array();
$item['id'] = $video['id'];
$item['snippet'] = $video['snippet'];]
$item['contentDetails'] = $video['contentDetails'];
$return_msg['items'][$item['id']] = $item;
}
}catch(Exception $e){
$return_msg['error'] = 'Error finding video:<br>'.$e->getMessage();
return $return_msg;
}
return $return_msg;
The reason I am storing the individual items in an array is because line $return_msg['results'] = $response; returns fields, yet not the items object as I'd expect.
Anywho, once I return all this to JS and log it to console, I see that inside the 'snippets' array there are no thumbnails.
Not sure why, or what I'm doing incorrectly as far as that goes. I've tried to log as much info as I could and I simply can't find any trace of the thumbnails collection.
A simple way to get thumbnail of a video from youtube is by using the video id:
http://img.youtube.com/vi/<your_video_id>/0.jpg
[0.jpg, 1.jpg, 2.jpg and 3.jpg can be used]
For Eg:
http://img.youtube.com/vi/-w8KI3A5zu4/0.jpg
if you got the video_id from youtube API, you can simply use this to get the image.
Related
I'm running some GA Requests as per Reporting API v4 (PHP)
I'm looping through multiple View IDs, some of which don't have the correct permissions. (I'm aware what permissions are required, however, sometimes I don't have the necessary access for one reason or another). When this happens, I get a 403 request error: "User does not have sufficient permissions for this profile." ... which I understand
While I'm looping through IDs, if one view ID returns such an error, it breaks my loop.
I would like to check the request status before executing $analytics->reports->batchGet( $body ); so that it doesn't break my loop. (i.e. don't run it if it returns an error).
My Question: What method can I call to check the request status before running batchGet()?
My Code
foreach($view_ids as $view_id){
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2015-06-15");
$dateRange->setEndDate("2015-06-30");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");
//Create the Dimensions object.
$browser = new Google_Service_AnalyticsReporting_Dimension();
$browser->setName("ga:browser");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($view_id);
$request->setDateRanges($dateRange);
$request->setDimensions(array($browser));
$request->setMetrics(array($sessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
// THIS IS WHERE I'M GETTING STUCK, DON'T KNOW WHICH METHOD TO CALL
//$request_status_code = $analyticsreporting->reports->[whichMethod]???
if($request_status_code == 200){
return $analyticsreporting->reports->batchGet( $body );
}
}
Let the user pick which view they want to access then run your code against that view. This code will show you how to list the views a user has access to.
accountsummeries.list
/**
* Note: This code assumes you have an authorized Analytics service object.
* See the Account Summaries Developer Guide for details.
*/
/**
* Example #1:
* Requests a list of all account summaries for the authorized user.
*/
try {
$accounts = $analytics->management_accountSummaries
->listManagementAccountSummaries();
} catch (apiServiceException $e) {
print 'There was an Analytics API service error '
. $e->getCode() . ':' . $e->getMessage();
} catch (apiException $e) {
print 'There was a general API error '
. $e->getCode() . ':' . $e->getMessage();
}
/**
* Example #2:
* The results of the list method are stored in the accounts object.
* The following code shows how to iterate through them.
*/
foreach ($accounts->getItems() as $account) {
$html = <<<HTML
<pre>
Account id = {$account->getId()}
Account kind = {$account->getKind()}
Account name = {$account->getName()}
HTML;
// Iterate through each Property.
foreach ($account->getWebProperties() as $property) {
$html .= <<<HTML
Property id = {$property->getId()}
Property kind = {$property->getKind()}
Property name = {$property->getName()}
Internal property id = {$property->getInternalWebPropertyId()}
Property level = {$property->getLevel()}
Property URL = {$property->getWebsiteUrl()}
HTML;
// Iterate through each view (profile).
foreach ($property->getProfiles() as $profile) {
$html .= <<<HTML
Profile id = {$profile->getId()}
Profile kind = {$profile->getKind()}
Profile name = {$profile->getName()}
Profile type = {$profile->getType()}
HTML;
}
}
$html .= '</pre>';
print $html;
}
I am using sample code from googles site and this throws no exceptions but returns no results.
If I use the API explorer the same data works just fine. I have tried different files (all from google sample code) different settings. All of which give me the same result, Nothing.
function transcribe_sync($content)
{
// set string as audio content
$audio = (new RecognitionAudio())
->setContent($content);
// set config
$encoding = AudioEncoding::LINEAR16;
$sampleRateHertz = 32000;
$languageCode = 'en-US';
$config = (new RecognitionConfig())
->setEncoding($encoding)
->setSampleRateHertz($sampleRateHertz)
->setAudioChannelCount(1)
->setMaxAlternatives(1)
->setLanguageCode($languageCode);
// create the speech client
$client = new SpeechClient();
try {
$response = $client->recognize($config, $audio);
echo $response->getResults()
}
catch (\Exception $e) {
$this->handleError('Error determining recognition. ' . $e->getMessage());
}
finally {
$client->close();
}
My resolution to this issues was the way I was passing the file (don't think the file was being populated correctly or at all). It was weird that I did not get an error. Because of the length of my audio files, I ended up integrating google storage to upload the file () and used:
$audio = (new RecognitionAudio())->setUri("gs://...");
... longRunningRecognize($config, $audio);
Hope this helps someone.
I can't seem to get tracking options created, the Category itself is creating fine.
However firstly - I should point out I believe there is a bug in the Xero-API for PHP, when debugging adding an option according to the documentation here the PUT should be
https://api.xero.com/api.xro/2.0/TrackingCategories/{TrackingCategoryID}/Options
However in the php lib it is
https://api.xero.com/api.xro/2.0/TrackingCategories/{TrackingCategoryID}/TrackingOptions
Even when that is resolved, I get no error however not tracking Option is created, any ideas?
$options = ['US', 'UK'];
$title = 'Region';
$trackingCategory = null;
if(!$trackingCategory) {
$trackingCategory = new \XeroPHP\Models\Accounting\TrackingCategory($xero);
$trackingCategory->setName($title);
$trackingCategory->save();
}
try {
foreach($options as $option) {
$to = new \XeroPHP\Models\Accounting\TrackingCategory\TrackingOption($xero);
$to->setName($option);
$trackingCategory->setOption($option);
$trackingCategory->save();
}
} catch(\Exception $e) {
$this->logger()->info($e->getTraceAsString());
$this->logger()->info("TRACKING: ". $e->getMessage());
return false;
}
So this would appear it is a bug as reported here
The source has not been fixed, however the above link resolves the problem for anyone else searching.
Changing TrackingOptions to Options in XeroPHP worked soughta... but I was still getting a different error. Ended up creating the Option manually
Note: $this->_xero_oauth_object is my \XeroPHP\Application\PublicApplication from authentication
// Create the URL object based on an absolute URL
$url = new \XeroPHP\Remote\URL($this->_xero_oauth_object, "https://api.xero.com/api.xro/2.0/TrackingCategories/{TrackCategoryGuid}/Options");
// Pass this to the request as a PUT request
$request = new \XeroPHP\Remote\Request($this->_xero_oauth_object, $url, \XeroPHP\Remote\Request::METHOD_PUT);
// Probably a better way but I just copied and paste the XML from the Xero API docs.
$request->setBody("<Options><Option><Name>My New Option Name</Name></Option></Options>");
// I wrapped this in a try - if it exists, there will be an error as you cant have duplicates.
try {
$request->send();
} catch (Exception $e) {
\Log::warn("Xero error: " . print_r($request->getResponse(), true));
}
// now option is created, new add the option to the tracking category
$tracking = new \XeroPHP\Models\Accounting\TrackingCategory($this->_xero_oauth_object);
$tracking->setTrackingCategoryID('3fceedc7-764e-490a-ac27-25684473af78');
// tracking category name - not sure if I need this
$tracking->setName('Contractor');
// match the option name above
$tracking->setOption('My New Option Name');
I create an rest api with php usring restler libary, its work well in my PC but when I uploaded the api to server, problems begin..
this function in my api
<?php
class user {
/**
#url GET /
*/
public function getAllInfo(){
$link = new PDO('mysql:host=localhost;dbname=---;charset=utf8','---','-----');
$handle = $link->prepare('select * from user');
$handle->execute();
$result = $handle->fetchAll(PDO::FETCH_OBJ);
if(empty($result)){
$err = new stdClass();
$err->error = "No user found";
return $err;
}
else{
return $result;
}
}
require_once 'restler.php';
$r = new Restler();
$r->setSupportedFormats('JsonFormat');
$r->addAPIClass('user');
$r->handle();
?>
when I access to this page nothing appear in browser
I thought the problem is this page can't access to require_once 'restler.php';
but I was wrong, because whan I print $r->handle(); like this print_r($r->handle());
this is what I see in browser
Luracast\Restler\EventDispatcher Object ( [listeners:Luracast\Restler\EventDispatcher:private] => Array ( ) [events:protected] => Array ( ) )
I don't know what is that or what I should do to print my json,
my database is full of data, its return json if my query doesn't have restler, but I need use restler with my code
I am currently working with the Amazon MWS to integrate some features into wordpress via a plugin. I am using the client libraries provided by amazon found here:
https://developer.amazonservices.com/api.html?group=bde§ion=reports&version=latest
Using these client libraries and the sample php files included I have set up my plugin to make two API calls. The first is requestReport
public function requestInventoryReport() {
AWI_Amazon_Config::defineCredentials(); // Defines data for API Call
$serviceUrl = "https://mws.amazonservices.com";
$config = array (
'ServiceURL' => $serviceUrl,
'ProxyHost' => null,
'ProxyPort' => -1,
'MaxErrorRetry' => 3,
);
$service = new MarketplaceWebService_Client(
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
$config,
APPLICATION_NAME,
APPLICATION_VERSION);
$request = new MarketplaceWebService_Model_RequestReportRequest();
$request->setMerchant(MERCHANT_ID);
$request->setReportType('_GET_MERCHANT_LISTINGS_DATA_');
self::invokeRequestReport($service, $request);
}
private function invokeRequestReport(MarketplaceWebService_Interface $service, $request) {
try {
$response = $service->requestReport($request);
if ($response->isSetRequestReportResult()) {
// Print Out Data
}
} catch (MarketplaceWebService_Exception $ex) {
// Print Out Error
}
}
and the second is getReportRequestList which has code similar to the first function. I am able to run these functions without any errors. The issue that I am having is that $response->isSetRequestReportResult() returns false. From my understanding and looking into the response object, this would suggest that the response object does not have the result. (Upon printing out the response object I can see that the FieldValue of the result array is NULL.) The call, however, does not throw an error but neither does it have the result.
I did some digging through the code and found that the result does actually get returned from the api call but never gets set to the return object when the library attempts to parse it from XML. I've tracked the error down to this block of code (This code is untouched by me and directly from the amazon mws reports library).
private function fromDOMElement(DOMElement $dom)
{
$xpath = new DOMXPath($dom->ownerDocument);
$xpath->registerNamespace('a', 'http://mws.amazonaws.com/doc/2009-01-01/');
foreach ($this->fields as $fieldName => $field) {
$fieldType = $field['FieldType'];
if (is_array($fieldType)) {
if ($this->isComplexType($fieldType[0])) {
// Handle Data
} else {
// Handle Data
}
} else {
if ($this->isComplexType($fieldType)) {
// Handle Data
} else {
$element = $xpath->query("./a:$fieldName/text()", $dom);
$data = null;
if ($element->length == 1) {
switch($this->fields[$fieldName]['FieldType']) {
case 'DateTime':
$data = new DateTime($element->item(0)->data,
new DateTimeZone('UTC'));
break;
case 'bool':
$value = $element->item(0)->data;
$data = $value === 'true' ? true : false;
break;
default:
$data = $element->item(0)->data;
break;
}
$this->fields[$fieldName]['FieldValue'] = $data;
}
}
}
}
}
The data that should go into the RequestReportResult exists at the beginning of this function as a node in the dom element. The flow of logic takes it into the last else statement inside the foreach. The code runs its query and returns $element however $element->length = 13 in my case which causes it to fail the if statement and never set the data to the object. I have also looked into $element->item(0) to see what was in it and it appears to be a dom object itself matching the original dom object but with a bunch of empty strings.
Now, I'm new to working with the MWS and my gut feeling is that I am missing a parameter somewhere in my api call that is messing up how the data is returned and is causing this weird error, but I'm out of ideas at this point. If anyone has any ideas or could point me in the right direction, I would greatly appreciate it.
Thanks for your time!
** Also as a side note, Amazon Scratchpad does return everything properly using the same parameters that I am using in my code **
These works for me, check if you are missing anything.
For RequestReportRequest i am doing this:
$request = new MarketplaceWebService_Model_RequestReportRequest();
$marketplaceIdArray = array("Id" => array($pos_data['marketplace_id']));
$request->setMarketplaceIdList($marketplaceIdArray);
$request->setMerchant($pos_data['merchant_id']);
$request->setReportType($this->report_type);
For GetReportRequestList i am doing this:
$service = new MarketplaceWebService_Client($pos_data['aws_access_key'], $pos_data['aws_secret_access_key'], $pos_data['config'], $pos_data['application_name'], $pos_data['application_version']);
$report_request = new MarketplaceWebService_Model_GetReportRequestListRequest();
$report_request->setMerchant($pos_data["merchant_id"]);
$report_type_request = new MarketplaceWebService_Model_TypeList();
$report_type_request->setType($this->report_type);
$report_request->setReportTypeList($report_type_request);
$report_request_status = $this->invokeGetReportRequestList($service, $report_request, $report_requestID);