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:
- PHP installed on your system.
- Google Ads API PHP client library installed using Composer.
Getting Started
- Download the Google Ads PHP client library:
- Clone or download the Google Ads PHP client library from the official repository.
- Copy the Authentication Script:
- Open and Edit the Script:
- Open the
auth.php
file and set theREDIRECT_URI
variable to your desired redirect URI: - private const REDIRECT_URI = ‘INSERT_REDIRECT_URL_HERE’;
- Open the
- 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.
- 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.
- Log into Google Ads:
- Log into the Google account associated with your Google Ads.
- Enter State Variable:
- Upon successful login, the URL will contain a state parameter. Enter this state variable when prompted by the script.
- 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/’.
- Retrieve Refresh Token:
- The script will exchange the authorization code for a refresh token. Copy this refresh token.
- Update Configuration File:
- Finally, update your
google_ads_php.ini
file with the obtained refresh token and other necessary information:
- Finally, update your
[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!