如何使用PHP在博客上注册新帖子?

时间:2015-03-02 01:36:48

标签: php google-api blogger

<?php
    session_start();

    require_once dirname(__FILE__) . '/google-api-php-client/src/Google/autoload.php'; // or wherever autoload.php is located
    require_once dirname(__FILE__).'/google-api-php-client/src/Google/Service/Blogger.php';

$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];

$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('Title'); //name of the application
$client->setClientId('xxxxxxxxxxx.apps.googleusercontent.com'); //insert your client id
$client->setClientSecret('zzzzzzzzzzzzzzzzzzz'); //insert your client secret
$client->setRedirectUri($scriptUri); //redirects to same url
$client->setDeveloperKey('yyyyyyyyyyyyyyyyy'); // API key (at bottom of page)
$client->setScopes(array('https://www.googleapis.com/auth/blogger')); //since we are going to use blogger services


$blogger = new Google_Service_Blogger($client);  

if (isset($_GET['logout'])) { // logout: destroy token
    unset($_SESSION['token']);
 die('Logged out.');
}

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
}

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];
    $client->setAccessToken($token);
}

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);
    die;
}
//you can get the data about the blog by getByUrl
$data = $blogger->blogs->getByUrl(array('url'=>'http://gggggggggg.blogspot.com/'));

//creates a post object
$mypost = new Google_Service_Blogger_Post();
$mypost->setTitle('this is a test 1 title');
$mypost->setContent('this is a test 1 content');
$data = $blogger->posts->insert('999999999999999', $mypost);
?>

返回错误: 警告:缺少Google_Client :: authenticate()的参数1,在第27行的/home/vvvvvvvvvv/public_html/post2.php中调用,并在/ home / vvvvvvvvvv / public_html / google-api-php-client / src / Google /中定义第122行的Client.php

致命错误:未捕获的异常&#39; Google_Auth_Exception&#39;消息&#39;无效代码&#39;在/home/vvvvvvvvv/public_html/google-api-php-client/src/Google/Auth/OAuth2.php:87堆栈跟踪:#0 / home / vvvvvvvvv / public_html / google-api-php-client / src / Google /Client.php(125):Google_Auth_OAuth2-&gt; authenticate(NULL)#1 /home/vvvvvvvvvv/public_html/post2.php(27):/ home / vvvvvvvvv中引用的Google_Client-&gt; authenticate()#2 {main}第87行/public_html/google-api-php-client/src/Google/Auth/OAuth2.php

1 个答案:

答案 0 :(得分:1)

我知道它已经很晚了,但你并没有在code方法中使用authenticate

更改此

$client->authenticate();

到这个

$client->authenticate( $_GET['code'] );