Google Ads API OAuth2 Authentication with PHP: A Step-by-Step Guide


If you’re a developer working with the Google Ads API in PHP, you know that authentication can be a bit of a process. In this blog post, I’ll guide you through on how to use a PHP script that generates the OAuth2 refresh token for the Google Ads API, making your workflow smoother.

Prerequisites

Before we get started, make sure you have the following set up:

Getting Started

  1. Download the Google Ads PHP client library:
  2. Copy the Authentication Script:
  3. Open and Edit the Script:
    • Open the auth.php file and set the REDIRECT_URI variable to your desired redirect URI:
    • private const REDIRECT_URI = ‘INSERT_REDIRECT_URL_HERE’;
  4. Run the Script:
    • Execute the script using the following command:
    • php auth.php

Script Execution

The script will prompt you to enter the OAuth2 client ID, client secret, and any additional scopes you may need (the Google Ads API scope is included by default). Follow the on-screen instructions carefully.

  1. Visit the Authorization URL:
    • Once you’ve entered the required information, the script will generate an authorization URL. Open this URL in your web browser.
  2. Log into Google Ads:
    • Log into the Google account associated with your Google Ads.
  3. Enter State Variable:
    • Upon successful login, the URL will contain a state parameter. Enter this state variable when prompted by the script.
  4. Provide Authorization Code:
    • After entering the state variable, you’ll be prompted to enter the authorization code. This code is usually presented after successful Google Ads authorization and starts with ‘4/’.
  5. Retrieve Refresh Token:
    • The script will exchange the authorization code for a refresh token. Copy this refresh token.
  6. Update Configuration File:
    • Finally, update your google_ads_php.ini file with the obtained refresh token and other necessary information:
[GOOGLE_ADS]
developerToken = "INSERT_DEVELOPER_TOKEN_HERE"
; Optional: Specify the login customer ID used to authenticate API calls.
; loginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"

[OAUTH2]
clientId = "YOUR_OAUTH2_CLIENT_ID"
clientSecret = "YOUR_OAUTH2_CLIENT_SECRET"
refreshToken = "YOUR_REFRESH_TOKEN"

Replace the placeholder values with your actual data.

With this OAuth2 refresh token generation script, authenticating your Google Ads API requests becomes a breeze. Incorporate this into your workflow to streamline your development process and spend more time on what matters – building great applications with the Google Ads API. Happy coding!