My Business
3.4K members online now
3.4K members online now
For developers who are using the Google My Business API to manage locations
Guide Me
star_border
Reply
Highlighted

List all locations - PHP

[ Edited ]
Visitor ✭ ✭ ✭
# 1
Visitor ✭ ✭ ✭

Hello,

I want to list in PHP all of the locations for the my account à https://developers.google.com/my-business/content/location-data#list_all_locations

 

I managed to list all of the locations for the my account with https://developers.google.com/oauthplayground/

 

I downloaded the Google My Business API client libraries for PHP.

 

But I don’t know how to do it. I can’t find any code information on the Internet.

 

Thank you for helping me.

2 Expert replyverified_user

Re: List all locations - PHP

Visitor ✭ ✭ ✭
# 2
Visitor ✭ ✭ ✭

Hey Sebastien,

 

You need the google APIs client library for PHP in addition to the my business client library.

This is a link to the client library for PHP.

Get the my business client library from here.

 

Hope this helps.

 

List all locations - PHP

Visitor ✭ ✭ ✭
# 3
Visitor ✭ ✭ ✭

Hi Michael,

Thanks for your answer!

But how to associate Google APIs Client Library with Google My Business API Client Library?

Thanks

Re: List all locations - PHP

[ Edited ]
Visitor ✭ ✭ ✭
# 4
Visitor ✭ ✭ ✭

You need to add the MyBusiness.php file in the zip you downloaded from here to the Google APIs Client Library, the location should be something like "google/apiclient/apiclient-services/src/Google/Service". You will see other services in that folder like Drive, AdSense, Calendar, and many others.

 

This process will be the same regardless of whether you downloaded the client library or are using composer(The preferred method). If you are not using composer I suggest you start. You can see how to install composer here.

 

List all locations - PHP

Visitor ✭ ✭ ✭
# 5
Visitor ✭ ✭ ✭

Thanks for your answer!

I downloaded Google API Client (https://github.com/google/google-api-php-client/releases/download/v2.2.1/google-api-php-client-2.2.1...) and Google My Business and now I have path ../google-api-php-client/vendor/google/apiclient-services/src/Google/Service/MyBusiness.php. Does it look good already?

 

Then, at the code level to list all of the locations for the my account ?

 

Thanks

Re: List all locations - PHP

[ Edited ]
Visitor ✭ ✭ ✭
# 6
Visitor ✭ ✭ ✭

For now, I did like this: 

require_once em_misc::getSpecifPath().'_vendors/google-api-php-client/vendor/autoload.php';
require_once em_misc::getSpecifPath().'_vendors/google-api-php-client/vendor/google/apiclient-services/src/Google/Service/MyBusiness.php';

$client = new Google_Client();
$client->addScope("https://www.googleapis.com/auth/plus.business.manage");
$client->setAuthConfig(em_misc::getSpecifPath().'_vendors/client_secret.json');
$client->setAccessType("offline");

$mybusinessService = new Google_Service_Mybusiness($client);

$accounts = $mybusinessService->accounts;

try {
$accountsList = $accounts->listAccounts()->getAccounts();

} catch (Exception $e) {
print "Caught exception: " . $e->getMessage() . "\n";
}

$locations = $mybusinessService->accounts_locations;

// For testing purposes, selects the very first account in the accounts array
$account = $accountsList[0];

// Lists all of the locations for the specified account.
try {
$locationsList = $locations->listAccountsLocations($account->name)->getLocations();
} catch (Exception $e) {
print "Caught exception: " . $e->getMessage() . "\n";
}

 

But I have an error: 

Caught exception: {
  "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": "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.",
        "domain": "global",
        "reason": "unauthorized"
      }
    ],
    "status": "UNAUTHENTICATED"
  }
}

What to add?
Thank you

 

Re: List all locations - PHP

[ Edited ]
Visitor ✭ ✭ ✭
# 7
Visitor ✭ ✭ ✭

When you are making an OAuth request you need to request and store an authorization token. Then you need to use that token to make subsequent requests, and in this case you need to set a redirect uri because google needs to grant you permission to access a specific accounts Google My Business data(unless you are using a service account). You can read more about googles Oauth application flow here.

 

For now I will just fix your code.

//This should include MyBusiness.php automatically.
require_once em_misc::getSpecifPath().'_vendors/google-api-php-client/vendor/autoload.php';
//starts session so we can store our access token
session_start();
$client = new Google_Client(); $client->addScope("https://www.googleapis.com/auth/plus.business.manage"); $client->setAuthConfig(em_misc::getSpecifPath().'_vendors/client_secret.json');
//sets the redirect to the page you are on. Make sure you have this set as a valid redirect in your google oauth credentials. $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; $client->setRedirectUri($redirect_uri); $client->setAccessType("offline"); $client->setIncludeGrantedScopes(true);
//checks for code variable URL parameters. Then logs our token. if (!isset($_GET['code'])) { $auth_url = $client->createAuthUrl(); header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); } else { $client->authenticate($_Get['code']); $_SESSION['access_token'] = $client->getAccessToken();
$logger = new Monolog\Logger;

  $tokenCallback = function ($cacheKey, $accessToken) use ($logger) {
    $logger->debug(sprintf('new access token received at cache key %s', $cacheKey));
  }; //sets our callback token to be refreshed automatically. $client->setTokenCallback($tokenCallback); $mybusinessService = new Google_Service_Mybusiness($client); $accounts = $mybusinessService->accounts; try { $accountsList = $accounts->listAccounts()->getAccounts(); } catch (Exception $e) { print "Caught exception: " . $e->getMessage() . "\n"; } $locations = $mybusinessService->accounts_locations; // For testing purposes, selects the very first account in the accounts array $account = $accountsList[0]; // Lists all of the locations for the specified account. try { $locationsList = $locations->listAccountsLocations($account->name)->getLocations(); } catch (Exception $e) { print "Caught exception: " . $e->getMessage() . "\n"; }

This is all assuming you have valid credentials in you client_secrets.json file and that is a valid path.

FYI I did not test this hopefully it is good.

 

 

 

List all locations - PHP

Visitor ✭ ✭ ✭
# 8
Visitor ✭ ✭ ✭

Thank you.
It does not work.
I do not know if it matters, but I want to use it for a cron job.

Re: List all locations - PHP

[ Edited ]
Visitor ✭ ✭ ✭
# 9
Visitor ✭ ✭ ✭

You may need to tweak that code a bit to fit you, but I just ran something similar and it seems to be fine. Make sure your OAuth credentials are setup correctly, and you have listed your url as a valid redirect url in your credentials.

 

If you are going to setup a cron job then you probably need to use a service account and impersonate someones email who is a manager of your GMB account, so you are not required to grant permission every time your server wants to make a new request.

 

Good luck!

Re: List all locations - PHP

Visitor ✭ ✭ ✭
# 10
Visitor ✭ ✭ ✭

I try with Service Account, I have this code now :

        require_once em_misc::getSpecifPath().'_vendors/google-api-php-client/vendor/autoload.php';
        require_once em_misc::getSpecifPath().'_vendors/google-api-php-client/vendor/google/apiclient-services/src/Google/Service/MyBusiness.php';

        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope('https://www.googleapis.com/auth/plus.business.manage');
        $client->setSubject('my@email.fr');
        $client->setAuthConfig(em_misc::getSpecifPath().'_vendors/GM-API.json');
...

But I have this error "Client is unauthorized to retrieve access tokens using this method".