googleapis / google-api-php-client

A PHP client library for accessing Google APIs
http://googleapis.github.io/google-api-php-client/
Apache License 2.0
9.32k stars 3.52k forks source link

User does not have sufficient permissions for this profile. #2488

Closed belchiorplan closed 10 months ago

belchiorplan commented 1 year ago

I'm using version 2.14.0, Laravel 10 and PHP 8.2 but I'm getting the error: { "error": { "code": 403, "message": "User does not have sufficient permissions for this profile.", "errors": [ { "message": "User does not have sufficient permissions for this profile.", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } }

I'm using service account authentication, I also added the service account email in the Google Analytics access properties, but I still get the permission error, here's the code:

public function index()
    {
        $client = new Google_Client();

        try {
            $jsonKey = storage_path('auth.json');
            $client->setAuthConfig($jsonKey);
        }
        catch (Google_Exception $ex) {
            abort(500, $ex);
        }

        $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

        $analytics = new Google_Service_AnalyticsReporting($client);
        $response  = $this->getReport($analytics);
        $result    = $this->getResults($response);

        dd($result);
}
public function getReport($analytics)
    {
        // I changed it to X just to not display my property ID, but in the code the ID is correct as in Analytics
        $VIEW_ID = 'ga:XXXXXX';

        $dateRange = new Google_Service_AnalyticsReporting_DateRange();
        $dateRange->setStartDate('today');
        $dateRange->setEndDate('today');

        $pageviews = new Google_Service_AnalyticsReporting_Metric();
        $pageviews->setExpression('ga:pageviews');
        $pageviews->setAlias('pageviews');
        $hour = new Google_Service_AnalyticsReporting_Dimension();
        $hour->setName('ga:hour');

        $pages = new Google_Service_AnalyticsReporting_Dimension();
        $pages->setName('ga:pagePath');

        $request = new Google_Service_AnalyticsReporting_ReportRequest();
        $request->setViewId($VIEW_ID);
        $request->setDateRanges($dateRange);
        $request->setMetrics(array($pageviews));
        $request->setDimensions(array($hour, $pages));

        $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
        $body->setReportRequests(array($request));

        return $analytics->reports->batchGet( $body );
}
public function getResults($reports) : array
    {
        $date = [];

        foreach ($reports as $report)
        {
            $header = $report->getColumnHeader();

            $dimensionHeaders = $header->getDimensions();
            $metricHeaders    = $header->getMetricHeader()->getMetricHeaderEntries();

            $rows = $report->getData()->getRows();

            foreach ($rows as $key => $row)
            {
                $dimensions = $row->getDimensions();
                $metrics    = $row->getMetrics();

                for($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++)
                {
                    if ($dimensionHeaders[$i] === 'ga:pagePath')
                    {
                        $date[$key]['pagina'] = str_replace('/atlas/2017_portal_atlas', '', $dimensions[$i]);
                    }
                    else
                    {
                        $date[$key]['hora'] = $dimensions[$i];
                    }
                }

                for ($j = 0; $j < count($metricHeaders) && $j < count($metrics); $j++)
                {
                    $metricHeaders[$j];
                    $values = $metrics[$j];

                    foreach ($values->getValues() as $key2 => $value)
                    {
                        $date[$key]['acessos'] = $values->getValues()[$key2];
                    }
                }
            }
        }

        return $date;
}
tamarz-sig commented 1 year ago

Same issue. Can anyone help pleas?

In addition, what is $VIEW_ID in GA4?

  // Replace with your view ID, for example XXXX.
  $VIEW_ID = "<REPLACE_WITH_VIEW_ID>";

property-id / STREAM ID / any other ID?

vishwarajanand commented 10 months ago

@belchiorplan it seems to be a permissions issue. Check the permissions for Account access management as well as Property access management in the UI portal. Also experiment with adding more scopes in your code, such as ANALYTICS_EDIT, ANALYTICS and ANALYTICS_READONLY, some users have seen success with that approach. defined here

@tamarz-sig pre-GA4 launch, a UA property had views, link, now after GA4 launch, it doesn't.

Views seem to be available only via Reporting APIs and Property analytics (for GA4) seems to be available via Data APIs

Hopefully it will unblock you, feel free to re-open otherwise.

namanbarkiya commented 3 months ago
import { google } from "googleapis";

export async function GET() {
  const auth = new google.auth.GoogleAuth({
    credentials: {
      client_email: process.env.GOOGLE_CLIENT_EMAIL,
      private_key: process.env.GOOGLE_PRIVATE_KEY?.replace(/\\n/g, "\n"),
    },
    scopes: ["https://www.googleapis.com/auth/analytics.readonly"],
  });

  const analytics = google.analytics("v3");
  const response = await analytics.data.ga.get({
    auth: auth,
    ids: "ga:<PROPERTY_ID>",
    "start-date": "30daysAgo",
    "end-date": "today",
    metrics: "ga:sessions,ga:pageviews,ga:users",
  });

  console.log(response.data);
  return Response.json(response.data);
}

I am facing the same issue here. I am unable to find the view ID, so instead, I am using the property ID. However, when I use this code, I get a 403 error:

errors: [
  {
    message: 'User does not have sufficient permissions for this profile.',
    domain: 'global',
    reason: 'insufficientPermissions'
  }
]
namanbarkiya commented 3 months ago

@vishwarajanand