1. Introduction
In this codelab, you'll learn some basics of working with the Content API for Shopping and the AdWords API and build an application that uses both. In particular, you'll build a command-line application that will create and link an AdWords account and a Merchant Center account.
What you'll learn
- How to create AdWords accounts managed by a manager account.
- How to create Merchant Center accounts managed by a multi-client account.
- How to request a link from a Merchant Center account to an AdWords account.
- How to accept a pending Merchant Center link in an AdWords account.
What you'll need
- An AdWords manager account
- A Merchant Center multi-client account
- Java 7+
- Maven
- The sample code
- A text editor (an IDE that understands Maven projects like Eclipse or IntelliJ is recommended)
2. Getting set up
Download the code
Click the following link to download all the code for this codelab:
Unpack the downloaded zip file. This will unpack a root folder (shopping-account-linking-master
), which contains a Maven project along with all of the resources you will need. The following subdirectories are of particular note:
src/main/java
is the source root of the Maven project and contains a code skeleton for you to work in.src/main/java/solution
contains the finished solution.
Install required packages and build
If you're using a Maven-aware IDE like Eclipse or IntelliJ, you can import the extracted folder as a Maven project and then compile the project normally.
If you're using Maven from the command line, you can run the following command to retrieve the necessary packages and compile the project from the root folder of the unpacked project (shopping-account-linking-master
):
mvn compile
3. Set up authentication
For this step, we won't be doing any coding, but setting up files that contain appropriate authentication tokens for the AdWords API and Content API for Shopping.
Set up AdWords API authentication
This codelab uses the same credential loading as the client library, so if you've already used the Google Ads APIs Client Library for Java with your manager account, then you should already be set up. Otherwise, follow steps 1-3 for getting started with the Google Ads APIs Client Library for Java.
Set up Content API authentication
If you don't already have a service account key:
- Go to the Merchant Center for your multi-client account and select Content API from the overflow menu:
- Select Authentication, then click the blue + button:
- After accepting the Google Cloud Platform and Google APIs Terms of Service, your browser will automatically download a JSON file containing your new service account key.
Now follow the directions for setting up authentication for the Shopping samples with a service account. That is, a copy of your service account key should be located at the following path from your home directory: shopping-samples/content/service-account.json
. You do not need to set up the samples configuration, unless you're interested in trying out the samples after finishing this codelab!
Test it out
Now that you have authentication tokens in the right places, try running the samples. If you're using Maven at the command line run the following commands:
mvn compile
mvn exec:java -Dexec.mainClass="SolutionRunner"
If you get an error message about session objects not being provided, then your authentication tokens are in place and working correctly! Otherwise, the error message you get should let you know which credentials failed to work and which file to fix.
4. Connect to the APIs
Now that you have valid authentication tokens for the two APIs we'll be using, let's get started on filling out the actual code. We'll start with creating session objects using our authentication tokens. In later steps, we'll access the various services and methods that each API provides using these session objects.
Create a Content API session object
To create a Content API session, we'll construct a ShoppingContent.Builder
object, and then use it to build the appropriate ShoppingContent
object. Luckily, all we need to construct the former is already available in the code skeleton, so we just need to pull it together like so:
SolutionRunner.java
// TODO(sessions): Create a ShoppingContent object using ShoppingContent.Builder.
contentApiSession =
new ShoppingContent.Builder(httpTransport, jsonFactory, contentApiCredential)
.setApplicationName("Linking AdWords and Merchant Center Accounts Codelab")
.build();
Setting an application name isn't strictly necessary, but it shows how to set any desired options via the ShoppingContent.Builder
object before calling the build()
method.
Create an AdWords API session object
Similarly, there is an AdWordsSession.Builder
class for building AdWordsSession
objects. The main difference here is that instead of setting configuration options directly on the builder, we'll use the fromFile()
method to load them from the ads.properties
file we set up in the previous step.
SolutionRunner.java
// TODO(sessions): Create a AdWordsSession object using AdWordsSession.Builder.
adWordsSession =
new AdWordsSession.Builder()
.fromFile()
.withOAuth2Credential(adwordsOAuth2Credential)
.build();
Test it out
We'll use the same commands as in the last section to rebuild and run the Maven project, if you're running it from the command line:
mvn compile
mvn exec:java -Dexec.mainClass="SolutionRunner"
This time, you should get no errors at all, though you also won't get any interesting output. We'll add that when we call the APIs to create and link the new accounts.
5. Create a new managed AdWords account
Now that we've created our API session objects, we'll go through and create the accounts we want to link. We'll start with AdWords and create a test account under our manager account.
Access the ManagedCustomerService
In the AdWords API, we access the various available services by first retrieving an instance of the AdWordsServices class using the static getInstance()
method. Using this instance, we can then create clients for those services via the get()
method, which takes two arguments: the session for which to create the client and the interface for the desired service.
SolutionRunner.java
// TODO(newAWaccount): Using the ManagedCustomerService, create a new testing AdWords account
// under the given manager account.
AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();
ManagedCustomerServiceInterface managedCustomerService =
adWordsServices.get(adWordsSession, ManagedCustomerServiceInterface.class);
Here, we access the ManagedCustomerService, which allows us to manage AdWords "customers" (accounts) from a given manager account.
Specify the new account settings
First, we'll create a ManagedCustomer object that contains the settings for our new account. We'll create a test account for this codelab, setting its currency to USD and its time zone to the same as the US west coast.
SolutionRunner.java
Random rand = new Random();
long run = rand.nextLong();
ManagedCustomer newAdWordsAccount = new ManagedCustomer();
newAdWordsAccount.setName(String.format("AdWords Account Created by Run %d", run));
newAdWordsAccount.setTestAccount(true);
newAdWordsAccount.setCurrencyCode("USD");
newAdWordsAccount.setDateTimeZone("America/Los_Angeles");
We also create a random number which we include in the name of the account. This is just so we can match the AdWords account we'll create here with the Merchant Center account we'll create later, so we can visually inspect them once our solution is complete and make sure that it did indeed link the two.
Create the new managed account
To actually create the new account, we'll use ManagedCustomerOperation to specify an ADD
operation:
SolutionRunner.java
ManagedCustomerOperation operation = new ManagedCustomerOperation();
operation.setOperand(newAdWordsAccount);
operation.setOperator(Operator.ADD);
Then we'll perform the operation using the mutate()
method of the ManagedCustomerService
object. This method takes an array of operations to perform, but here we only want to perform a single operation. The result of the mutate()
method is a value containing a list of ManagedCustomer
s; here, it'll be a list containing one customer, the new account we created. We'll retrieve the ID for that new account for future use, and we'll also print it so we can see it as part of the output of our solution.
SolutionRunner.java
ManagedCustomerReturnValue result =
managedCustomerService.mutate(new ManagedCustomerOperation[] {operation});
Long adWordsId = result.getValue()[0].getCustomerId();
System.out.printf("Created new AdWords account %d%n", adWordsId);
Test it out
As before, try running the solution. If you're using Maven from the command line:
mvn compile
mvn exec:java -Dexec.mainClass="SolutionRunner"
If all goes well, you should still see no errors, and this time we'll see the ID of the new AdWords account we created. Check the AdWords site for your manager account and you should see the new account listed there as well!
6. Create a new Merchant Center sub-account
In this step, we'll create the Merchant Center sub-account that we'll link to the AdWords account we created in the last step. Instead of separately requesting a link after creating the sub-account, we can request the link during creation since we already have the ID for the corresponding AdWords account.
Specify the settings for the new sub-account
Unlike the AdWords API, the setters for the Account
model class return the object, so we can chain our calls to them on the new Account
object. We'll use the random number we generated during the AdWords account creation in the name of the new Merchant Center account as well.
SolutionRunner.java
Account newMcAccount = new Account()
.setName(String.format("Merchant Center Account Created by Run %d", run))
.setAdwordsLinks(
ImmutableList.of(
new AccountAdwordsLink()
.setAdwordsId(BigInteger.valueOf(adWordsId))
.setStatus("active")));
As mentioned in the introduction for this step, since we already have the AdWords ID for the new managed account, we can add that ID to the list of AdwordsLinks
for the new sub-account now. When the new sub-account is created, this link will be automatically requested and available in the AdWords API.
Create the new sub-account
In the Content API, we call the accounts()
method of the session object to access the Accounts
service, and then call the insert()
method directly instead of setting up an operation object. This method takes two arguments: the ID of the multi-client account under which to create the new sub-account, and the Account
object that contains the desired settings:
SolutionRunner.java
newMcAccount = contentApiSession.accounts().insert(mcaId, newMcAccount).execute();
System.out.printf("Created new Merchant Center account %s%n", newMcAccount.getId());
The insert()
method returns an Account
object that contains the settings for the new sub-account. We overwrite our original Account
object because the returned version includes an important piece of information: the new sub-account's ID. We print that in the output from our solution, so we can run our solution and then verify the new sub-account exists in the Merchant Center.
Test it out
As before, try running the solution. If you're using Maven from the command line:
mvn compile
mvn exec:java -Dexec.mainClass="SolutionRunner"
If all goes well, you should still see no errors, and this time we'll see the IDs for both the new AdWords account and the new Merchant Center account. Check the Merchant Center for your multi-client account to see the new sub-account there.
7. Accept the link from the AdWords account
In the last step, we created a new Merchant Center sub-account, requesting the link to our new AdWords account at the same time. In this step, we'll finish the process by using the AdWords API to accept the requested link.
Access the CustomerService
Like before, we'll use the AdWordsServices
class to get a client for the CustomerService
. However, before we create the client, we first change our AdWords session object so that future uses will operate on the new managed account instead of the manager account. After all, the Merchant Center account requested a link to the managed account, not the manager account.
SolutionRunner.java
// TODO(acceptLink): Using the mutateServiceLinks method in CustomerService, accept the
// proposed link between the new AdWords account and the new Merchant Center account.
adWordsSession.setClientCustomerId(adWordsId.toString());
CustomerServiceInterface customerService =
adWordsServices.get(adWordsSession, CustomerServiceInterface.class);
Specify the requested link
Like when we created a new AdWords account, we'll create a ServiceLink
object that contains the link settings, and then a ServiceLinkOperation
object that describes the desired operation. Here, we want to take the pending service link to a MERCHANT_CENTER
account and SET
it to ACTIVE
. For the serviceLinkId
setting, we'll use the ID of the Merchant Center account we just created, as that is used for the ID of the service link in AdWords.
SolutionRunner.java
ServiceLink serviceLink = new ServiceLink();
serviceLink.setServiceLinkId(newMcAccount.getId().longValue());
serviceLink.setLinkStatus(ServiceLinkLinkStatus.ACTIVE);
serviceLink.setServiceType(ServiceType.MERCHANT_CENTER);
ServiceLinkOperation op = new ServiceLinkOperation();
op.setOperator(Operator.SET);
op.setOperand(serviceLink);
Accept the link
Finally, we'll call the mutateServiceLinks()
method of the CustomerService object to perform the operation. As before, it takes an array of service link operations. This time, the method returns a list of (possibly changed) service links directly, so we'll just print out the result of our solution by looping over that list. Of course, since we only specified a single operation, you only expect a single link to be printed out in the output.
SolutionRunner.java
ServiceLink[] mutatedServiceLinks =
customerService.mutateServiceLinks(new ServiceLinkOperation[] {op});
for (ServiceLink mutatedServiceLink : mutatedServiceLinks) {
System.out.printf(
"Service link with service link ID %d, type '%s' updated to status: %s.%n",
mutatedServiceLink.getServiceLinkId(),
mutatedServiceLink.getServiceType(),
mutatedServiceLink.getLinkStatus());
}
Test it out
As before, try running the solution. If you're using Maven from the command line:
mvn compile
mvn exec:java -Dexec.mainClass="SolutionRunner"
If all goes well, you should still see no errors, and this time we'll also see a note that the service link was updated to be active. Check AdWords and the Merchant Center and double-check that the accounts are indeed now linked.
8. Variations on a theme
Congratulations on making it through the codelab! Now that you have a fully working solution, let's look at some examples of how you might modify or extend it to use more of the APIs you've seen in this codelab.
Extra credit: Update an existing Merchant Center account to request an AdWords link
In the codelab, we cleverly created the AdWords account first so that we could use its information to request the link when creating the Merchant Center account. However, if the Merchant Center account already exists, then you'll need to update its configuration instead. Try altering your code to create the Merchant Center account first, and then go back after creating the AdWords account and update its configuration to request the link.
Extra credit: Verify the link creation by retrieving the AdWords and Merchant Center account information
Currently, the application only treats the absence of errors from API calls as a sign of success. Try extending the example to check the link information for the new Merchant Center and Adwords accounts and see that the link is indeed active.
The world's your oyster
If you think of other changes you could make, give them a try! If you need reference code for your ideas, check out the Google Shopping samples and the examples
directory in the Google Ads Java client library source.