Search code examples
phpgoogle-apigoogle-oauthgoogle-api-php-clientgoogle-my-business-api

Request is missing required authentication credential in Google my businness for Review API


I am trying to integrate My business API to fetch all google reviews on my website, of my google location. I have looked at several answers and not being able to find what the problem is. I am facing a problem with how to get Access Token to proceed. I have passed the following which I got from the developer console after setting up the OAuth Consent steps.

'CLIENT_SECRET_PATH'=> 'client_secret_77331013078-oknip449r6oat5va0ef974d7nd7ncf1o.apps.googleusercontent.com.json'
'CREDENTIALS_PATH'=> 'credentials.json'

MY code:

$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME); 
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
$client->addScope("https://www.googleapis.com/auth/plus.business.manage");
// https://www.googleapis.com/auth/business.manage
$client->setRedirectUri($redirect_uri);
// For retrieving the refresh token
$client->setAccessType("offline");
$client->setApprovalPrompt("auto");
/************************************************
We are going to create the Google My Business API
service, and query it.
************************************************/
$mybusinessService = new Google_Service_Mybusiness($client);
$credentialsPath = CLIENT_SECRET_PATH;
if (isset($_GET['code'])) {
  // Exchange authorization code for an access token.
  $accessToken = $client->authenticate($_GET['code']);
  // Store the credentials to disk.
  if (!file_exists(dirname($credentialsPath))) {
    mkdir(dirname($credentialsPath), 0700, true);
  }
  file_put_contents($credentialsPath, $accessToken);
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
 
// Load previously authorized credentials from a file.
if (file_exists($credentialsPath)) {
  $accessToken = file_get_contents($credentialsPath);
  $client->setAccessToken($accessToken);
  // // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->refreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, $client->getAccessToken());
  }
} else {
  // Request authorization from the user.
  $authUrl = $client->createAuthUrl();
}

Full Error CODE:

Error 1: Uncaught InvalidArgumentException: Invalid token format=> Google\Client->setAccessToken(Array) #1 {main} thrown 

Error 2: {
   "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"
   }
}

What I have realized with the first Error1 is that Access token is not proper format. It gets the content from that client****.json file which is in a JSON format. How can I fix it? So that it creates an access token?

Also what else needs to be done for both the errors to get resolved? Please guide me.


Solution

  • Your error probably stems from the fact that CLIENT_SECRET_PATH should be the Path to the credentials.json file which you downloaded from Google developer console. Not just the client id.

    Make sure you created web browser credetinals.

    How your code works

    It sounds like you dont exactly understand how your code works. Heres what will happen the firs time you run it.

    its going to hit this section

    $authUrl = $client->createAuthUrl();
    

    Which will open the authorization window and maybe a google login window. Once that happends its going to reroute to your code and hit

    if (isset($_GET['code'])) {
    

    Because its going to be returning a code (authorization code) in the query parameters.

    At that point becouse

    if (!file_exists(dirname($credentialsPath))) {
    

    Doesnt exist a new file will be created for you at that time.

    The next time your code runs its going to have a file so the following will be true

    if (file_exists($credentialsPath)) {
    

    So it will use the code in the file to grab you a new access token.

    Note: as written your code will be single user.