/**
 * Gets an OAuth2 credential.
 * @param AdWordsUser $user the user that contains the client ID and secret
 * @return array the user's OAuth 2 credentials
 */
function GetOAuth2Credential(AdWordsUser $user)
{
    $redirectUri = NULL;
    $offline = TRUE;
    // 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.
    $OAuth2Handler = $user->GetOAuth2Handler();
    $authorizationUrl = $OAuth2Handler->GetAuthorizationUrl($user->GetOAuth2Info(), $redirectUri, $offline);
    // 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:\n%s\n\n", $authorizationUrl);
    print "After approving the token enter the authorization code here: ";
    $stdin = fopen('php://stdin', 'r');
    $code = trim(fgets($stdin));
    fclose($stdin);
    print "\n";
    // Get the access token using the authorization code. Ensure you use the same
    // redirect URL used when requesting authorization.
    $user->SetOAuth2Info($OAuth2Handler->GetAccessToken($user->GetOAuth2Info(), $code, $redirectUri));
    // The access token expires but the refresh token obtained for offline use
    // doesn't, and should be stored for later use.
    return $user->GetOAuth2Info();
}
/**
 * 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);
}
Example #3
0
 /**
  * Gets the HTTP headers for the report download request.
  * @param AdWordsUser $user the AdWordsUser to get credentials from
  * @param string $url the URL the request will be made to
  * @param array $options the options for the download
  * @return array and array of strings, which are header names and values
  */
 private static function GetHeaders($user, $url, array $options = NULL)
 {
     $headers = array();
     $version = !empty($options['version']) ? $options['version'] : $user->GetDefaultVersion();
     // Authorization.
     $authHeader = NULL;
     $oAuth2Info = $user->GetOAuth2Info();
     $oAuth2Handler = $user->GetOAuth2Handler();
     if (!empty($oAuth2Info)) {
         $oAuth2Info = $oAuth2Handler->GetOrRefreshAccessToken($oAuth2Info);
         $user->SetOAuth2Info($oAuth2Info);
         $authHeader = $oAuth2Handler->FormatCredentialsForHeader($oAuth2Info);
     } else {
         DeprecationUtils::CheckUsingClientLoginWithUnsupportedVersion($user, AdWordsUser::FINAL_CLIENT_LOGIN_VERSION, $version);
         $authHeader = sprintf(self::CLIENT_LOGIN_FORMAT, $user->GetAuthToken());
     }
     $headers['Authorization'] = $authHeader;
     // Developer token.
     $headers['developerToken'] = $user->GetDeveloperToken();
     // Target client.
     $email = $user->GetEmail();
     $clientCustomerId = $user->GetClientCustomerId();
     if (isset($clientCustomerId)) {
         $headers['clientCustomerId'] = $clientCustomerId;
     } else {
         if ($version < 'v201109' && isset($email)) {
             $headers['clientEmail'] = $email;
         } else {
             throw new ReportDownloadException('The client customer ID must be ' . 'specified for report downloads.');
         }
     }
     // Flags.
     if (isset($options['returnMoneyInMicros'])) {
         DeprecationUtils::CheckUsingReturnMoneyInMicrosWithUnsupportedVersion(self::FINAL_RETURN_MONEY_IN_MICROS_VERSION, $version);
         $headers['returnMoneyInMicros'] = $options['returnMoneyInMicros'] ? 'true' : 'false';
     }
     return $headers;
 }
Example #4
0
 /**
  * Gets the HTTP headers for the report download request.
  * @param AdWordsUser $user the AdWordsUser to get credentials from
  * @param string $url the URL the request will be made to
  * @param array $options the options for the download
  * @return array and array of strings, which are header names and values
  */
 private static function GetHeaders($user, $url, array $options = NULL)
 {
     $headers = array();
     $version = !empty($options['version']) ? $options['version'] : $user->GetDefaultVersion();
     // Authorization.
     $authHeader = NULL;
     $oAuth2Info = $user->GetOAuth2Info();
     $oAuth2Handler = $user->GetOAuth2Handler();
     if (!empty($oAuth2Info)) {
         $oAuth2Info = $oAuth2Handler->GetOrRefreshAccessToken($oAuth2Info);
         $user->SetOAuth2Info($oAuth2Info);
         $authHeader = $oAuth2Handler->FormatCredentialsForHeader($oAuth2Info);
     } else {
         throw new ServiceException('OAuth 2.0 authentication is required.');
     }
     $headers['Authorization'] = $authHeader;
     // Developer token.
     $headers['developerToken'] = $user->GetDeveloperToken();
     // Target client.
     $clientCustomerId = $user->GetClientCustomerId();
     if (isset($clientCustomerId)) {
         $headers['clientCustomerId'] = $clientCustomerId;
     } else {
         throw new ReportDownloadException('The client customer ID must be ' . 'specified for report downloads.');
     }
     // Flags.
     if (isset($options['returnMoneyInMicros'])) {
         DeprecationUtils::CheckUsingReturnMoneyInMicrosWithUnsupportedVersion(self::FINAL_RETURN_MONEY_IN_MICROS_VERSION, $version);
         $headers['returnMoneyInMicros'] = $options['returnMoneyInMicros'] ? 'true' : 'false';
     }
     return $headers;
 }
 /**
  * Gets the HTTP headers for the report download request.
  * @param AdWordsUser $user the AdWordsUser to get credentials from
  * @param string $url the URL the request will be made to
  * @param array $options the options for the download
  * @return array and array of strings, which are header names and values
  */
 private static function GetHeaders($user, $url, array $options = null)
 {
     $headers = array();
     $version = !empty($options['version']) ? $options['version'] : $user->GetDefaultVersion();
     // Authorization.
     $authHeader = null;
     $oAuth2Info = $user->GetOAuth2Info();
     $oAuth2Handler = $user->GetOAuth2Handler();
     if (!empty($oAuth2Info)) {
         $oAuth2Info = $oAuth2Handler->GetOrRefreshAccessToken($oAuth2Info);
         $user->SetOAuth2Info($oAuth2Info);
         $authHeader = $oAuth2Handler->FormatCredentialsForHeader($oAuth2Info);
     } else {
         throw new ServiceException('OAuth 2.0 authentication is required.');
     }
     $headers['Authorization'] = $authHeader;
     // Developer token.
     $headers['developerToken'] = $user->GetDeveloperToken();
     // Target client.
     $clientCustomerId = $user->GetClientCustomerId();
     if (isset($clientCustomerId)) {
         $headers['clientCustomerId'] = $clientCustomerId;
     } else {
         throw new ReportDownloadException('The client customer ID must be ' . 'specified for report downloads.');
     }
     // Flags.
     if (isset($options['skipReportHeader'])) {
         $headers['skipReportHeader'] = $options['skipReportHeader'] ? 'true' : 'false';
     }
     if (isset($options['skipColumnHeader'])) {
         $headers['skipColumnHeader'] = $options['skipColumnHeader'] ? 'true' : 'false';
     }
     if (isset($options['skipReportSummary'])) {
         $headers['skipReportSummary'] = $options['skipReportSummary'] ? 'true' : 'false';
     }
     if (isset($options['includeZeroImpressions'])) {
         $headers['includeZeroImpressions'] = $options['includeZeroImpressions'] ? 'true' : 'false';
     }
     return $headers;
 }
    // OPTIONAL: Create an AdGroupFeed for even more fine grained control over
    // which feed items are used at the AdGroup level.
}
// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
    return;
}
try {
    // Get AdWordsUser from credentials in "../auth.ini"
    // relative to the AdWordsUser.php file's directory.
    $user = new AdWordsUser();
    $oAuth2Info = $user->GetOAuth2Info();
    $oAuth2Handler = $user->GetOAuth2Handler();
    if (!isset($oAuth2Info['access_token'])) {
        $oAuth2Info = $oAuth2Handler->GetOrRefreshAccessToken($oAuth2Info);
        $user->SetOAuth2Info($oAuth2Info);
    }
    // Log every SOAP XML request and response.
    $user->LogAll();
    // If the GMB_EMAIL_ADDRESS is the same user you used to generate your
    // AdWords API refresh token, leave the assignment below unchanged.
    // Otherwise, to obtain an access token for your GMB account, run the
    // Auth/GetRefreshToken example. Make sure you are logged in as the same user
    // as GMB_EMAIL_ADDRESS above when you follow the link provided by the example
    // then call GetOAuth2Info on the generated AdWordsUser object and copy and
    // paste the value into the assignment below.
    define('GMB_ACCESS_TOKEN', $oAuth2Info['access_token']);
    // Run the example.
    AddGoogleMyBusinessLocationExtensions($user, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, BUSINESS_ACCOUNT_IDENTIFIER);
} catch (Exception $e) {
    printf("An error has occurred: %s\n", $e->getMessage());
 /**
  * Tests that the access_token is refreshed correctly and set on the URL
  * params for this client library.
  */
 public function testIntegrationOAuth2Handler_InvalidAccessToken()
 {
     $credentialsOverride = array('access_token' => sprintf('TEST_ACCESS_TOKEN_%s', uniqid()), 'refresh_token' => sprintf('TEST_REFRESH_TOKEN_%s', uniqid()), 'expires_in' => '3600', 'timestamp' => strtotime('-1 day'));
     $credentialsRefreshed = array('access_token' => sprintf('TEST_ACCESS_TOKEN_%s', uniqid()), 'refresh_token' => $credentialsOverride['refresh_token'], 'expires_in' => '3600', 'timestamp' => time(), 'Foo' => 'bar');
     // Get the response xml
     $xmlResponse = $this->assetHelper->getAsset(sprintf(self::RESPONSE_NAME, self::SERVICE));
     // Create a regular AdWordsUser
     $user = new AdWordsUser($this->assetHelper->getAssetPath('auth.ini'));
     $campaignService = $user->getService(self::SERVICE);
     $oAuth2Info = $user->GetOAuth2Info();
     $newOAuth2Info = array_merge($oAuth2Info, $credentialsOverride);
     $user->SetOAuth2Info($newOAuth2Info);
     // Get the expected auth param for the URL.
     $oauth2Url = http_build_query(array('access_token' => $credentialsRefreshed['access_token']));
     // Setup the mocked OAuth2Handler class.
     $oAuth2Handler = $this->getMock('SimpleOAuth2Handler', array('RefreshAccessToken'));
     $oAuth2Handler->expects($this->any())->method('RefreshAccessToken')->will($this->returnValue($credentialsRefreshed));
     $user->SetOAuth2Handler($oAuth2Handler);
     // Setup the test.
     $soapClientMock = $this->getMockBuilder('SoapClient')->setMethods(array('__doRequest'))->disableOriginalConstructor()->getMock();
     // Checking for the URL param for the auth token
     // (passed in the second function param)
     $soapClientMock->expects($this->any())->method('__doRequest')->with($this->anything(), $this->stringContains($oauth2Url))->will($this->returnValue($xmlResponse));
     // Set the transport layer on the soap client to be the mocked soap client.
     $campaignService->__SetTransportLayer($soapClientMock);
     // Create selector.
     $selector = new Selector();
     // Specify the fields to retrieve.
     $selector->fields = array('Login', 'CustomerId', 'Name');
     // Make the get request.
     $campaignService->get($selector);
 }