Search code examples
phpapigoogle-apisdkadsense

Adsense API get single domain


I'm currently looking into selecting a single domain on the Adsense API to see if the domain is currently available in Adsense. Selecting all domains goes well, but it seems a bit cumbersome to loop all properties. So I'm looking for a single select

Current code:

# Setup client
$client = new Google_Client();
$client->setAccessToken(GOOGLE_ACCESS_TOKEN);

# Setup api
$adsense = new \Google\Service\Adsense($client);

# Set Scope to adsense
$client->setScopes(['https://www.googleapis.com/auth/adsense']);

# list account sites
$ads = $adsense->accounts_sites->listAccountsSites("accounts/pub-xxxxxxxxxxxxxxxx");

#loop through the domains and check if in array
foreach ($ads as $a) {
    $ad_sites[] = $a['domain'];
}

# Result:
$in_adsense = in_array($domain, $ad_sites)

What looks promising is the current doc by Google: https://developers.google.com/adsense/management/reference/rest/v2/accounts.sites/get

And the corresponding get method: https://developers.google.com/adsense/management/reference/rest/v2/accounts.sites/get

I however can't seem to find the right syntax to select a single domain on the Google SDK. Any help would be appriciated.


Solution

  • Turns out I've overlooked a possibility to use a gRPC query. This turns out to be the following code, based on the example created by @Wahyu Kristianto.

    $domain = "google.com";
    $adsense = new \Google\Service\Adsense($client);
    
    try {
        $site = $adsense->accounts_sites->get("accounts/pub-xxxxxxxx/sites/{$domain}");
        $in_adsense = true;
    } catch (\Exception $e) {
        $in_adsense = false;
    }
    
    

    So we're calling a gRPC query to the get method: accounts/pub-xxxxxxxx/sites/google.com