Using the Google Site Verification API in PHP

I wasn’t able to find any tutorial or guide on how to programmatically verify a site for Google, server-side from PHP. What follows is my attempt at doing it.

You have to install “Google APIs Client Library for PHP”, available at https://github.com/google/google-api-php-client.

I recommend reading the Google documentation on Google Site Verification API from https://developers.google.com/site-verification/v1/getting_started

So, here’s the code.

Part 1. Handle the authentication

There are multiple ways to authenticate to Google.
I went using the “OAuth 2.0 for Server to Server” path. This is where you get a json file from Google which gets you direct access to a separate (service) account. This works completely server-side, no user interaction required.
Or you can go the OAuth 2.0 for Web Server Applications path. Use this if you want to authenticate a specific Google account. User intereaction will be required, you will use a redirect url for the user to confirm the access.

Part 2. Get the verification token

Yeah, it’s a mess… but it works.
$site->setIdentifier(…) – this is where you set either the url or the domain/subdomain.
$site->setType(…) – sets the type, SITE or INET_DOMAIN
$request->setVerificationMethod(…) – sets the verification method, possible values: FILE, META, ANALYTICS, TAG_MANAGER, DNS_TXT, DNS_CNAME. more info at https://developers.google.com/site-verification/v1/getting_started#tokens

Handle the $result. If the request goes through you’ll receive a “token” field, save that and use it accordingly to complete the verification on your part. (eg: create a file, create a dns record, etc; depending on your chosen verification method)

Part 3. Complete the verification

This is similair to part 2, you have to use the same values for the site, type and verification method fields. If everything is ok, the site will be added to the Web Resource Collection, which is a list of all sites that belong to the authenticated user. You can get the list like this:

4 thoughts on “Using the Google Site Verification API in PHP

  1. i get every time i try to verify
    {“error”:{“errors”:[{“domain”:”global”,”reason”:”insufficientPermissions”,”message”:”Insufficient Permission”}],”code”:403,”message”:”Insufficient Permission”}}

  2. @Scott
    As far as I know, you can use the last method from the article ( $webResource->webResource->listWebResource() ) and check if the site appears in that list.

  3. @UJWAL
    Unfortunately I’m no longer actively using this API so don’t know what might be wrong. Have you checked that all other API calls return ok, especially the authentication?

Leave a Reply

Your email address will not be published. Required fields are marked *