Iam trying to download a reports for various sub-accounts under an MCC account. I am setting the clientCustomerId from within my code since I would want to loop through the various clientCustomerIds to have all the reports downloaded in one run. So far I have been testing it with one clientCustomerId but I get the following error:
An error has occurred: The client customer ID must be specified for report downloads.
I have no idea where I am going wrong. I am using AdWords API v201406:
Here is the code:
<?php
require_once dirname(dirname(__FILE__)) . '/init.php';
require_once ADWORDS_UTIL_PATH . '/ReportUtils.php';
/**
* Runs the example.
* #param AdWordsUser $user the user to run the example with
* #param string $filePath the path of the file to download the report to
*/
function KeywordPerformanceReport(AdWordsUser $user, $filePath) {
// Load the service, so that the required classes are available.
$user->LoadService('ReportDefinitionService', ADWORDS_VERSION);
// Create selector.
$selector = new Selector();
$selector->fields = array('AccountDescriptiveName', 'CampaignId', 'CampaignName', 'CampaignStatus', 'AdGroupId', 'AdGroupName', 'AdGroupStatus',
'AverageCpc', 'AveragePageviews', 'AverageTimeOnSite', 'Id', 'Impressions', 'KeywordText', 'Clicks', 'PlacementUrl', 'TrackingUrlTemplate', 'ConversionRate', 'Conversions', 'Cost', 'Date', 'DayOfWeek', 'DestinationUrl');
// Filter out removed criteria.
$selector->predicates[] = new Predicate('Status', 'NOT_IN', array('REMOVED'));
// Create report definition.
$reportDefinition = new ReportDefinition();
$reportDefinition->selector = $selector;
$reportDefinition->reportName = 'Keyword performance report #' . time();
$reportDefinition->dateRangeType = 'YESTERDAY';
$reportDefinition->reportType = 'KEYWORDS_PERFORMANCE_REPORT';
$reportDefinition->downloadFormat = 'CSV';
// Exclude criteria that haven't recieved any impressions over the date range.
$reportDefinition->includeZeroImpressions = FALSE;
// Set additional options.
$options = array('version' => ADWORDS_VERSION);
// Download report.
ReportUtils::DownloadReport($reportDefinition, $filePath, $user, $options);
printf("Report with name '%s' was downloaded to '%s'.\n",
$reportDefinition->reportName, $filePath);
}
// 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();
$customerId='xxx-xxx-xxx';
$user->SetClientId($customerId);
// Log every SOAP XML request and response.
$user->LogAll();
// Download the report to a file in the same directory as the example.
$filePath = dirname(__FILE__) . '/report.csv';
// Run the example.
KeywordPerformanceReport($user, $filePath);
} catch (Exception $e) {
printf("An error has occurred: %s\n", $e->getMessage());
}
You can also use like this (Adwords Api Version : v201502)
$user = new AdWordsUser(NULL, NULL, NULL, NULL, NULL, NULL, $oauth2Info);
$user->SetClientCustomerId($clientCustomerId);
$user->LogAll();
I normally pass the customer id in when instantiating the user. This code is from v201402.
$user = new AdWordsUser(NULL, NULL, NULL, NULL, NULL, NULL, $customerID);
use the function SetClientCustomerId() to get the data from multiple account, this was supported in previous version of API, which is now withClientCustomerId() present in AdWordsSessionBuilder.
Related
I want to make functionality for users to upload video on my channel without authentication (if needed). IS it possible ?
Please help me .
Thanks
OM
Yes Omprakash,it is possible
You will need Google APIs Client Library for PHP.
You will also need to create a project on
https://console.developers.google.com/ and get credentials(i.e
client secret & client id).
Finally,you will need to generate access token for specific channel.
Please take a look at this link
(https://youtube-eng.googleblog.com/2013/06/google-page-identities-and-youtube-api_24.html)
to generate access token.
Once you have all these things ready with you,you can use ready made
example code available in Google APIs Client Library for PHP to upload
video on YouTube.
Note: This is not in detail process.It is not possible to explain all of the process in detail on stack-overflow. But, once you get close to solution,you can re-post or put comment for further assistance.
This is example code to upload video on YouTube. Hope, it will help you
/*include google libraries */
require_once '../api/src/Google/autoload.php';
require_once '../api/src/Google/Client.php';
require_once '../api/src/Google/Service/YouTube.php';
$application_name = 'Your application/project name created on google developer console';
$client_secret = 'Your client secret';
$client_id = 'Your client id';
$scope = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtubepartner');
try{
$key = file_get_contents('the_key.txt'); //it stores access token obtained in step 3
$videoPath = 'video path on your server goes here';
$videoTitle = 'video title';
$videoDescription = 'video description';
$videoCategory = "22"; //please take a look at youtube video categories for videoCategory.Not so important for our example
$videoTags = array('tag1', 'tag2','tag3');
// Client init
$client = new Google_Client();
$client->setApplicationName($application_name);
$client->setClientId($client_id);
$client->setAccessType('offline');
$client->setAccessToken($key);
$client->setScopes($scope);
$client->setClientSecret($client_secret);
if ($client->getAccessToken()) {
/**
* Check to see if our access token has expired. If so, get a new one and save it to file for future use.
*/
if($client->isAccessTokenExpired()) {
$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);
file_put_contents('the_key.txt', $client->getAccessToken());
}
$youtube = new Google_Service_YouTube($client);
// Create a snipet with title, description, tags and category id
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle($videoTitle);
$snippet->setDescription($videoDescription);
$snippet->setCategoryId($videoCategory);
$snippet->setTags($videoTags);
// Create a video status with privacy status. Options are "public", "private" and "unlisted".
$status = new Google_Service_YouTube_VideoStatus();
$status->setPrivacyStatus('public');
// Create a YouTube video with snippet and status
$video = new Google_Service_YouTube_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
// Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks,
// for reliable connections). Setting it lower leads better recovery (fine-grained chunks)
$chunkSizeBytes = 1 * 1024 * 1024;
// Setting the defer flag to true tells the client to return a request which can be called
// with ->execute(); instead of making the API call immediately.
$client->setDefer(true);
// Create a request for the API's videos.insert method to create and upload the video.
$insertRequest = $youtube->videos->insert("status,snippet", $video);
// Create a MediaFileUpload object for resumable uploads.
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($videoPath));
// Read the media file and upload it chunk by chunk.
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
/**
* Video has successfully been upload, now lets perform some cleanup functions for this video
*/
if ($status->status['uploadStatus'] == 'uploaded') {
$youtube_id = $status->id; //you got here youtube video id
} else {
// handle failere here
}
// If you want to make other calls after the file upload, set setDefer back to false
$client->setDefer(true);
} else{
// #TODO Log error
echo 'Problems creating the client';
}
} catch(Google_Service_Exception $e) {
echo "\r\n Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage();
echo "\r\n Stack trace is ".$e->getTraceAsString();
} catch (Exception $e) {
echo "\r\n Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage();
echo "\r\n Stack trace is ".$e->getTraceAsString();
}
To generate/initiate a new vulnerability scan at SoftLayer, this works (for every server in an account):
require_once('SoapClient.class.php');
$apiUsername = "omitted";
$apiKey = "omitted";
$client = SoftLayer_SoapClient::getClient('SoftLayer_Account', null, $apiUsername, $apiKey);
$accountInfo = $client->getObject();
$hardware = $client->getHardware();
foreach ($hardware as $server){
$scanclient = SoftLayer_SoapClient::getClient('SoftLayer_Network_Security_Scanner_Request', '', $apiUsername, $apiKey);
$scantemplate = new stdClass();
$scantemplate->accountId = $accountInfo->id;
$scantemplate->hardwareId = $server->id;
$scantemplate->ipAddress = $server->primaryIpAddress;
try{
// Successfully creates new scan
$scan = $scanclient->createObject($scantemplate);
} catch (Exception $e){
echo $e->getMessage() . "\n\r";
}
}
When changing
$reportstatus = $scanclient->createObject($scantemplate);
to
$reportstatus = $scanclient->getReport($scantemplate);
The API responds with an error concerning "Object does not exist to execute method on.".
Would SoftLayer_Network_Security_Scanner_RequestInitParameters be required as per the docs? If so how do you define these "init parameters" and attach to the request for status or report?
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Security_Scanner_Request/getReport
You need to set the init parameter using the Softlayer PHP client you can do that like this:
When you are creating the client:
$virtualGuestService = SoftLayer_SoapClient::getClient('SoftLayer_Virtual_Guest', $initParemter, $username, $key);
Or after creating the client:
$virtualGuestService = SoftLayer_SoapClient::getClient('SoftLayer_Virtual_Guest', null, $username, $key);
# Setting the init parameter
$virtualGuestService->setInitParameter($virtualGuestId);
The init parameter is basically the id of the object you wish to get edit or delete, in this case the init parameter is the id of the vulnerability scan you wish to get the report.
You can try this code:
$scanclient = SoftLayer_SoapClient::getClient('SoftLayer_Network_Security_Scanner_Request', '', $apiUsername, $apiKey);
$scanclient->setInitParameter(15326); # The id of the vulnerability scan
$reportstatus = $scanclient->getReport();
To get the list of your vulnerabilities scans in a VSI you can use this method:
http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/getSecurityScanRequests
and for bare metal servers you can use this one:
http://sldn.softlayer.com/reference/services/SoftLayer_Hardware_Server/getSecurityScanRequests
Regards
I've downloaded the PHP client library for Google Adwords API. I need to fetch 'ConversionsManyPerClick' data from the api, I can't find an option for the same from the client library. But the same time i am able to take this data as file by using this 'AD_PERFORMANCE_REPORT' method. Please help me.
function DownloadCriteriaReportExample(AdWordsUser $user, $filePath) {
// Load the service, so that the required classes are available.
$user->LoadService('ReportDefinitionService');
// Create selector.
$selector = new Selector();
$selector->fields = array('Headline','Description1','Description2','DisplayUrl','AdGroupName','CampaignName','Clicks','ConversionsManyPerClick');
$selector->predicates[] = new Predicate('Status', 'NOT_IN', array('PAUSED'));
$reportDefinition = new ReportDefinition();
$reportDefinition->selector = $selector;
$reportDefinition->reportName = 'ad performance report #' . uniqid();
$reportDefinition->dateRangeType = 'LAST_30_DAYS';
$reportDefinition->reportType = 'AD_PERFORMANCE_REPORT';
$reportDefinition->downloadFormat = 'CSV';
$reportDefinition->includeZeroImpressions = FALSE;
$options = array('version' => 'v201502');
ReportUtils::DownloadReport($reportDefinition, $filePath, $user, $options);
}
Thanks in advance.
Please read the following documentation and also try to modify the core plugin
https://developers.google.com/adwords/api/docs/guides/conversion-tracking
I am trying to upload a video to Youtube using PHP. I am using Youtube API v3 and I am using the latest checked out source code of Google API PHP Client library.
I am using the sample code given on
https://code.google.com/p/google-api-php-client/ to perform the authentication. The authentication goes through fine but when I try to upload a video I get Google_ServiceException with error code 500 and message as null.
I had a look at the following question asked earlier:
Upload video to youtube using php client library v3 But the accepted answer doesn't describe how to specify file data to be uploaded.
I found another similar question Uploading file with Youtube API v3 and PHP, where in the comment it is mentioned that categoryId is mandatory, hence I tried setting the categoryId in the snippet but still it gives the same exception.
I also referred to the Python code on the the documentation site ( https://developers.google.com/youtube/v3/docs/videos/insert ), but I couldn't find the function next_chunk in the client library. But I tried to put a loop (mentioned in the code snippet) to retry on getting error code 500, but in all 10 iterations I get the same error.
Following is the code snippet I am trying:
$youTubeService = new Google_YoutubeService($client);
if ($client->getAccessToken()) {
print "Successfully authenticated";
$snippet = new Google_VideoSnippet();
$snippet->setTitle = "My Demo title";
$snippet->setDescription = "My Demo descrition";
$snippet->setTags = array("tag1","tag2");
$snippet->setCategoryId(23); // this was added later after refering to another question on stackoverflow
$status = new Google_VideoStatus();
$status->privacyStatus = "private";
$video = new Google_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
$data = file_get_contents("video.mp4"); // This file is present in the same directory as the code
$mediaUpload = new Google_MediaFileUpload("video/mp4",$data);
$error = true;
$i = 0;
// I added this loop because on the sample python code on the documentation page
// mentions we should retry if we get error codes 500,502,503,504
$retryErrorCodes = array(500, 502, 503, 504);
while($i < 10 && $error) {
try{
$ret = $youTubeService->videos->insert("status,snippet",
$video,
array("data" => $data));
// tried the following as well, but even this returns error code 500,
// $ret = $youTubeService->videos->insert("status,snippet",
// $video,
// array("mediaUpload" => $mediaUpload);
$error = false;
} catch(Google_ServiceException $e) {
print "Caught Google service Exception ".$e->getCode()
. " message is ".$e->getMessage();
if(!in_array($e->getCode(), $retryErrorCodes)){
break;
}
$i++;
}
}
print "Return value is ".print_r($ret,true);
// We're not done yet. Remember to update the cached access token.
// Remember to replace $_SESSION with a real database or memcached.
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a href='$authUrl'>Connect Me!</a>";
}
Is it something that I am doing wrong?
I was able to get the upload working using the following code:
if($client->getAccessToken()) {
$snippet = new Google_VideoSnippet();
$snippet->setTitle("Test title");
$snippet->setDescription("Test descrition");
$snippet->setTags(array("tag1","tag2"));
$snippet->setCategoryId("22");
$status = new Google_VideoStatus();
$status->privacyStatus = "private";
$video = new Google_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
$error = true;
$i = 0;
try {
$obj = $youTubeService->videos->insert("status,snippet", $video,
array("data"=>file_get_contents("video.mp4"),
"mimeType" => "video/mp4"));
} catch(Google_ServiceException $e) {
print "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage(). " <br>";
print "Stack trace is ".$e->getTraceAsString();
}
}
I realize this is old, but here's the answer off the documentation:
// REPLACE this value with the path to the file you are uploading.
$videoPath = "/path/to/file.mp4";
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle("Test title");
$snippet->setDescription("Test description");
$snippet->setTags(array("tag1", "tag2"));
// Numeric video category. See
// https://developers.google.com/youtube/v3/docs/videoCategories/list
$snippet->setCategoryId("22");
// Set the video's status to "public". Valid statuses are "public",
// "private" and "unlisted".
$status = new Google_Service_YouTube_VideoStatus();
$status->privacyStatus = "public";
// Associate the snippet and status objects with a new video resource.
$video = new Google_Service_YouTube_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
// Specify the size of each chunk of data, in bytes. Set a higher value for
// reliable connection as fewer chunks lead to faster uploads. Set a lower
// value for better recovery on less reliable connections.
$chunkSizeBytes = 1 * 1024 * 1024;
// Setting the defer flag to true tells the client to return a request which can be called
// with ->execute(); instead of making the API call immediately.
$client->setDefer(true);
// Create a request for the API's videos.insert method to create and upload the video.
$insertRequest = $youtube->videos->insert("status,snippet", $video);
// Create a MediaFileUpload object for resumable uploads.
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($videoPath));
// Read the media file and upload it chunk by chunk.
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
// If you want to make other calls after the file upload, set setDefer back to false
$client->setDefer(false);
I also realize this is old, but as I cloned the latest version of php-client from GitHub I ran in to trouble with Google_Service_YouTube_Videos_Resource::insert()-method.
I would pass an array with "data" => file_get_contents($pathToVideo) and "mimeType" => "video/mp4" set as an argument for the insert()-method, but I still kept getting (400) BadRequest in return.
Debugging and reading through Google's code i found in \Google\Service\Resource.php there was a check (on lines 179-180) against an array key "uploadType" that would initiate the Google_Http_MediaFielUpload object.
$part = 'status,snippet';
$optParams = array(
"data" => file_get_contents($filename),
"uploadType" => "media", // This was needed in my case
"mimeType" => "video/mp4",
);
$response = $youtube->videos->insert($part, $video, $optParams);
If I remember correctly, with version 0.6 of the PHP-api the uploadType argument wasn't needed. This might apply only for the direct upload style and not the resumable upload shown in Any Day's answer.
The answer would be using Google_Http_MediaFileUpload through the Google PHP client libraries.
Here's the sample code: https://github.com/youtube/api-samples/blob/master/php/resumable_upload.php
Using the latest PHP CLient Library (v2.6.3) I can't seem to figure out to get all campaigns for a client in my MCC (my client center) account.
I can easily get all accounts via:
$user = new AdWordsUser(NULL, $email, $password, $devToken, $applicationToken, $userAgent, NULL, $settingsFile);
$service = $user->GetServicedAccountService();
$selector = new ServicedAccountSelector();
$selector->enablePaging = false;
$graph = $service->get($selector);
$accounts = $graph->accounts; // all accounts!
Now that I've done that, I want to get all the campaigns within each account. Running the code as documented here doesn't work.
// Get the CampaignService.
// ** Different than example because example calls a private method ** //
$campaignService = $user->GetCampaignService('v201101');
// Create selector.
$selector = new Selector();
$selector->fields = array('Id', 'Name');
$selector->ordering = array(new OrderBy('Name', 'ASCENDING'));
// Get all campaigns.
$page = $campaignService->get($selector);
// Display campaigns.
if (isset($page->entries)) {
foreach ($page->entries as $campaign) {
print 'Campaign with name "' . $campaign->name . '" and id "'
. $campaign->id . "\" was found.\n";
}
}
All the above code will do is throw an error:
Fatal error: Uncaught SoapFault exception: [soap:Server]
QuotaCheckError.INVALID_TOKEN_HEADER # message=null
stack=com.google.ads.api.authserver.common.AuthException at
com.go;
I have a feeling that the reason this fails is that GetCampaignService needs an account's id...but I can't figure out how to specify this id.
What am I doing wrong?
The problem ended up being that I was given the wrong developerToken. I didn't think INVALID_TOKEN_HEADER really meant what it said because SOME calls still worked with the faulty token. I don't know why.