İstemci kitaplığı kullanıyorsanız uygulamanızın bir Doubleclicksearch
hizmet nesnesi oluşturması gerekir. Search Ads 360 API ile tüm etkileşimler bu hizmet nesnesi aracılığıyla gerçekleşir. İstemci kitaplığı kullanmıyorsanız bu bölümü atlayabilirsiniz ancak HTTP istekleri gönderip yanıtları ayrıştırabilecek bir kod yazmanız gerekir.
Her Doubleclicksearch
örneği için kimlik bilgilerinizi ve OAuth 2.0 erişim jetonunuzu içeren bir nesneye referans gerekir.
Doubleclicksearch
, her istekte kimlik bilgilerini ve jetonu Search Ads 360 API'ye iletir. Aşağıdaki kodda, yüklü uygulamalar için OAuth 2.0 kullanılarak bir Doubleclicksearch
hizmet nesnesi oluşturma işlemi gösterilmektedir.
Search Ads 360 API için OAuth 2.0 kimlik bilgilerinizi henüz edinmediyseniz Yetkilendirmeyi Ayarlama başlıklı makaleyi inceleyin.
Java
import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.store.DataStoreFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.doubleclicksearch.Doubleclicksearch; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.Arrays; private static final String[] SCOPES = new String[] { "https://www.googleapis.com/auth/doubleclicksearch" }; /** File for storing user credentials. */ private static final java.io.File DATA_STORE_FILE = new File(System.getProperty("user.home"), ".credentials/doubleclicksearch.json"); /** * Global instance of the {DataStoreFactory}. The best practice is to make it a single * globally shared instance across your application. */ private static FileDataStoreFactory dataStoreFactory; /** * Sets up a new Doubleclicksearch service. The builder for the service * requires a Credential object, which provides the credentials needed to * interact with Search Ads 360. */ private static Doubleclicksearch getService() throws Exception { JsonFactory jsonFactory = new JacksonFactory(); NetHttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); Credential credential = readCredentialFromCommandLine(jsonFactory, transport); return new Doubleclicksearch.Builder(transport, jsonFactory, credential) .setApplicationName("Sample") .build(); } /** * Generates a credential by reading client id, client secret and refresh * token from the command line. You could update this method to read the * data from a database or other secure location. */ private static Credential readCredentialFromCommandLine( JsonFactory jsonFactory, NetHttpTransport transport) { String clientId = System.console().readLine("Client id: "); String clientSecret = System.console().readLine("Client secret: "); String refreshToken = System.console().readLine("Refresh token: "); return new GoogleCredential.Builder() .setJsonFactory(jsonFactory) .setTransport(transport) .setClientSecrets(clientId, clientSecret) .build() .setRefreshToken(refreshToken); } /** * This method is an alternative to {@link #readCredentialFromCommandLine}. It reads * client secrets from a {@code client_secrets.json} file, interactively creates * the necessary authorization tokens on first run, and stores the tokens in the * {@code FileDataStore}. Subsequent runs will no longer require interactivity * as long as the {@code .credentials/doubleclicksearch.json} file is not removed. * You can download the {@code .credentials/doubleclicksearch.json} file from the * Google API Console. * Note that setting the {@link GoogleAuthorizationCodeFlow} access type * to {@code offline} is what causes {@code GoogleAuthorizationCodeFlow} to obtain * and store refresh tokens. */ private static Credential generateCredentialInteractively( JsonFactory jsonFactory, NetHttpTransport transport) throws Exception { dataStoreFactory = new FileDataStoreFactory(DATA_STORE_FILE); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( jsonFactory, new InputStreamReader( Doubleclicksearch.class.getResourceAsStream("/client_secrets.json"))); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( transport, jsonFactory, clientSecrets, Arrays.asList(SCOPES)) .setDataStoreFactory(dataStoreFactory) .setAccessType("offline") .build(); return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); }
.NET
using System; using System.Collections.Generic; using System.IO; using System.Threading; using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2.Flows; using api = Google.Apis.Doubleclicksearch.v2; /// <summary> /// Creates a Doubleclicksearch API service with static credentials. /// </summary> /// <param name="clientId">API project client ID.<param> /// <param name="clientSecret">API project client secret.<param> /// <param name="refreshToken">Refresh token generated for installed applications.<param> private static api.DoubleclicksearchService CreateService( String clientId, String clientSecret, String refreshToken) { var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse { RefreshToken = refreshToken, }; var credentials = new UserCredential(new GoogleAuthorizationCodeFlow( new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret, }, }), "user", token); return new api.DoubleclicksearchService( new Google.Apis.Services.BaseClientService.Initializer { HttpClientInitializer = credentials, ApplicationName = "Sample DS API client", }); }
Python
import argparse import httplib2 from apiclient.discovery import build from oauth2client import GOOGLE_TOKEN_URI from oauth2client.client import OAuth2Credentials, HttpAccessTokenRefreshError def create_credentials(client_id, client_secret, refresh_token): """Create Google OAuth2 credentials. Args: client_id: Client id of a Google Cloud console project. client_secret: Client secret of a Google Cloud console project. refresh_token: A refresh token authorizing the Google Cloud console project to access the DS data of some Google user. Returns: OAuth2Credentials """ return OAuth2Credentials(access_token=None, client_id=client_id, client_secret=client_secret, refresh_token=refresh_token, token_expiry=None, token_uri=GOOGLE_TOKEN_URI, user_agent=None) def get_service(credentials): """Set up a new Doubleclicksearch service. Args: credentials: An OAuth2Credentials generated with create_credentials, or flows in the oatuh2client.client package. Returns: An authorized Doubleclicksearch serivce. """ # Use the authorize() function of OAuth2Credentials to apply necessary credential # headers to all requests. http = credentials.authorize(http = httplib2.Http()) # Construct the service object for the interacting with the Search Ads 360 API. service = build('doubleclicksearch', 'v2', http=http) return service if __name__ == '__main__': parser = argparse.ArgumentParser(description='Sample DS API code.') parser.add_argument('--client_id', dest='c_id', action='store', help=('Specifies the DS API client_id. Looks like: ' '1234567890.apps.googleusercontent.com'), required=True) parser.add_argument('--client_secret', dest='secret', action='store', help=('Specifies the DS API client_secret. Looks like: ' '1ab2CDEfghigKlM3OPzyx2Q'), required=True) parser.add_argument('--refresh_token', dest='token', action='store', help=('Specifies the DS API refresh_token. Looks like: ' '4/abC1ddW3WJURhF7DUj-6FHq8kkE'), required=True) args = parser.parse_args() creds = create_credentials(args.c_id, args.secret, args.token) try: service = get_service(creds) print 'Successfully loaded credentials.' except HttpAccessTokenRefreshError: print ('Error: Unable to get credentials. Please ensure that the ' 'credentials are correct. ' 'https://developers.google.com/search-ads/v2/authorizing' )