Adventures with Google Content API and OAuth

So recently I have had the opportunity to play with Google’s Content API and their OAuth API.

I have needed to use it in “offline” mode, as I want to interact with Google when the authorising user is not present (cron jobs and such).

Here are my lessons learnt.

  • You can Indeed use OAuth on a website that wants to use it in the background. You just need to persistently store the tokens (especially the refresh token!)
  • The refresh token ONLY appears when the user is asked for permission. it does *not* appear when access is auto approved. This means when you generate the authorise url – you need to specify the “approval=force” option!
  • Their testing facilities are not that good, trying to sort out a sandbox site is like pulling teeth. Their account signup pages were busted 🙁
  • Their API is pretty good!

Google Content API Class

Below is a simple class stub to interact with Google. The PersistentKeyValueStore class is fairly self explanitory and you can implement your own (I persist my data in a simple table with the columns “key” and “value” with “key” being a primary key).

When implementing this class you will need

  • A user to initially interact with a web page
  • Your code to call the Google_Content_Client->doAuthorise() function so the user can interact with the OAuth page.
  • <?php
    client = new GSC_Client($options->merchantId);
    		$this->options = $options;
    
    		$this->authToken = new GSC_OAuth2Token(
    			$this->options->clientId,
    			$this->options->clientSecret,
    			$this->options->userAgent
    		);
    
    		$token = PersistentKeyValueStore::get(self::TOKEN_KEY);
    		if (!$token) {
    			return false;
    		}
    		$this->authToken->fromBlob($token);
    
    		$this->client->setToken($this->authToken);
    	}
    
    	/**
    	 * handles the user interaction for the authorising
    	 */
    	public function doAuthorise($revoke, $force = false) {
    
    		if ($revoke) {
    			// do we have a refresh token to revoke?
    
    			$bits = explode('|',PersistentKeyValueStore::get(self::TOKEN_KEY));
    			if ($bits[4]) {
    				$this->authToken->revoke();
    			}
    			PersistentKeyValueStore::set(self::TOKEN_KEY,'');
    		} else {
    			$code = @$_GET['code'];
    
    			$approvalPrompt = $force ? 'force' : 'auto';
    			$authorizeUrl = $this->authToken->generateAuthorizeUrl($this->options->redirectUri, $approvalPrompt);
    			if ('' == $code) {
    				header("Location: $authorizeUrl");
    				die;
    			} else {
    				$this->authToken->getAccessToken($_GET['code']);
    				$this->client->setToken($this->authToken);
    				PersistentKeyValueStore::set(self::TOKEN_KEY,$this->authToken->toBlob());
    			}
    		}
    
    	}
    
    	/** your functions to wrap Google's **/
    }