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.

Tag:google-ads-api, google-api, google-ads-script, google-oauth

5 comments.

  1. dorian

    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
    1. Kostas

      Yeah, I figured that one out myself, fortunately. Are you aware of any way I can use a refresh token instead or to automatically refresh the access token? Because I can't manually do that every hour and the refresh token I had didn't work.

    2. dorian

      You can't used refresh tokens to access Google APIs. As mentioned, there are client libraries by Google that will refresh your access token automatically using the refresh token.

    3. Kostas

      But I'm using cURL, not a client library. Does that mean I should cURL an access token from Google each time, automatically?

    4. dorian

      That would be a possible strategy, yes.

Add a new comment.