如果用户删除了他们的“App”文件夹,Dropbox API 会抛出 Dropbox\Exception_InvalidAccessToken 异常。所以你应该只正确处理这个异常。例如:
use \Dropbox as dbx;
define ('API_CONF_FILE', '/path/to/api-conf.json');
define ('CLIENT_ID', 'Your Upload App/1.0');
$accessToken = obtain_the_access_token();
$appInfo = dbx\AppInfo::loadFromJsonFile(API_CONF_FILE);
for (;;) {
echo "Connecting to Dropbox...\n";
$dbxClient = new dbx\Client($accessToken, CLIENT_ID);
try {
// This call will also throw `Dropbox\Exception_InvalidAccessToken`
//$folderMetadata = $dbxClient->getMetadataWithChildren("/");
$f = fopen("/path/to/test.txt", "r");
$result = $dbxClient->uploadFile("/test.txt", dbx\WriteMode::add(), $f);
fclose($f);
print_r($result);
break;
} catch (Dropbox\Exception_InvalidAccessToken $e) {
$message = $e->getMessage();
if ($brace_pos = strpos($message, '{')) {
$error_title = substr($message, 0, $brace_pos);
if ($json_error = json_decode(substr($message, $brace_pos), true)) {
$error_description = $json_error['error'] ?? 'N/A';
}
fprintf(STDERR, "Error: %s\nDescription: %s\n",
$error_title, $error_description ?? 'N/A');
$webAuth = new dbx\WebAuthNoRedirect($appInfo, CLIENT_ID);
$authorizeUrl = $webAuth->start();
echo "1. Go to: $authorizeUrl\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
echo "3. Copy the authorization code.\n";
$authCode = \trim(\readline("Enter the authorization code here: "));
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
echo "Access Token: $accessToken\n";
}
} catch (Exception $e) {
fprintf(STDERR, "Unknown exception: %s\n", $e->getMessage());
exit(1);
}
}
注意,我使用的是 PHP7 Null coalescing operator。
示例输出(最初删除文件夹时)
Connecting to Dropbox...
Error: HTTP status 401
Description: User has removed their App folder.
1. Go to: https://www.dropbox.com/1/oauth2/authorize?locale=&client_id=2deadbeef2ofaft&response_type=code
2. Click "Allow" (you might have to log in first).
3. Copy the authorization code.
Enter the authorization code here: IugIByIMdKkAAAAAAAAAhVTH02dF7LW70_fFEHHohXo
Access Token: IugIByIMdKkAAAAAAAAAhtPGKSoVOBs557XXrq-zX57L4QRAmqiUTagktS7YDmg1
Connecting to Dropbox...
Array
(
[revision] => 1
[bytes] => 10
[thumb_exists] =>
[rev] => 14ef8952b
[modified] => Tue, 04 Oct 2016 09:02:31 +0000
[mime_type] => text/plain
[path] => /working-draft.txt
[is_dir] =>
[size] => 10 bytes
[root] => app_folder
[id] => id:rmvcpq3LHlAAAAAAAAAAAw
[client_mtime] => Tue, 04 Oct 2016 09:02:31 +0000
[icon] => page_white_text
)
示例输出(当文件夹最初存在时)
Connecting to Dropbox...
Array
(
[revision] => 2
[bytes] => 10
[thumb_exists] =>
[rev] => 24ef8b68e
[modified] => Tue, 04 Oct 2016 09:18:20 +0000
[mime_type] => text/plain
[path] => /test.txt
[is_dir] =>
[size] => 10 bytes
[root] => app_folder
[id] => id:VMaySA3Ug5AAAAAAAAAABA
[client_mtime] => Tue, 04 Oct 2016 09:18:20 +0000
[icon] => page_white_text
)
当用户点击链接并单击“允许”按钮时,将创建根 App 文件夹。