无法json解码令牌

时间:2016-04-07 07:55:56

标签: php

这是我的代码,

   <?php
session_start(); 
$url = 'http://localhost:8080/google-drive/index.php?msg=Successfully Uploaded!'; 
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();

if(isset($_POST['submit'])){ 
$files = glob('files/*'); // get all file names
foreach($files as $file){ // iterate files
  if(is_file($file))
    unlink($file); // delete file
}

$uploaddir = 'files/';
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);
move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile);
}
$files= array();
$dir = dir('files');
while ($file = $dir->read()) {
    if ($file != '.' && $file != '..') {
        $files[] = $file;
    }
}
$dir->close();

if (!empty($_POST)) {

    $token = file_get_contents('auth.txt');
    echo $token;
    $token = array(
    'access_token' => 'xxxxxx',
    'token_type' =>'Bearer',
    'expires_in' =>'3600',
    'refresh_token' => 'xxxxx',
    'created' => 'xxxxxxx'
   );

 $tokennew = json_encode($token);
 $client->setClientId('xxxxxxxxxx');
$client->setClientSecret('xxxxxx');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
    $client->setAccessToken($tokennew);
    $service = new Google_DriveService($client);
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $file = new Google_DriveFile();
    foreach ($files as $file_name) {
        $file_path = 'files/'.$file_name;
        $mime_type = finfo_file($finfo, $file_path);
        $file->setTitle($file_name);
        $file->setDescription('This is a '.$mime_type.' document');
        $file->setMimeType($mime_type);
        $service->files->insert(
            $file,
            array(
                'data' => file_get_contents($file_path),
                'mimeType' => $mime_type
            )
        );
    }
    finfo_close($finfo);
    header('location:'.$url);
    exit;

}
include 'app.php'; 

?>

当我运行此文件时,我收到了'未捕获异常'Google_AuthException',并显示消息'无法json解码令牌'。我想从文本文件中读取访问令牌并传递给setAccessToken()函数。访问令牌打印得很好。我错在哪里?

1 个答案:

答案 0 :(得分:0)

您能提供auth.txt的内容吗?函数json_encode用于将数组转换为json对象。 auth.txt文件的内容应采用正确的格式。如果auth.txt包含一个json对象,那么你不需要json_encode,而是使用:

$client->setAccessToken(file_get_contents('auth.txt'));