Skip to content

API access on behalf of your clients (web flow)

Thanet Knack Praneenararat edited this page May 22, 2019 · 5 revisions

This guide will walk you through how to setup OAuth2 for API access on behalf of your clients using web flow.

Step 1 - Creating OAuth2 credentials

Follow the steps for the product you're using to generate a client ID and secret, then come back to this page.

Step 2 - Setting up the client library

The following is an example of web application code using a single PHP file that shows how to ask a user for their permission for your application to access their Google Ads or Ad Manager account on their behalf. This client library uses the Google Auth library to handle OAuth2.

  1. First, create an OAuth2 instance. You will need to fill in the redirectUri, clientId, and clientSecret you created in Step 1 above, as well as the OAuth2 scope of the ads API you're using.

    use Google\Auth\OAuth2;
    
    session_start();
    
    $oauth2 = new OAuth2([
        'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
        'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
        'redirectUri' => '****',
        'clientId' => '****',
        'clientSecret' => '****',
        'scope' => '****'
    ]);
  2. Direct the user to a consent screen where they can authorize your app.

    if (!isset($_GET['code'])) {
      // Create a 'state' token to prevent request forgery.
      // Store it in the session for later validation.
      $oauth2->setState(sha1(openssl_random_pseudo_bytes(1024)));
      $_SESSION['oauth2state'] = $oauth2->getState();
    
      // Redirect the user to the authorization URL.
      $config = [
        // Set to 'offline' if you require offline access.
        'access_type' => 'online'
      ];
      header('Location: ' . $oauth2->buildFullAuthorizationUri($config));
      exit;
    }

    Consent screen allow

  3. Assuming you've set the redirectUri to come back to this same page, first validate the state, and then use the authorization code to get an access token (and a refresh token if you requested offline access).

    // Check given state against previously stored one to mitigate CSRF attack.
    } elseif (empty($_GET['state'])
        || ($_GET['state'] !== $_SESSION['oauth2state'])) {
      unset($_SESSION['oauth2state']);
      exit('Invalid state.');
    } else {
      $oauth2->setCode($_GET['code']);
      $authToken = $oauth2->fetchAuthToken();
    
      // Store the refresh token for your user in your local storage if you
      // requested offline access.
      $refreshToken = $authToken['refresh_token'];
      ...
    }
  4. You can now use the OAuth2 object to make calls using the client library.

    use Google\AdsApi\AdWords\AdWordsServices;
    use Google\AdsApi\AdWords\AdWordsSessionBuilder;
    use Google\AdsApi\AdWords\v201809\cm\CampaignService;
    use Google\AdsApi\Common\OAuth2TokenBuilder;
    
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oauth2)
        ->build();
    
    $adWordsServices = new AdWordsServices();
    
    $campaignService = $adWordsServices->get($session, CampaignService::class);
    
    // Make calls using $campaignService.