Use OAuth 2.0 to authenticate your application so that you can access the hotel APIs.
Setting up OAuth 2.0
The OAuth 2.0 API requires that you identify yourself using a Service Account which is associated with your Google Account. The Service Account sends a private key (that you will create) in exchange for an OAuth 2.0 access token. You then pass this token in calls to the hotel APIs for read-only data, such as pricing, hotel, and diagnostic reporting data about your Hotel Price Feed.
The access token lasts for 3600 seconds (one hour).
If you previously implemented ClientLogin, the OAuth 2.0 approach is similar, with the following differences:
- Your application uses a Google Service Account to access the API.
- You pass the OAuth 2.0 access token in the
AuthorizationHTTP header when you call the APIs.
To set up your account to use OAuth 2.0 with the "Travel Hotel Ads API", perform the following general steps:
- Create a new Project in the Google Developers Console (DevConsole)
- Enable access to the "Travel Hotel Ads API" for the new Project
- Create a Service Account and its credentials
- Give your Service Account access to your hotel data
Each of these steps is described in the sections that follow.
Step 1: Create a new DevConsole Project
The Google Developers Console ("DevConsole") is Google's developer experience for managing and viewing traffic data, authentication, and billing information for the Google APIs that your projects use.
In the DevConsole, a project is a collection of settings, credentials, and metadata about the application or applications you're working on that make use of Google Developer APIs and Google Cloud resources.
The DevConsole is where you manage these aspects of your project, such as generating API credentials, activating APIs, and managing team and billing information associated with your project.
To create a new DevConsole project:
- Log in to your gMail/Google Account.
- Open the Google Developers Console. If this is your first project, the main view displays a
simple Create Project button:
Click the Create Project button. DevConsole displays the New Project dialog box:
Enter a friendly name for your new project in the Project Name input field. Below the field, the DevConsole generates a project ID for you, ensuring that the ID is unique across all projects. For example, if you enter "My New Project", DevConsole assigns an ID like "my-new-project-420".
Click the Create button to create your new project. DevConsole creates the new project and displays the Project Dashboard view for it:
As you can see in the image, the main navigation icon is in the upper left of the DevConsole. The currently-selected project is in the upper right.
When you create a new project, it has no APIs associated with it yet. In the next step, you will enable the Travel Partner API for your new Project.
Step 2: Enable the "Travel Hotel Ads API" for the new Project
To use the hotel APIs, you must enable "Travel Hotel Ads API" in your new DevConsole project.
To enable the hotel APIs for your new project:
- Open the Google Developers Console.
- Select the navigation icon and click Google API Console.
- In the search input field, start typing “Travel Hotel Ads API”. The Google API Console displays a list of APIs that match what you type:
- Click “Travel Hotel Ads API” in the table of matching APIs. DevConsole displays a description about the API.
- Click the Enable API button to enable this API for your project.
The hotel APIs are now enabled for your Google Account's new project.
The next step is to create a Service Account and generate keys for it.
Step 3: Create a Service Account and generate its credentials
Service Accounts are used by server-to-server interactions such as those between a web application and your hotel data.
To create and configure a Service Account:
- In the Google API Console main view, click Credentials in the left-hand navigation. DevConsole displays the Credentials view.
The Credentials view displays client IDs and credentials for your project. Your application will use the client ID when requesting an OAuth 2.0 access token. New projects will have no clients or credentials yet.
Click the New Credentials button, and select "Service Account Key" from the drop down:
The Create service account key view displays.
- From the “Service Account” drop down, select "New Service Account".
- Enter a Service Account Name and Service Account ID.
The Name can be anything you want, but the Account ID must be unique across all projects. DevConsole will generate a unique Account ID for you, based on the Name that you enter.
- Select P12 for the Key Type, as the following image shows:
- Click the Create button. DevConsole generates a
private/public key pair for your project. The private key is saved to the
default location that your browser stores downloads. You must download the
.p12 format (binary), as opposed to the .json file format.
You use the private key in your scripts or other applications that access the Travel Partner API.
DevConsole displays the following notice when it finishes generating the keys:
- Click the OK, got it button. DevConsole returns you to the
Credentials view. To confirm the details about your Service
Account and see the Service Accounts associated with your project, click
"Manage service accounts" in this view.
The Service Account now has the following credentials associated with it:
- Client ID: A unique identifier that your application uses when requesting an OAuth 2.0 access token.
- Email address: A generated email address for the Service Account, in the form "account_name@project_name.google.com.iam.gserviceaccount.com".
- Certificate fingerprints: The ID of the private key that you downloaded.
Step 4: Give the Service Account access to your hotel data
The final step is to provide the new Service Account with access to your Hotel Ads data. The Service Account is identified by the generated email address that you created in the previous step. You provide access to this account by using the Hotel Ads Center's sharing settings.
To give a Service Account access to your Hotel Ads data:
- In a new browser window, open the Hotel Ads Center.
- Click the Share this account icon on your Hotel Ads Center
Hotel Ads Center displays the Share Settings dialog box.
In the Invite people field, enter the Service Account’s email address that DevConsole generated in
Step 3: Create a Service Account and generate its credentials ("account_name@project_name.google.com.iam.gserviceaccount.com").
Keep the Notify people via email option selected and the Can edit permission selected, as the following example shows:
Click the Send button.
- After adding the Service Account to your Hotel Ads Center account, your Service Account’s email address will be enabled for API access within about 24 hours.
After Google notifies you that API access is enabled for your Service Account, you can start accessing the API with OAuth 2.0, as described in Using OAuth 2.0.
Using OAuth 2.0
To access the API, your application must identify itself to Google with the
Service Account's generated email address and private key. Google's authentication
mechanism exchanges this key for an OAuth 2.0 access token that you pass in the
Authorization header in your app's API calls.
Access tokens (also known as bearer tokens) are part of the OAuth 2.0 standard. The syntax for specifying an access token in an HTTP header is:
Authorization: Bearer oauth2_access_token
The following example shows sample HTTP headers of a request that accesses the Reports API:
GET /travelpartner/v2.0/42000042/reports/top_opportunity_7_day HTTP/1.1 Host: www.googleapis.com Authorization: Bearer nd42.fdLSKkljD98344444444444lSDF42fdLSKkljD98344444444444lSDF42 Cache-Control: no-cache
To generate an access token, create an application in any language you choose.
The following example generates the token in Python. You can then use this
token in your requests'
Authorization headers when accessing the Travel Partner API.
The access token is good for 1 hour.
#!/usr/bin/python2.7 # # Copyright 2016 Google Inc. All Rights Reserved. # """ Sample code to get an auth header that you can use in your HTTP requests 1. Please see https://developers.google.com/api-client-library/python/start/installation to download and install the google-api-python-client package. 2. Edit lines below marked _SERVICE_ACCOUNT, _KEY_FILE, _PARTNER_NAME, and _API_VERSION. 3. Run the program using: "python sample.py". The app returns the value that you use for the Authorization header's Bearer token in your request. 4. Copy the token and use it in requests to the Travel Partner API. For example (2.0): https://www.googleapis.com/travelpartner/2.0/42000042/reports/budget For example (1.x): https://www.googleapis.com/travelpartner/1.2/reports?report_type=BUDGET """ import httplib2 import json import os import sys import urllib HAS_CRYPTO = False from apiclient import discovery from oauth2client.client import flow_from_clientsecrets try: # Some systems may not have OpenSSL installed so can't use SignedJwtAssertionCredentials. from oauth2client.client import SignedJwtAssertionCredentials HAS_CRYPTO = True except ImportError: print "Unable to import SignedJwtAssertionCredentials" from oauth2client import tools from oauth2client.file import Storage # Authorization scope for our requests (do not change) _DEFAULT_APISCOPE = 'https://www.googleapis.com/auth/travelpartner' # Use the service account you set up in the Google Developers Platform. # It will be of the form "gsaccount_name@project_name.google.com.iam.gserviceaccount.com". _SERVICE_ACCOUNT = ('email@example.com') # Set this to the full path to your service account's private binary .p12 key file # that you downloaded from the Google Developer's Console and stored in a secure place. # DO NOT use the json version of the certificate. _KEY_FILE = '../mylocaldir/api-keys/8482bb2bdb08.p12' # Set this to the case-sensitive "TECHNCIAL" partner account name, NOT the account # name in the Hotel Ads Center or the numeric partner ID. # Check with your TAM if you do not know your technical partner account name. _PARTNER_NAME = 'testpartner2' class HotelAdsAPIConnection(object): def __init__(self, service_account=_SERVICE_ACCOUNT, key=_KEY_FILE, partner=_PARTNER_NAME): self.key_file = key self.account = service_account self.partner = partner def InitializeCredentials(self, scope): '''Get credentials for use in API requests. Generates service account credentials if the key file is present, and regular user credentials if the file is not found. ''' if os.path.exists(self.key_file): if not HAS_CRYPTO: raise Exception("Unable to use cryptographic functions " + "Try installing OpenSSL") with open (self.key_file, 'rb') as file: key = file.read(); creds = SignedJwtAssertionCredentials(self.account, key, scope) self.credentials = creds def authorize(self): '''Construct a HTTP client that uses the supplied credentials.''' return credentials.authorize(httplib2.Http()) def print_creds(self): '''Prints the Authorization header to use in HTTP requests.''' cred_dict = json.loads(self.credentials.to_json()) if 'access_token' in cred_dict: print 'Authorization: Bearer %s' % (cred_dict['access_token'],) else: print 'creds: %s' % (cred_dict,) def GetConnection(self): http = httplib2.Http() self.credentials.refresh(http) http = self.credentials.authorize(http) self.print_creds() return http def main(args): # Create an instance of the HotelAdsAPIConnection inner class api = HotelAdsAPIConnection() # Generate credentials api.InitializeCredentials(_DEFAULT_APISCOPE) # Output the Authorization header to use in HTTP requests api.GetConnection() if __name__ == "__main__": main(sys.argv)
The sample Python script outputs an
Authorization header's Bearer
token, as the following example shows:
$ python sample.py Authorization: Bearer ya29.42424242sample_420icu8122KSvoh4T42cRoG3rW1lc0Q $
Use the value of the token in your requests. It is good for 1 hour after you generate it.
Running into problems? Doing a quick check on the following items may solve the problem.
- Did you create a project in the Google Developers Console?
- Did you find and enable the “Travel Hotel Ads API”?
- Did you download a .p12 file (a private key after clicking “Create client ID” and choosing “Service Account”)?
- Did you get a Service Account Client ID Email Address (of a form like "nnnnnnn@app_name.google.com.iam.gserviceaccount.com")?
- Did you shared your Hotel Ads Center account with the Service Account by clicking the “Share this account” button?
- Did you send the Service Account's email address and your partner ID to firstname.lastname@example.org?
- Are your Travel Partner API calls passing a recently-obtained token in the
- Is your
Authorizationheader's Bearer token more than 1 hour old?
The following table lists some common errors and possible resolutions:
||This could mean a number of things. If you encounter this error, check that:
||Your endpoint is most likely malformed. Check that you are submitting a GET request, and that the request URL is valid (it conforms to the API syntax that you're trying to access).|
||One or more parts of the endpoint contains invalid syntax. For example, you might have misspelled part of the path. Check that you used the correct underscores, capitalization, and wording in your entire path.|
||This error most commonly occurs when using the Reports API. You must specify "alt=csv" in the URL of your GET request. The Reports API does not support JSON.|
||When running the sample Python app, this error might be caused by one of the following:
||When running the sample Python app, the path to your .p12 file is incorrect.|
||When running the sample Python app, the API scope must be "https://www.googleapis.com/auth/travelpartner".|
||The account ID that you use is one that you do not have authorization to access. If you are a sub account owner, you might not be able to access the parent or root account ID.|
If the issue persists, please contact Google's technical support.