/** * Runs the example. * @param string $clientId the OAuth2 client ID * @param string $clientSecret the OAuth2 client secret */ function UseOAuth2Example($clientId, $clientSecret) { // Set the OAuth2 client ID and secret. $oauth2Info = array('client_id' => $clientId, 'client_secret' => $clientSecret); // Create the AdWordsUser and set the OAuth2 info. $user = new AdWordsUser(); $user->SetOAuth2Info($oauth2Info); $user->LogAll(); // Get the authorization URL for the OAuth2 token. // No redirect URL is being used since this is an installed application. A web // application would pass in a redirect URL back to the application, // ensuring it's one that has been configured in the API console. // Passing true for the second parameter ($offline) will provide us a refresh // token which can used be refresh the access token when it expires. $authorizationUrl = $user->GetOAuth2AuthorizationUrl(NULL, TRUE); // In a web application you would redirect the user to the authorization URL // and after approving the token they would be redirected back to the // redirect URL, with the URL parameter "code" added. For desktop // or server applications, spawn a browser to the URL and then have the user // enter the authorization code that is displayed. printf("Log in to your AdWords account and open the following URL: %s\n", $authorizationUrl); print 'After approving the token enter the authorization code here: '; $stdin = fopen('php://stdin', 'r'); $code = trim(fgets($stdin)); fclose($stdin); // Get the access token using the authorization code. Ensure you use the same // redirect URL used when requesting authorization. $user->GetOAuth2AccessToken($code, NULL); // The access token expires but the refresh token obtained for offline use // doesn't, and should be stored for later use. $oauth2Info = $user->GetOAuth2Info(); print "OAuth2 authorization successful.\n"; print_r($oauth2Info); // Get the number of campaigns in the account. $campaignService = $user->GetService('CampaignService', ADWORDS_VERSION); $selector = new Selector(); $selector->fields = array('Id'); $selector->paging = new Paging(0, 0); $page = $campaignService->get($selector); // Display number of campaigns. printf("Found %d campaigns.\n", $page->totalNumEntries); }