I am trying to get some YouTube Analytics reports using the API with a Service account in order to perform some CRON jobs. I've already solved the common problem of NTP server sync and, obviously, i've set up the API console properly.
<?php
ini_set('display_errors', 1);
require_once 'gapi/src/Google_Client.php';
require_once 'gapi/src/contrib/Google_YouTubeAnalyticsService.php';
// Define constants.
const CLIENT_ID = '************************.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = '************************#developer.gserviceaccount.com';
const KEY_FILE = '************************-privatekey.p12';
const MY_CHANNEL = '************************';
$client = new Google_Client();
$client->setApplicationName("YouTube Analytics API Test");
session_start();
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array("https://www.googleapis.com/auth/yt-analytics.readonly"),
$key)
);
$client->setClientId(CLIENT_ID);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$token = $client->getAccessToken();
$youtubeAnalyticsService = new Google_YouTubeAnalyticsService($client);
$optparam = array("dimensions" => "country", "max-results" => "10");
$reports = $youtubeAnalyticsService->reports->query("channel==" . MY_CHANNEL, "2013-09-01", "2013-09-25", "views", $optparam);
echo $reports;
?>
returns to me this message:
Fatal error: Uncaught exception 'Google_ServiceException' with message
'Error calling GET https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DmychannelID&start-date=2013-09-01&end-date=2013-09-25&metrics=views&dimensions=country&max-results=10: (500) Unknown error occurred on the server.' in /mydomain/gapi/src/io/Google_REST.php:66
Stack trace:
0 /mydomain/gapi/src/io/Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest))
1 /mydomain/gapi/src/service/Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest))
2 /mydomain/gapi/src/contrib/Google_YouTubeAnalyticsService.php(48): Google_ServiceResource->__call('query', Array)
3 /mydomain/myfile.php(45): Google_ReportsServiceResource->query('channel==...', '2013-09-01', '2013-09-25', 'views', Array)
4 {main} thrown in /mydomain/gapi/src/io/Google_REST.php on line 66
Any suggestion? Thank you all in advance!
Related
In the incoming call back url
I have the next code:
Twilio Call id
if (isset($_REQUEST['CallSid'])){
$tw_call_id = $_REQUEST['CallSid'];
}
else {
$tw_call_id = '';<br />
}<br />
$sid = "Axxxx";
$token = "Txxxx";
$twilio = new Client($sid, $token);
$recording = $twilio->calls($tw_call_id)
->recordings
->create([
"recordingStatusCallback" => "https://mycode.php",
"recordingStatusCallbackEvent" => ["completed"],
"recordingChannels" => "dual"
]
);
After this I have a say() and a dial() , so I want to record the say and the dial , no only the dial call
I got the error
PHP Fatal error: Uncaught Twilio\Exceptions\RestException: [HTTP 400] Unable to create record: Requested resource is not eligible for recording in /var/www/html/vendor/twilio/sdk/src/Twilio/Version.php
What I am looking for is to record the complete conversation from incoming call
Although, we'd prepared YouTube channel art upload mechanism as described on the it's official documentation page, (https://developers.google.com/youtube/v3/docs/channelBanners/insert), from few days, we are facing following error,
A service error occurred: { "error": { "errors": [ { "domain": "global", "reason": "backendError", "message": "Backend Error" } ], "code": 500, "message": "Backend Error" } }
Which was perfectly working before.
/**
* This sample sets a custom banner for a user's channel by:
*
* 1. Uploading a banner image with "youtube.channelBanners.insert" method via resumable upload
* 2. Getting user's channel object with "youtube.channels.list" method and "mine" parameter
* 3. Updating channel's banner external URL with "youtube.channels.update" method
*
* #author Ibrahim Ulukaya
*/
/**
* Library Requirements
*
* 1. Install composer (https://getcomposer.org)
* 2. On the command line, change to this directory (api-samples/php)
* 3. Require the google/apiclient library
* $ composer require google/apiclient:~2.0
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();
//session_destroy();
/*
* You can acquire an OAuth 2.0 client ID and client secret from the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* For more information about using OAuth 2.0 to access Google APIs, please see:
* <https://developers.google.com/youtube/v3/guides/authentication>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$OAUTH2_CLIENT_ID = 'OUR_CLIENT_ID';
$OAUTH2_CLIENT_SECRET = 'OUR_CLIENT_SECRET';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
$htmlBody = '';
try{
// REPLACE with the path to your file that you want to upload for thumbnail
$imagePath = "2560x1440-pixels-image.jpg";
$imageSize = get_headers($imagePath, 1);
// 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);
$chan = new Google_Service_YouTube_ChannelBannerResource();
// Create a request for the API's channelBanners.insert method to upload the banner.
$insertRequest = $youtube->channelBanners->insert($chan);
// Create a MediaFileUpload object for resumable uploads.
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'image/jpeg',
null,
true,
$chunkSizeBytes
);
//$media->setFileSize(filesize($imagePath));
$media->setFileSize($imageSize["Content-Length"]);
// Read the media file and upload it chunk by chunk.
$status = false;
$handle = fopen($imagePath, "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);
$thumbnailUrl = $status['url'];
// Call the API's channels.list method with mine parameter to fetch authorized user's channel.
$listResponse = $youtube->channels->listChannels('brandingSettings', array(
'mine' => 'true',
));
/*echo '<pre>';
print_r($listResponse);
echo '</pre>';*/
$responseChannel = $listResponse[0];
$responseChannel['brandingSettings']['image']['bannerExternalUrl']=$thumbnailUrl;
// Call the API's channels.update method to update branding settings of the channel.
$updateResponse = $youtube->channels->update('brandingSettings', $responseChannel);
$bannerMobileUrl = $updateResponse["brandingSettings"]["image"]["bannerMobileImageUrl"];
$htmlBody .= "<h3>Thumbnail Uploaded</h3><ul>";
$htmlBody .= sprintf('<li>%s</li>',
$thumbnailUrl);
$htmlBody .= sprintf('<img src="%s">', $bannerMobileUrl);
$htmlBody .= '</ul>';
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'OUR_CLIENT_ID') {
$htmlBody = <<<END
<h3>Client Credentials Required</h3>
<p>
You need to set <code>\$OAUTH2_CLIENT_ID</code> and
<code>\$OAUTH2_CLIENT_ID</code> before proceeding.
<p>
END;
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>Banner Uploaded and Set</title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>
Any suggestions?
I am not trying to do anything fancy. I am just trying to send an email using API of mandrill. I have included the library but I still get the error: "Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host smtp.mandrillapp.com [Connection refused #111]' in /home/laundryanna/public_html/mandrill/lib/classes/Swift/Transport/StreamBuffer.php:265 Stack trace: #0 /home/laundryanna/public_html/mandrill/lib/classes/Swift/Transport/StreamBuffer.php(62): Swift_Transport_StreamBuffer->_establishSocketConnection() #1 /home/laundryanna/public_html/mandrill/lib/classes/Swift/Transport/AbstractSmtpTransport.php(113): Swift_Transport_StreamBuffer->initialize(Array) #2 /home/laundryanna/public_html/mandrill/lib/classes/Swift/Mailer.php(79): Swift_Transport_AbstractSmtpTransport->start() #3 /home/laundryanna/public_html/mandrill/mailed.php(26): Swift_Mailer->send(Object(Swift_Message), Array) #4 {main} thrown in /home/laundryanna/public_html/mandrill/lib/classes/Swift/Transport/StreamBuffer.php on line 265". Here is the code:
<?php
include_once "lib/swift_required.php";
$subject = 'Hello from Mandrill, PHP!';
$from = array('mail1#example.com' =>'EA CEO');
$to = array(
'email1#gmail.com' => '$_POST["e1"]',
'email1' => 'Recipient2 Name'
);
$text = "Mandrill speaks plaintext";
$html = "<em>Mandrill speaks <strong>HTML</strong></em>";
$transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 587);
$transport->setUsername('***ore#gmail.com');
$transport->setPassword('******');
$swift = Swift_Mailer::newInstance($transport);
$message = new Swift_Message($subject);
$message->setFrom($from);
$message->setBody($html, 'text/html');
$message->setTo($to);
$message->addPart($text, 'text/plain');
if ($recipients = $swift->send($message, $failures))
{
echo 'Message successfully sent!';
} else {
echo "There was an error:\n";
print_r($failures);
}
?>
Please tell me what to do... :(
When I run this code:
$client = new \Google_Client();
$client->setApplicationName($application_name);
$client->setClientId($client_id);
$key = file_get_contents('Google.p12');
$secret = file_get_contents('Google.json');
$cred = new \Google_Auth_AssertionCredentials(
$email_address, array(
'https://www.googleapis.com/auth/admin.directory.user',
'https://www.googleapis.com/auth/admin.directory.group'
), $key, 'notasecret', 'http://oauth.net/grant_type/jwt/1.0/bearer');
$client->setClientSecret($secret);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$token = $client->getAccessToken();
$client->setAccessToken($token);
$this->service = new \Google_Service_Directory($client);
$adminOptParams = array('domain' => 'mydomain.it');
$results = $this->service->users->listUsers($adminOptParams);
foreach ($results as $item) {
print_r($item);
}
I get this error:
[Google_Service_Exception]
Error calling GET https://www.googleapis.com/admin/directory/v1/users?domai
n=mydomain.it: (403) Access Not Configured. Please use Google Developers C
onsole to activate the API for your project.
Note that in Google app admin console I already done:
client_id --> approved api --> https://www.googleapis.com/auth/admin.directory.group
https://www.googleapis.com/auth/admin.directory.orgunit
https://www.googleapis.com/auth/admin.directory.user
Enable API SDK in api lists for using with App.
I am attempting to gain three-legged Oauth access, but I can't get the first step to work. My code so far:
include("OAuth.php");
$consumer_key = "anonymous";
$consumer_secret = "anonymous";
define("URI", "http://www.google.com");
$request_token_url = URI.'/accounts/OAuthGetRequestToken?scope=https%3A%2F%2Fwww.google.com%2Fh9%2Ffeeds%2F';
$parsed = parse_url($request_token_url);
$params = array();
$oauth_consumer = new OAuthConsumer($consumer_key, $consumer_secret, NULL);
$req_req = OAuthRequest::from_consumer_and_token($oauth_consumer, NULL, "GET", $request_token_url, $params);
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$req_req->sign_request($sig_method, $oauth_consumer, NULL);
$request = $req_req->to_url();
$session = curl_init($request);
curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
// Make the request
$response = curl_exec($session);
//Error Handling:
// there is an error while executing the request,
if (!$response) {
$response = curl_error($curl);
}
curl_close($session);
parse_str($response, $params);
$oauth_token = $params['oauth_token'];
$oauth_token_secret = $params['oauth_token_secret'];
$_SESSION['CONSUMER_KEY'] = $consumer_key;
$_SESSION['CONSUMER_SECRET'] = $consumer_secret;
$_SESSION['REQUEST_TOKEN'] = $oauth_token;
$_SESSION['REQUEST_TOKEN_SECRET'] = $oauth_token_secret;
print_r($_SESSION);
I'm using OAuth.php.
The returning array does not give me anything:
Array (
[CONSUMER_KEY] => googlecodesamples.com
[CONSUMER_SECRET] => [REQUEST_TOKEN] => [REQUEST_TOKEN_SECRET] =>
)
I found this on the Google Oauth Reference
If your application is not registered, select HMAC-SHA1 and use the following key and secret:
consumer key: "anonymous" consumer
secret: "anonymous"
I have altered the consumer_key and consumer_secret variables but the returning array remains empty.
I'm not sure what I'm doing wrong this is a basic H9 sandbox development procedure; any advice would help.
Well I have figured this one out,
When I printed the response of the curl I got a message which said:
This URL has moved here:
https://www.google.com/accounts/OAuthGetRequestToken?oauth_consumer_key=anonymous%20%20%20%20[amp;oauth_nonce]%20=%3E%20828f80d4cec64b5b6fcca5010e2aa952%20%20%20%20[amp;oauth_signature]%20=%3E%20H+WrK1WIhyFEkrHRBvjpzcVLFvs=%20%20%20%20[amp;oauth_signature_method]%20=%3E%20HMAC-SHA1%20%20%20%20[amp;oauth_timestamp]%20=%3E%201282773417%20%20%20%20[amp;oauth_version]%20=%3E%201.0%20%20%20%20[amp;scope]%20=%3E%20https://www.google.com/h9/feeds/
So once I changed the $request_token_url to this, it worked like a charm and I finally have one-leg!! two left :)