LoginSignup
0
0

More than 3 years have passed since last update.

PHPでSORACOM APIを呼び出す

Last updated at Posted at 2020-03-17

SORACOMのAPIをPHP(Guzzle)を使って呼び出してみます。

SAMを用意する

ユーザーコンソールからAPIを実行するためのSAM(SORACOM Access Management)ユーザーを用意します。

ユーザーを作成して権限設定、認証情報を作成しましょう。
AWSのIAMと同じような感じです。

発行した認証キーIDと認証キーシークレットはAPI呼び出しに必要になります。

PHPからAPIを呼び出す

Guzzleをインストール

HTTPクライアントのGuzzleをインストールします。

composer require guzzlehttp/guzzle

APIを呼び出す

最初にauthAPIに認証キーIDと認証キーシークレットを渡して、APIキーとAPIトークンを取得する必要があります。
他のAPIはすべて、取得したAPIキーとAPIトークンをリクエストヘッダに含めてリクエストしなければいけません。

下記のサンプルでは、最初にauthAPIを呼び出して次にLatestBillingAPIを呼び出しています。

exec.php
<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

const BASE_URL = 'https://api.soracom.io/v1/';

$credential = [
    'authKeyId' => 'keyId-************************',
    'authKey' => 'secret-*****************************************',
];

$httpClient = new Client();

// APIキーとAPIトークンを取得
$url = BASE_URL . 'auth';
try {
    $response = $httpClient->request('POST', $url, [
        'headers' => [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ],
        'json' => $credential,
    ]);
} catch (ClientException $e) {
    throw $e;
}
$body = $response->getBody();
$info = json_decode($body, true);
$apiKey = $info['apiKey'];
$operatorId = $info['operatorId'];
$userName = $info['userName'];
$token = $info['token'];

// LatestBillingAPIの呼び出し
$url = BASE_URL . 'bills/latest';
try {
    $response = $httpClient->request('GET', $url, [
        'headers' => [
            'Accept' => 'application/json',
            'X-Soracom-API-Key' => $apiKey,
            'X-Soracom-Token' => $token,
        ],
    ]);
} catch (ClientException $e) {
    throw $e;
}
$body = $response->getBody();
echo $body;

実行結果は次のようになります。

>php exec.php
{"lastEvaluatedTime":"20200317003205","amount":0}

参考

API リファレンス

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0