Here are the steps that I took to get OAuth2 working. YMMV of course...
Step 1 - Register Application with Google Console API
- Log into Google using your email and password above
- Head to the Google API Console. You probably get redirected to Google Cloud Console
- Under 'APIs & Auth' click on 'Consent screen'. Fill in at least 'Product Name' and 'Email'.
- Under 'APIs & Auth' click on 'Registered apps'.
- Click 'Register App'. Fill in details ensuring that you select 'Native' as platform.
- Under 'OAuth 2.0 Client ID' make a note of the CLIENT ID and CLIENT SECRET values.
Step 2 - Generate Refresh Token
Next step is to generate a refresh token. This is a generate-once-use-multiple-times token that allows your application to obtain new access tokens:
- Download GetRefreshToken.java.
Create an
aps.properties
file to be referenced by theGoogleClientSecretsBuilder() .forApi(Api.ADWORDS)
call. Thisads.properties
file should contain two lines:api.adwords.clientId=client-id-from-step1.6
api.adwords.clientSecret=client-secret-from-step1.6
Using web browser log into the Google AdWords MCC.
- Run
GetRefreshToken.java
and follow instructions i.e. copy browser URL into browser, enter code returned into console etc. etc. - You should now have a refreshToken. Copy this refresh token into your
ads.properties
files like this:
api.adwords.refreshToken=your-refresh-token
PS GetRefreshToken.java
has a couple of dependencies. If you are using Maven then here they are (adjust versions accordingly!):
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-oauth2</artifactId>
<version>v2-rev50-1.17.0-rc</version>
</dependency>
<dependency>
<groupId>com.google.api-ads</groupId>
<artifactId>adwords-axis</artifactId>
<version>1.20.0</version>
</dependency>
Step 3 - Generate Credential
With your refreshToken, clientId & clientSecret in your ads.properties
you can now generate a Credential like this:
Credential oAuth2Credential = new OfflineCredentials.Builder()
.forApi(Api.ADWORDS)
.fromFile()
.build()
.generateCredential();
Step 4 - Get AdWords Session
The final step (hats off to you if you have got this far!) is to create an AdWords Session using the oAuth2Credential
instance of Credential
that you created in Step 3. You can do this by adding two more things into your ads.properties file:
api.adwords.developerToken=developer-token-from-mcc
api.adwords.clientCustomerId=client-id-of-adwords-account-that-you-want-to-access
Then get an AdWords session up using like this:
AdWordsSession awSession =
new AdWordsSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
Step 5 - Grab a coffee and reflect on how easy it is to access the Google AdWords API using OAuth2
This step is entirely optional.