简体   繁体   中英

(401) Unauthorized when trying to insert a moment using the Google+ API

Using code below I successfully received a token and using this token also get user detail, but when I try to post/insert moment in user wall I see the following error message

Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https:--www.googleapis.com/plus/v1/people/me/moments/vault: (401) Unauthorized' in $_SESSION['access_token_gp']

I got user token when user login using my site in login page I ask for below permission

$client->addScope("email");
$client->addScope("https://www.googleapis.com/auth/plus.stream.write");
$client->addScope("https://www.googleapis.com/auth/plus.login");

If I print_r($tokenInfo); you will see all scope which I ask at login time.

The full code:

session_start();
require_once realpath(dirname(__FILE__) . '/google-api-php-client-master/autoload.php');

$client_id = 'my_client_id';
$client_secret = 'my_secret_key';
$redirect_uri = 'my_redirect_url';

// code to post in google plus start here //
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);

if (isset($_SESSION['access_token_gp'])) {
    // Verify the token
    $token = json_decode($_SESSION['access_token_gp']);
    $reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.$token->access_token;
    $req = new Google_Http_Request($reqUrl);
    $tokenInfo = get_object_vars(json_decode($client->getAuth()->authenticatedRequest($req)->getResponseBody()));
    if($tokenInfo['expires_in'] <= 0){
        $client->authenticate($_SESSION['access_token_gp']);
        $_SESSION['access_token_gp'] = $client->getAccessToken();
    } else {
        $client->setAccessToken($_SESSION['access_token_gp']);
    }

    $plusservicemoment = new Google_Service_Plus_Moment();
    $plusservicemoment->setType("http://schemas.google.com/AddActivity");

    $plusService = new Google_Service_Plus($client);

    $item_scope = new Google_Service_Plus_ItemScope();
    $item_scope->setId($tokenInfo['user_id']);
    $item_scope->setType("http://schemas.google.com/AddActivity");
    $item_scope->setName("The madexme Platform");
    $item_scope->setDescription("A page that describes just how madexme is work!");
    //$item_scope->setImage("full image path here");
    $plusservicemoment->setTarget($item_scope);
    $result = $plusService->moments->insert('me','vault',$plusservicemoment);
    //print_r($result);
}
// code to post in google plus end here //

Make sure you have the latest client lib from GitHub . There is something wrong with your Oauth2 connection. This code is partially converted from my Google Google Calendar API tutorial. I don't have the power to test it right now. But this should be close. I will test it tonight.

<?php    
require_once 'Google/Client.php';
require_once 'Google/Service/Plus.php';  

session_start(); 
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("AIzaSyBBH88dIQPjcl5nIG-n1mmuQ12J7HThDBE");  
$client->setClientId('2046123799103-i6cjd1hkjntu5bkdkjj5cdnpcu4iju8p.apps.googleusercontent.com');
$client->setClientSecret('6s4YOx3upyJhtwnetovfK40e');
$client->setRedirectUri('http://localhost/google-api-php-client-samples/Calendar/oauth2Pure.php');
$client->setAccessType('offline');   // Gets us our refreshtoken

$client->setScopes(array(https://www.googleapis.com/auth/plus.login'));


//For loging out.
if (isset($_GET['logout'])) {
    unset($_SESSION['token']);
}


// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {

    $client->authenticate($_GET['code']);  
    $_SESSION['token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

// Step 1:  The user has not authenticated we give them a link to login    
if (!isset($_SESSION['token'])) {

    $authUrl = $client->createAuthUrl();

    print "<a class='login' href='$authUrl'>Connect Me!</a>";
}    
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
    print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";  

    $service = new Google_Service_Plus($client);    

    $moment = new Google_Moment();
    $moment->setType('http://schemas.google.com/AddActivity');
    $itemScope = new Google_ItemScope();
    $itemScope->setUrl('https://developers.google.com/+/plugins/snippet/examples/thing');
    $moment->setTarget($itemScope);
    $plus->moments->insert('me', 'vault', $moment);
?>

Again I hope you understand that this is not going to show up on the users Google+ page / timeline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM