0
votes

I was trying to post moment in google+ using google php api. I am using Codeigniter framework. I am following https://developers.google.com/+/api/latest/moments/insert documentation and used a little modified version of it. I tested each line of the following code one by one. It seems only this line of code is not working.

$momentResult = $this->googleplus->plus->moments->insert('me', 'vault', $this->googleplus->moment_body);

It causes 401 unauthorized error like following.

Google_Service_Exception Object
(
    [errors:protected] => Array
    (
        [0] => Array
        (
            [domain] => global
            [reason] => unauthorized
            [message] => Unauthorized
            )

        )

    [message:protected] => 'Error calling POST https://www.googleapis.com/plus/v1/people/me/moments/vault?key=my_key_from_console: (401) Unauthorized'
...
...
)

I used proper api_key,secret_key,client_id,app_name,redirect_url, but still can't fix this error.

    <?php

    if (!defined('BASEPATH'))
        exit('No direct script access allowed');
    include_once 'base_controller.php';

    class Gp_auth extends Base_controller {

        private $_gp_client;

        public function __construct() {
            parent::__construct();

            $this->load->library('googleplus');
            $this->_gp_client = $this->googleplus->client;

            $this->_gp_client->setApplicationName("my_app_name");
            $this->_gp_client->setDeveloperKey("my_developerkey_incase_it_needed");
            $this->_gp_client->setClientId('my_client_id_from_console');
            $this->_gp_client->setClientSecret('my_client_secret');
            $this->_gp_client->setRedirectUri(base_url().'gp_auth');
        }

        public function index() {

            if ($this->input->get_post('code')) {
                try {
                    $this->_gp_client->authenticate($this->input->get_post('code'));
                    $access_token = $this->_gp_client->getAccessToken();
                    $this->session->set_userdata('access_token', $access_token);
                    redirect('/gp_auth/me');
                } catch (Google_Auth_Exception $e) {
                    echo "<pre>";
                    print_r($e);
                    echo "</pre>";
                }
            } else {
                $this->_gp_client->addScope(array(
                    'https://www.googleapis.com/auth/plus.login',
                    'https://www.googleapis.com/auth/plus.moments.write'
                    ));
                $this->_gp_client->setAccessType('online');
                $this->_gp_client->setApprovalPrompt("force");
                $this->_gp_client->setRequestVisibleActions('http://schemas.google.com/CreateActivity');

                try {
                    echo anchor($this->_gp_client->createAuthUrl(), 'Conect Me');
                } catch (Google_Auth_Exception $e) {
                    echo "<pre>";
                    print_r($e);
                    echo "</pre>";
                }
            }
        }

        public function me() {
            try {
                $this->_gp_client->setAccessToken($this->session->userdata('access_token'));
                $response = $this->googleplus->plus->people->get('me');
                $post_data = array(
                    'gp_id' => $response->id,
                    'gp_access_token' => $this->session->userdata('access_token'),
                    'post_body' => 'Silicon orchard limited logo.',
                    'post_attachment' => 'http://www.siliconorchard.com/img/logo.png'
                    );
                $this->gp_post($post_data);
            } catch (Google_Auth_Exception $e) {
                echo "<pre>";
                print_r($e);
                echo "</pre>";
            }
        }

        public function gp_post($post_data) {
            $this->_gp_client->setAccessToken($post_data['gp_access_token']);
            $this->_gp_client->setRequestVisibleActions(array('http://schemas.org/AddActivity'));

            $this->googleplus->item_scope->setId("target-id-1");
            $this->googleplus->item_scope->setType("http://schema.org/AddAction");
            $this->googleplus->item_scope->setName("The Google+ Platform");
            $this->googleplus->item_scope->setDescription("A page that describes just how awesome Google+ is!");
            $this->googleplus->item_scope->setImage("https://developers.google.com/+/plugins/snippet/examples/thing.png");

            $this->googleplus->moment_body->setObject($this->googleplus->item_scope);

            try {
                $momentResult = $this->googleplus->plus->moments->insert('me', 'vault', $this->googleplus->moment_body);
                echo "<pre>";
                print_r($momentResult);
                echo "</pre>";
            } catch (Google_Auth_Exception $e) {
                echo "<pre>";
                print_r($e);
                echo "</pre>";
            } catch (Google_Service_Exception $servic_exception) {
                echo "<pre>";
                print_r($servic_exception);
                echo "</pre>";
            }
        }

    }

This is the googleplus library file.

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Googleplus {

    public function __construct() {

        $CI = & get_instance();
        $CI->config->load('googleplus');

        (set_include_path(APPPATH."third_party/" . PATH_SEPARATOR . get_include_path()));
        require_once 'Google/Client.php';
        require_once 'Google/Service/Plus.php';

        $cache_path = $CI->config->item('cache_path');
        $GLOBALS['apiConfig']['ioFileCache_directory'] = ($cache_path == '') ? APPPATH . 'cache/' : $cache_path;

        $this->client = new Google_Client();
        $this->client->setApplicationName($CI->config->item('application_name', 'googleplus'));
        $this->client->setClientId($CI->config->item('client_id', 'googleplus'));
        $this->client->setClientSecret($CI->config->item('client_secret', 'googleplus'));
        $this->client->setRedirectUri($CI->config->item('redirect_uri', 'googleplus'));
        $this->client->setDeveloperKey($CI->config->item('api_key', 'googleplus'));

        $this->plus = new Google_Service_Plus($this->client);

        $this->moment_body = new Google_Service_Plus_Moment();
        $this->moment_body->setType("http://schema.org/AddAction");

        $this->item_scope = new Google_Service_Plus_ItemScope();
    }

    public function __get($name) {

        if (isset($this->plus->$name)) {
            return $this->plus->$name;
        }
        return false;
    }

    public function __call($name, $arguments) {

        if (method_exists($this->plus, $name)) {
            return call_user_func(array($this->plus, $name), $arguments);
        }
        return false;
    }

}

Found plenty of similar problem but no solution works. I am using latest version of google php api.

1

1 Answers

1
votes

Sometimes using both OAuth and an API/developer key at the same time confuses the API (even though it shouldn't).

Removing the ->setDeveloperKey lines from your code should work to fix this.

There's an open issue for this here: https://code.google.com/p/google-plus-platform/issues/detail?id=458


One more potential issue:

You use this when you create the authentication URL:

->setRequestVisibleActions('http://schemas.google.com/CreateActivity');

But then you try to write a moment like this:

->setType("http://schema.org/AddAction");

You will have to include this moment type for your original authentication, instead of/in addition to the CreateActivity. Setting it at a later point after authentication happened won't change the permissions the current access token has.