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.
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'm having issues accessing Google Sheets through PHP in WordPress (WP). I've accessed the same sheet before in a local python program and I recall that once the code first ran the google authorization window popped up asking for approval. This WP shortcode isn't getting to that point and instead outputs an error message to the WP page stating a valid API Key is missing. What am I missing here?
Shortcode:
require_once __DIR__ . '/vendor/autoload.php';
function excel_tester_function() {
$client = new Google_Client();
$client->setApplicationName('Google Sheets and PHP');
$client->setAuthConfig(__DIR__ . '/credentials.json');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAccessType('online');
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
$service = new Google_Service_Sheets($client);
$spreadsheetId = '{SHEET_ID}';
$get_range = '{RANGE}';
$response = $service->spreadsheets_values->get($spreadsheetId, $get_range);
$values = $response->getValues();
foreach ($val as $values) {
print($val);
}
}
add_shortcode('excel-tester', 'excel_tester_function');
Error:
Fatal error: Uncaught Google_Service_Exception: { "error": { "code": 403, "message": "The request is missing a valid API key.", "errors": [ { "message": "The request is missing a valid API key.", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } } in...
Please advise. Let me know if there is any info I can provide that could help solve this. Thank you.
I want to change all signatures from my Gmail domain. This domain has many accounts, and I need to change it from server-side.
I'm using php, and I started my project with:
php composer.phar require google/apiclient:2.0
I wrote one code, but when I try to update one email (like teste#mydomain.com), I receive:
{ "error": { "errors": [ { "domain": "global", "reason": "insufficientPermissions", "message": "Insufficient Permission" } ], "code": 403, "message": "Insufficient Permission" } }
My code (using API client library) is something like:
<?php
// initialize gmail
function getService() {
try {
include_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$credentials_file = __DIR__ . '/credentials/gmailAPI.json';
// set the location manually. Credential server-side
$client->setAuthConfig($credentials_file);
$client->setApplicationName("GmailAPI");
$client->setScopes(['https://apps-apis.google.com/a/feeds/emailsettings/2.0/']);
$gmail = new Google_Service_Gmail($client);
return $gmail;
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
function updateSignature(&$gmail) {
try {
// Start sendAs
$signature = new Google_Service_Gmail_SendAs();
// Configure Signature
$signature->setSignature("Any HTML text here.");
// Update account and print answer
var_dump($gmail->users_settings_sendAs->update("someEmail#myDomain.com.br","someEmail#myDomain.com.br",$signature));
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
try {
$gmail = getService();
updateSignature($gmail);
} catch (Exception $e) {
echo $e->getMessage();
}
?>
My credential file (gmailAPI.json) is one service account key, and I'm using Google for Work.
I created this credential using one administrator account from this domain.
My credential file is:
{
"type": "service_account",
"project_id": "myProjectId",
"private_key_id": "myPrivateKeyid",
"private_key": "myPrivateKey",
"client_email": "gmailapi#projectid.iam.gserviceaccount.com",
"client_id": "myId",
"auth_uri": "url",
"token_uri": "url",
"auth_provider_x509_cert_url": "url",
"client_x509_cert_url": "url"
}
Edit 1
I changed the scopes as instructed, and now my scopes are:
$client->setScopes(['https://www.googleapis.com/auth/gmail.settings.basic','https://www.googleapis.com/auth/gmail.settings.sharing']);
I also added permision on Google (/AdminHome?chromeless=1#OGX:ManageOauthClients) to my service account key.
I tried API explorer and it works. When i changed the scopes, the error changed to:
{ "error": { "errors": [ { "domain": "global", "reason": "failedPrecondition", "message": "Bad Request" } ], "code": 400, "message": "Bad Request" } }
I'm using this command:
var_dump($gmail->users_settings_sendAs->update("someEmail#myDomain.com.br","someEmail#myDomain.com.br",$signature));
I tried also
var_dump($gmail->users_settings_sendAs->get("someEmail#myDomain.com.br","someEmail#myDomain.com.br"));
But I received same error.
Thank You everyone.
I tried a lot of codes, and finally found one that works.
include_once __DIR__ . '/vendor/autoload.php';
// credential file (service account)
$credentials_file = __DIR__ . '/credentials/gmailAPI.json';
putenv('GOOGLE_APPLICATION_CREDENTIALS='.$credentials_file);
// Initialize Google Client
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
// scopes to change signature
$client->setScopes(['https://www.googleapis.com/auth/gmail.settings.basic','https://www.googleapis.com/auth/gmail.settings.sharing']);
// *important* -> Probably because delegated domain-wide access.
$client->setSubject("admEmailHere#test.com");
// Initialize Gmail
$gmail = new Google_Service_Gmail($client);
// set signature
$signature = new Google_Service_Gmail_SendAs();
$signature->setSignature("HTML code here.");
// update signature
$response = $gmail->users_settings_sendAs->update("admEmailHere#test.com","admEmailHere#test.com",$signature)->setSignature();
// get signature
$response = $gmail->users_settings_sendAs->get("admEmailHere#test.com","admEmailHere#test.com")->getSignature();
echo json_encode($response);
I commented all code, and I used https://developers.google.com/api-client-library/php/auth/service-accounts to create it.
Atention -> You need to give permission on Gmail, and create server key (with domain-wide access).
I think your access token doesn't contain all scopes you want. First try in API explorer. Check what are the scopes API explorer request from you and then add those scopes to your code(place where you get permission).
https://developers.google.com/apis-explorer
hope this solves your problem
Well, the error 403 or Insufficient Permission is returned when you have not requested the proper or complete scopes you need to access the API that you are trying to use. Here is the list of scopes with description that you can use with Gmail API.
To know the scope that you are using, you can verify it with this:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=xxxxxx
Note: You need to include all the scope that you are using and make
sure you enable all the API that you use in the Developer Console.
This Delegating domain-wide authority to the service
account
might also help.
For more information, check these related SO questions:
Gmail API: Insufficient Permission
How do I get around HttpError 403 Insufficient Permission?
I'm trying to set publish permissions for gmail to a pubsub topic in google cloud.
The application where I implemented this code is running in AWS.
It's a PHP application and I'm using version 2.0.0-RC7 of the google PHP api client.
In code, I implemented the flow as described in the documentation:
Create a topic (Works)
Create a subscription (works)
Grant publish rights to gmail (here I get stuck)
The first two actions are done with the same google client instance, that is authenticated with the service account credentials.
The code:
$scopes = [
'https://www.googleapis.com/auth/pubsub',
'https://mail.google.com',
];
$pushEndpoint = 'https://some.url/google_notifications/';
$client = new Google_Client();
$client->setScopes($scopes);
$client->setAuthConfig($serviceAccountInfo);
if ($client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
}
$service = new Google_Service_Pubsub($client);
// This part works
$topicObject = new Google_Service_Pubsub_Topic();
$topicObject->setName($this->getTopicName());
$service->projects_topics->create($this->getTopicName(), $topic);
// This part also works
$push = new Google_Service_Pubsub_PushConfig();
$push->setPushEndpoint($pushEndpoint);
$subscription = new Google_Service_Pubsub_Subscription();
$subscription->setName($this->getSubscriptionName());
$subscription->setTopic($this->getTopicName());
$subscription->setPushConfig($push);
$service->projects_subscriptions->create($this->getSubscriptionName(), $subscription);
// This part gives the error
$binding = new Google_Service_Pubsub_Binding();
$binding->setRole('roles/pubsub.publisher');
$binding->setMembers(['serviceAccount:gmail-api-push#system.gserviceaccount.com']);
$policy = new Google_Service_Pubsub_Policy();
$policy->setBindings([$binding]);
$setRequest = new Google_Service_Pubsub_SetIamPolicyRequest();
$setRequest->setPolicy($policy);
try {
$result = $service->projects_topics->setIamPolicy($this->getTopicName(), $setRequest);
var_dump($result);
} catch (\Exception $e) {
echo $e->getMessage();
}
The result is always:
{
"error": {
"code": 403,
"message": "User not authorized to perform this action.",
"errors": [
{
"message": "User not authorized to perform this action.",
"domain": "global",
"reason": "forbidden"
}
],
"status": "PERMISSION_DENIED"
}
}
Can someone tell me what I'm doing wrong ?
It's really annoying to set those permissions by hand all the time.
Thanks.
To use projects.topics.setIamPolicy method your service account must have a "Pub/Sub Admin" role. You can change a role of the account by visiting "IAM & admin" page for your project: https://console.cloud.google.com/iam-admin/iam
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+.