google-apigoogle-oauthgoogle-ads-apigoogle-ads-script

Google Ads API, PHP: "Request had invalid authentication credentials. Expected OAuth 2 access token..." Error


I'm attempting to cURL the Google Ads API with the following PHP code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://googleads.googleapis.com/v14/customers/[CUSTOMER_ID]:generateKeywordHistoricalMetrics');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'developer-token: [DEVELOPER_TOKEN',
    'login-customer-id: [LOGIN_CUSTOMER_ID]',
    'Authorization: Bearer [???????]',
    'Accept: application/json',
    'Content-Type: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"historicalMetricsOptions":{"yearMonthRange":{"start":{"month":"JUNE","year":2022},"end":{"month":"MAY","year":2023}}},"keywords":[""]}');

$response = curl_exec($ch);

curl_close($ch);

And the response is:

{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

What I believe the issue to be is on the "Authentication" field. So far, I've put the following in that field(and failed each time):

  1. OAUTH 2 Client ID
  2. OAUTH 2 Client Secret
  3. OAUTH 2 Refresh Token, that works for another Google Ads project I've made
  4. Developer token

So, I could appreciate any and all help, since I'm running out of ideas and don't know what to do.


Solution

  • You'll need to exchange your long-lived OAuth2 refresh token for an short-lived access token and use that for the Authorization header.

    The exchange is handled automatically for you when you use a client library, but can also be done with a manual HTTP request, like such:

    POST /token HTTP/1.1
    Host: oauth2.googleapis.com
    Content-Type: application/x-www-form-urlencoded
    
    client_id=<OAUTH2_CLIENT_ID>&
    client_secret=<OAUTH2_CLIENT_SECRET>&
    refresh_token=<OAUTH2_REFRESH_TOKEN>&
    grant_type=refresh_token