SOFTELメモ Developer's blog

会社概要 ブログ 調査依頼 採用情報 ...
技術者募集中

【php】DropboxのAPIをphpから使う

問題

DropboxのAPIをphpから使いたいです。

答え

file_get_contents関数でさくっと対応する例。

オフラインアクセスができるAPIキー(リフレッシュトークン)、アクセストークンは取得しているものとする。

/oauth2/token で、リフレッシュトークンからアクセストークンを再取得する

$data = http_build_query(array(
    'grant_type' => 'refresh_token',
    'refresh_token' => 'リフレッシュトークンは取得済みとする',
), '', '&');
$options = array(
    'http' => array(
        'ignore_errors' => true,
        'method' => 'POST',
        'header' => array(
            'Content-type: application/x-www-form-urlencoded',
            'Authorization: Basic ' . base64_encode(DROPBOX_APP_KEY . ':' . DROPBOX_APP_SECRET),
        ),
        'content' => $data,
    ),
);
$context = stream_context_create($options);
$response = json_decode(file_get_contents('https://api.dropbox.com/oauth2/token', false, $context));

//取得したかったアクセストークンはこちら
$access_token = $response->access_token;

/files/upload でファイルをアップロードする例

$access_token = 'アクセストークンは取得済みとする';
$pdf = file_get_contents('/PDFファイルの内容を/アップロードする場合.pdf');
$arg = json_encode(array(
    "autorename" => false,
    "mode" => "add",
    "mute" => false,
    "path" => "/hogehoge/fugafuga.pdf",
    "strict_conflict" => false,
));
$options = array(
    'http' => array(
        'ignore_errors' => true,
        'method' => 'POST',
        'header' => array(
            'Authorization: Bearer ' . $access_token,
            'Dropbox-API-Arg: ' . $arg,
            'Content-type: application/octet-stream',
        ),
        'content' => $pdf,
    ),
);
$context = stream_context_create($options);
$response = json_decode(file_get_contents('https://content.dropboxapi.com/2/files/upload', false, $context));

/sharing/create_shared_link_with_settings でファイルの共有リンクを取得する例

$arg = array(
    "path" => 'ファイルのIDかファイルのパス',
);
$options = array(
    'http' => array(
        'ignore_errors' => true,
        'method' => 'POST',
        'header' => array(
            'Authorization: Bearer ' . $access_token,
            'Content-type: application/json',
        ),
        'content' => json_encode($arg),
    ),
);
$context = stream_context_create($options);
$response = json_decode(file_get_contents('https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings', false, $context));

// 取得したかったURLはこちら
$url = $response->url;

関連するメモ

コメント