Im trying to post some activity to a users profile in their google+.
i have been searching all the post about moments problem but still i cant solve my problem. below are my codes
$requestVisibleActions = array(
'http://schemas.google.com/AddActivity');
$client = new Google_Client();
$client->setApplicationName("PHP Google OAuth Login Example");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($simple_api_key);
$client->addScope("https://www.googleapis.com/auth/plus.login");
$client->addScope("https://www.googleapis.com/auth/plus.me");
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$client->setRequestVisibleActions($requestVisibleActions);
$plus = new Google_Service_Plus($client);
// Add Access Token to Session
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
// Set Access Token to make Request
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
}
// Post moment from mysite
if ($client->getAccessToken()) {
$moment = new Google_Service_Plus_Moment();
$moment->setType('http://schemas.google.com/AddActivity');
$itemScope = new Google_Service_Plus_ItemScope();
$itemScope->setUrl('http://developers.google.com/+/web/snippet/examples/thing');
$moment->setTarget($itemScope);
$momentResult = $plus->moments->insert('me', 'vault',$moment);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
redirect($authUrl);
}
but i get a google exception error
Type: Google_Service_Exception
Message: Error calling POST
https://www.googleapis.com/plus/v1/people/me/moments/vault?key=xxxxxxx:
(400) Unable to fetch metadata.
Filename: /home2/mysite/public_html/application/libraries/google-api-php-client-master/src/Google/Http/REST.php
When i try to access the post url i get this.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
i realy dont know where im wrong. please help me
Moments: insert Record a moment representing a user's action such as making a purchase or commenting on a blog. Writing moments involves specifying the type, which is a moment type, and posting that type of moment's required fields.
Moments describe activities that users engage within your app.
Momemt types is the same as App Activity Types they are:
AddAction
,BuyAction,CheckInAction,CommentAction,CreateAction,DiscoverAction,ListenAction,ReserveAction,ReviewAction,WantAction
A moment is NOT posting to a users Google+ stream. It is NOT possible to post some activity to a users profile in their Google+.
Related
I try to use the YouTube API, but when I wish to use the LiveBroadcasts.list API.
When I use the same JSON key to list my playlist it's OK... I don't understand why.
$client = new \Google_Client();
$client->setAuthConfig(__DIR__ . '/../../key/youtube_client.json');
$client->setApplicationName('Broadcast');
$client->setScopes([
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/youtube.upload',
'https://www.googleapis.com/auth/youtube.readonly'
]);
$service = new \Google_Service_YouTube($client);
$broadcastsResponse = $service->liveBroadcasts->listLiveBroadcasts(
'id,snippet,contentDetails',
array(
'broadcastType' => 'persistent',
'mine' => 'true',
)
);
The error message is:
{ "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED" } }
Can someone help me to know where is my mistake?
You appear to be missing a lot of the authorization code that is required in order to fetch an access token.
<?php
/**
* Sample PHP code for youtube.liveBroadcasts.list
* See instructions for running these code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#php
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
}
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName('API code samples');
$client->setScopes([
'https://www.googleapis.com/auth/youtube.readonly',
]);
// TODO: For this request to work, you must replace
// "YOUR_CLIENT_SECRET_FILE.json" with a pointer to your
// client_secret.json file. For more information, see
// https://cloud.google.com/iam/docs/creating-managing-service-account-keys
$client->setAuthConfig('YOUR_CLIENT_SECRET_FILE.json');
$client->setAccessType('offline');
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open this link in your browser:\n%s\n", $authUrl);
print('Enter verification code: ');
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
$response = $service->liveBroadcasts->listLiveBroadcasts('');
print_r($response);
This sample is going to end up running more as a console application as it just builds the url for you. If you need it run as a web application let me know i have some other sampes just not for this API which you can find here. If you need help altering it let me know.
I wish to develop one restful app where users will upload video to youtube via some admin interface. Since users will only upload on behalf of my name and in one channel I want to make authentication only once and then use refresh token to get access token.
So what I did is the following
I have visited https://developers.google.com and select and authorize all Youtube data API v3 API's with my email
Exchange authorization code for tokens (so now I have Authorization code, refresh and access token)
Code implementation (stuck here, can't imagine huh?)
$client = new Google_Client();
$client->setApplicationName('myApp');
$client->setClientId('<client-id>');
$client->setClientSecret('<client-secret>');
$client->setDeveloperKey('<dev-key>'); // <- do I really need that
$client->setScopes('https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/youtubepartner https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtubepartner-channel-audit https://www.googleapis.com/auth/youtube.readonly');
$client->refreshToken('<my-refresh-token>');
$client->setAuthConfig('client_secrets.json'); // <- is that the same as setting clientId and ClientSecret???
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$accessToken = $client->getAccessToken();
if (is_null($accessToken) || $client->isAccessTokenExpired()) {
// How to refresh token with REFRESH token?
dd($_GET);
}
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
// Define the $video object, which will be uploaded as the request body.
$video = new Google_Service_YouTube_Video();
// Add 'snippet' object to the $video object.
$videoSnippet = new Google_Service_YouTube_VideoSnippet();
$videoSnippet->setCategoryId('1');
$videoSnippet->setChannelId('<my-channel-id>');
$videoSnippet->setDescription('Description of uploaded video.');
$videoSnippet->setTags(['tag', 'tag2', 'tag3']);
$videoSnippet->setTitle('Test video upload.');
$video->setSnippet($videoSnippet);
// Add 'status' object to the $video object.
$videoStatus = new Google_Service_YouTube_VideoStatus();
$videoStatus->setEmbeddable(true);
$videoStatus->setLicense('youtube');
$videoStatus->setPrivacyStatus('private');
$video->setStatus($videoStatus);
$queryParams = [
'stabilize' => false
];
// TODO: For this request to work, you must replace "YOUR_FILE"
// with a pointer to the actual file you are uploading.
// The maximum file size for this operation is 64GB.
$response = $service->videos->insert(
'snippet,status',
$video,
$queryParams,
array(
'data' => file_get_contents($fullFilePath),
'mimeType' => 'video/*',
'uploadType' => 'multipart'
)
);
print_r($response);
So now I have several problems, which I don't know how to tackle.
Which $client->.... functions must be present if I'm already authorized (via OAuth playground)
How to refresh token with refresh token?
So far the only response I get is Google_Service_Exception
Message: { "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } }
It's my second day of trying to upload video via api with PHP and it's driving me nuts. I hope you guys will help me out.
If you need any additional informations, please let me know and I will provide. Thank you!!
UPDATE
After adding following code
$client->setAccessToken('<ACCESS_TOKEN>');
I get following errors
div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
<h4>An uncaught Exception was encountered</h4>
<p>Type: Google_Service_Exception</p>
<p>Message: {
"error": {
"errors": [
{
"domain": "youtube.quota",
"reason": "quotaExceeded",
"message": "The request cannot be completed because you have exceeded your \u003ca href=\"/youtube/v3/getting-started#quota\"\u003equota\u003c/a\u003e."
}
],
"code": 403,
"message": "The request cannot be completed because you have exceeded your \u003ca href=\"/youtube/v3/getting-started#quota\"\u003equota\u003c/a\u003e."
}
}
</p>
<p>Filename: /home/vagrant/workspace/spot-scouting-adminpage/rest/vendor/google/apiclient/src/Google/Http/REST.php</p>
<p>Line Number: 118</p>
Which is of course not true, since I have never made a single successful request to google. Here is prof:
Maybe the problem is that a have generated access key via developers.google.com???
You have missed just a small step to set access token.
Once you get the access token set it with google client :
$client->setAccessToken($accessToken);
And then use youtube service:
$service = new Google_Service_YouTube($client);
I have selected Application type "other and web application" while creating separate projects in Youtube developer console and using following code.
$scope = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube');
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setAccessToken('ya29.GlyKBK9LdtYRLNDYUdhXlhTiY_d51nLUZrIdikYoRY3M_5YQOpt5Pkx-uJ1RYpsvPOKyf4hTNBhKwOJ_fEncTURyNBeZa9ISRoVAmcuFaAlI_YgcQAs97GCbHklvXg');
$client->setScopes($scope);
$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]);
}
But it always give following error.
A service error occurred: { "error": { "errors": [ { "domain":
"global", "reason": "authError", "message": "Invalid Credentials",
"locationType": "header", "location": "Authorization" } ], "code":
401, "message": "Invalid Credentials" } }
I am not getting what I am doing wrong and what could be the possible fix for this?
I'm trying to create php script that post article to Blogger using Google API. I'm using library google/apiclient:^2.0. I'm choosing to use service account keys. Here's my codes:
require_once '../../vendor/autoload.php';
try {
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/../../credentials/BeMine92929929.json');
$client = new Google_Client();
$client->setApplicationName('Be Mine');
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Blogger::BLOGGER);
$token = $client->fetchAccessTokenWithAssertion();
$client->setAccessToken($token);
// I dump $token here, and it's available. token generation is success.
$service = new Google_Service_Blogger($client);
$blog = $service->blogs->getByUrl('http://bemine.blogspot.com');
//this is part for sending post into blogger, which is getting
//error
$post = new Google_Service_Blogger_Post();
$post->setTitle('Coba Post Artikel Kedua');
$post->setContent('Artikel kedua ini dikirim melalui layanan Blogger api.');
$service->posts->insert('Here Is My Blog ID', $post);
//If I comment posting part, and try to get list article of
//my blog, It success.
$posts = $service->posts->listPosts($blog->getId());
//file_put_contents('/tmp/anarky.txt', var_export($posts, true));
} catch (\Exception $ex) {
echo $ex->getMessage();
}
The response when I try to post article :
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "We're sorry, but you don't have permission to access this resource."
}
],
"code": 403,
"message": "We're sorry, but you don't have permission to access this resource."
}
}
What do I miss Need your advise, thank you.
I have got the code for analytics to work so that it manages to query Google Analytics and brings back results however when I try to use the code to query webmaster tools it comes back with Insufficient Permissions.
Google Enabled API's are : Analytics API, Google Search Console API
Is there something I am missing?
Google Analytics Code:
$client = new Google_Client();
$client->setAuthConfigFile($SECRET);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); //For analytics stuff
$client->setAccessType('offline');
$client->setPrompt('prompt');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
//Checking to see if the token is expired
if($client->isAccessTokenExpired()){
$client->refreshToken($refreshToken);
$_SESSION['access_token'] = $client->getAccessToken();
}
$results = $analytics->data_ga->get(
$viewID,
$fromDate,
$toDate,
$metrics,
$optParams);
foreach($results->rows as $data){
echo "<pre>",print_r($data),"</pre>";
}
}else {
$redirect_uri = $redirectURL;
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Webmaster Tools Code:
$client = new Google_Client();
$client->setAuthConfigFile($SECRET);
$client->addScope(Google_Service_Webmasters::WEBMASTERS_READONLY); //For WebMaster Tools
$client->setAccessType('offline');
$client->setPrompt('prompt');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
//Checking to see if the token is expired
if($client->isAccessTokenExpired()){
$client->refreshToken($refreshToken);
$_SESSION['access_token'] = $client->getAccessToken();
}
//Creating Webmaster Service
$webmastersService = new Google_Service_Webmasters($client);
$searchanalytics = $webmastersService->searchanalytics;
//Creating Request
$request = new Google_Service_Webmasters_SearchAnalyticsQueryRequest();
$request->setStartDate('2016-05-01');
$request->setEndDate('2016-05-31');
$request->setDimensions( array('query') );
$qsearch = $searchanalytics->query("http://www.example.co.uk", $request);
$rows = $qsearch->getRows();
echo "<pre>",print_r($rows),"</pre>";
} else {
$redirect_uri = $redirectURL;
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Webmaster Tools Error Message :
{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
When you run the first one you ask the user can I access your Google Analytics data the user says yes you can and you get a access token that can be used to access their google analytics data.
In the second one you ask the user can I access your webmaster tools data the user says yes you get an access token to access their web mater tools data.
If you where to put both of the scopes in instead of just one the user would be asked can I access your google analytics data and your web master tools data. If they say yes you get an access token to access them both.
If you try and use authentication from a analytics Auth request to access web master tools you will get a Insufficient permissions.
If you need access to both then request access to both. If you first want one then maybe later want the other one then yes you will have to ask them for the other one later.