PHPでBOXのAPIを呼び出す方法(その3:PHPプログラム作成)

PHPでBOXのAPIを呼び出し、BOXのファイルを検索するプログラムを作成する。

BOXアプリにファイルアップロード

BOXにログインし、ファイルアップロード

BOXにログイン後、左メニューの「管理コンソール」をクリック。

左メニューの「コンテンツ」から作成したアプリを右クリックして「ユーザーのアカウントにログインする」をクリック。

まだ何もアップロードしていないので空っぽの状態なのでファイルをアップする。

ファイルはなんでもよいのだが、例えば以下のサイトからエクセルファイルを適当にダウンロードしておく。

■総務省|令和2年版 情報通信白書|情報通信機器の保有状況
https://www.soumu.go.jp/johotsusintokei/whitepaper/ja/r02/html/nd252110.html

フォルダ構造を作り、フォルダごとアップロードする。

BOXがインデックスを作成するのに時間がかかるため、しばらく待つ。

「パソコン」で検索し、検索結果が表示されていればインデックスが作成されている。

APIを呼び出す

以下のAPIリファレンスを見ながら検索処理を実装する。

■コンテンツを検索 – APIリファレンス – Box開発者向けドキュメントポータル
https://ja.developer.box.com/reference/get-search/

以下のGuzzleのAPIリファレンスも参考まで。

■Request Options — Guzzle Documentation
https://docs.guzzlephp.org/en/stable/request-options.html

ダウンロードしたJSONファイルを同じディレクトリに置いておくこと(※言わずもがな本番では公開ディリクトリに置かないこと)。

<?php
require __DIR__ . '/vendor/autoload.php';
$json = file_get_contents('952190543_4afdcca9_config.json');
$config = json_decode($json);

$private_key = $config->boxAppSettings->appAuth->privateKey;
$passphrase = $config->boxAppSettings->appAuth->passphrase;
$key = openssl_pkey_get_private($private_key, $passphrase);

$authenticationUrl = 'https://api.box.com/oauth2/token';

$claims = [
  'iss' => $config->boxAppSettings->clientID,
  'sub' => $config->enterpriseID,
  'box_sub_type' => 'enterprise',
  'aud' => $authenticationUrl,
  'jti' => base64_encode(random_bytes(64)),
  'exp' => time() + 45,
  'kid' => $config->boxAppSettings->appAuth->publicKeyID
];

use \Firebase\JWT\JWT;
$assertion = JWT::encode($claims, $key, 'RS512');

use GuzzleHttp\Client;

$params = [
  'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
  'assertion' => $assertion,
  'client_id' => $config->boxAppSettings->clientID,
  'client_secret' => $config->boxAppSettings->clientSecret
];

$client = new Client();
$response = $client->request('POST', $authenticationUrl, [
  'form_params' => $params
]);

$data = $response->getBody()->getContents();
$accessToken = json_decode($data)->access_token;

// https://ja.developer.box.com/reference/get-search/
$query = '電気';
$url = 'https://api.box.com/2.0/search?query='.$query;
$headers = array(
  'Authorization' => 'Bearer ' . $accessToken,
);
$client = new Client();
$response = $client->request('GET', $url, array(
  'headers' => $headers,
));
$contents = json_decode($response->getBody()->getContents(), true);
$contents_kensu = count($contents['entries']);
$total_count = $contents['total_count'];

print($contents_kensu . "/" . $total_count);

?>

以下のように表示されればOK。

取得した結果をループして表示してみる。

<?php
require __DIR__ . '/vendor/autoload.php';
$json = file_get_contents('952190543_4afdcca9_config.json');
$config = json_decode($json);

$private_key = $config->boxAppSettings->appAuth->privateKey;
$passphrase = $config->boxAppSettings->appAuth->passphrase;
$key = openssl_pkey_get_private($private_key, $passphrase);

$authenticationUrl = 'https://api.box.com/oauth2/token';

$claims = [
  'iss' => $config->boxAppSettings->clientID,
  'sub' => $config->enterpriseID,
  'box_sub_type' => 'enterprise',
  'aud' => $authenticationUrl,
  'jti' => base64_encode(random_bytes(64)),
  'exp' => time() + 45,
  'kid' => $config->boxAppSettings->appAuth->publicKeyID
];

use \Firebase\JWT\JWT;
$assertion = JWT::encode($claims, $key, 'RS512');

use GuzzleHttp\Client;

$params = [
  'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
  'assertion' => $assertion,
  'client_id' => $config->boxAppSettings->clientID,
  'client_secret' => $config->boxAppSettings->clientSecret
];

$client = new Client();
$response = $client->request('POST', $authenticationUrl, [
  'form_params' => $params
]);

$data = $response->getBody()->getContents();
$accessToken = json_decode($data)->access_token;

// https://ja.developer.box.com/reference/get-search/
$query = '世帯保有率';
$url = 'https://api.box.com/2.0/search?query='.$query;
$headers = array(
  'Authorization' => 'Bearer ' . $accessToken,
);
$client = new Client();
$response = $client->request('GET', $url, array(
  'headers' => $headers,
));
$contents = json_decode($response->getBody()->getContents(), true);
$contents_kensu = count($contents['entries']);
$total_count = $contents['total_count'];

$honbun = '「' . $query . '」で検索した結果:' . $contents_kensu . '/' . $total_count;
print('<html><body><h1>' . $honbun . '</h1><ul>');

$count = 1;
foreach ($contents['entries'] as $content) {
  /* for debug フォルダ配下のitemsを取得した場合
  print_r($content);
  ↓ディレクトリの場合
  Array ( 
    [type] => folder 
    [id] => 151836977485 [sequence_id] => 0 [etag] => 0 [name] => フォルダA 
  )
  ↓ファイルの場合
  Array
  (
      [type] => file
      [id] => 123456789012
      [file_version] => Array
          (
              [type] => file_version
              [id] => 123456789012
              [sha1] => 85ac014aceac01d334e590761ac56c6d3e9241ac
          )

      [sequence_id] => 2
      [etag] => 2
      [sha1] => 85a301dbc4a431c2945e90461cc5ac6b7e97463c
      [name] => aaa.xls
  )
  */
  print('<li>');
  print($count . ' : ' . $content['type'] . ' - ' . $content['name']);
  print('</li>');
  $count = $count + 1;
} // end of Loop
print('</ul></body></html>');

?>

以下のように表示される。

他にもファイルのアップロード・ダウンロードも可能である。今回PHPで実装したが、Pythonでも実装できるようである。そのため、Lambdaを使ってサーバレス環境でBOXの検索も比較的簡単に実現できそうだ。