Token Handling - Zend Framework - OAuth 2.0 - Google

Sample code to get a request token from Google through OAuth 2.0. These are snippets of code to show the request and response interaction.

This is the link to allow a user to authorize application access.

        $auth_uri='https://accounts.google.com/o/oauth2/auth?'.
                'client_id='.$this->configs->contacts->client->id.'&'.
                'redirect_uri='.$this->configs->contacts->redirect_uri.'&'.
                'scope='.$this->configs->contacts->scope.'&'.
                'response_type=code';

If the user authorizes access, Google gives them a token, which is referred to as an auth_code in the following code. They paste the token in the auth_code input and click a button to initiate this action.

            if ($form->getElement('auth_code')->isValid($data['auth_code']))
            {
                $client = new Zend_Http_Client($this->configs->oauth_uri,
                    array( 'maxredirects' => 0, 'timeout'      => 30));
                $client->setMethod(Zend_Http_Client::POST);
                $client->setHeaders('Content-Type: application/x-www-form-urlencoded');
                $client->setParameterPost(array(
                    'code' => $data['auth_code'],
                    'client_id' => $this->configs->contacts->client->id,
                    'client_secret' => $this->configs->contacts->client->secret,
                    'redirect_uri' => $this->configs->contacts->redirect_uri,
                    'grant_type' => 'authorization_code'));
                $response = $client->request();
                $this->googlecontacts_data->last_status = $response->getStatus();
                if ($response->isSuccessful())
                {
                    $response_data = Zend_Json::decode($response->getBody());
                    $this->googlecontacts_data->last_auth = new Doctrine_Expression('NOW()');
                    $this->googlecontacts_data->access_token = $response_data['access_token'];
                    $this->googlecontacts_data->expires_in = $response_data['expires_in'];
                    $this->googlecontacts_data->token_type = $response_data['token_type'];
                    $this->googlecontacts_data->refresh_token = $response_data['refresh_token'];
                    $this->googlecontacts_data->status = 'authorized';
                }
                else
                {
                    $this->googlecontacts_data->access_token =
                    $this->googlecontacts_data->expires_in =
                    $this->googlecontacts_data->token_type =  
                    $this->googlecontacts_data->refresh_token = null;
                    $this->googlecontacts_data->status = 'not_authorized';
                }
                $this->save_googlecontacts_data(); 

This code uses the access or refresh token to retrieve the contacts.

        if ($this->googlecontacts_data->status == 'authorized')
        {
            $client = new Zend_Http_Client($this->configs->contacts->userinfo,
                array( 'maxredirects' => 0, 'timeout' => 30));
            $client->setMethod(Zend_Http_Client::GET);
            $client->setHeaders('Authorization: Bearer '.$this->googlecontacts_data->access_token);
            $response = $client->request();
            if (!$response->isSuccessful())
            {
                $client = new Zend_Http_Client($this->configs->oauth_uri,
                    array( 'maxredirects' => 0, 'timeout'      => 30));
                $client->setMethod(Zend_Http_Client::POST);
                $client->setHeaders('Content-Type: application/x-www-form-urlencoded');
                $client->setParameterPost(array(
                    'client_id' => $this->configs->contacts->client->id,
                    'client_secret' => $this->configs->contacts->client->secret,
                    'refresh_token' => $this->googlecontacts_data->refresh_token,
                    'grant_type' => 'refresh_token'));
                $response = $client->request();
            }
            $this->googlecontacts_data->last_status = $response->getStatus();
            if ($response->isSuccessful())
            {
                $response_data = Zend_Json::decode($response->getBody());
                $this->googlecontacts_data->last_auth = new Doctrine_Expression('NOW()');
                $this->googlecontacts_data->access_token = $response_data['access_token'];
                $this->googlecontacts_data->expires_in = $response_data['expires_in'];
                $this->googlecontacts_data->token_type = $response_data['token_type'];
                $this->googlecontacts_data->auto = null;
                $this->googlecontacts_data->deleted_at = null;
                $this->googlecontacts_data->status = 'authorized';
            }
            else
            {
                $this->googlecontacts_data->access_token =
                $this->googlecontacts_data->expires_in =
                $this->googlecontacts_data->token_type =
                $this->googlecontacts_data->refresh_token =
                $this->googlecontacts_data->auto = null;
                $this->googlecontacts_data->status = 'not_authorized';
            }
            $return = $this->save_googlecontacts_data();
            if (!isset($return['error']))
            {
                $this->view->results = $this->get_contacts();
                $this->return['success'] = true;
            }
        }
        else
            $this->return['error'] = $this->status();

Some of the config values (other omitted for security):

oauth_uri = “https://accounts.google.com/o/oauth2/token”
contacts.uri = “https://www.google.com/m8/feeds/contacts/default/full”
contacts.scope = “https://www.google.com/m8/feeds/”
contacts.userinfo = “https://www.googleapis.com/oauth2/v1/userinfo”

.ini file settings for auth_code input. This application forces the user to cut and paste the token into the browser.

[production]
action="/contacts/google”
method="post”

disableTranslator = 0
; code element
elements.auth_code.type = “ValidationTextBox”
elements.auth_code.options.label = “Authorization Code”
elements.auth_code.options.required = true
elements.auth_code.options.trim = “true”
elements.auth_code.options.class = “long”
elements.auth_code.options.validators.strlen.validator = “StringLength”
elements.auth_code.options.validators.strlen.options.min = “8″
elements.auth_code.options.validators.strlen.options.max = “100″
elements.auth_code.options.validators.regex.validator = “regex”
elements.auth_code.options.validators.regex.options.pattern = “/^[\w\/\-]{8,100}$/”
elements.auth_code.options.validators.regex.options.messages.regexInvalid = “Invalid code”
elements.auth_code.options.filters[] = “StringTrim”
elements.auth_code.options.filters[] = “StripTags”
elements.auth_code.options.filters[] = “StripNewlines”

displayGroups.gcode.options.order = 10
displayGroups.gcode.options.class = “auth_code”
displayGroups.gcode.elements[] = “auth_code”