5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

カラーミーAPIを利用して商品一覧のjsonを取得する

Posted at

「カラーミーAPI」を利用して、
カラーミーで作ったショップの全商品一覧および各商品の詳細を、
別サーバー(ここではheteml)にjsonとして保存した時のソースコードです。
以下のようなコードをhetemlのweb以下に「products.php」として置き、
cronで10分ごとに動かし、
同ディレクトリに「cache.json」として保存します。

# !/usr/local/php/7.3/bin/php
<?php
$request_options = array(
  'http' => array(
  'method' => 'GET',
  'header'=> "Authorization: Bearer オーソリゼーションコードだよ〜\r\n"
  )
);
//アクセストークンなどAPI取得に必要な情報だよ
$context = stream_context_create($request_options);
//商品一覧を取得する
//先に商品が全部でいくつあるか取得する
$url = 'https://api.shop-pro.jp/v1/products.json'; //あとでoffsetで51件目以降の処理を作る
$response_body = file_get_contents($url, false, $context);//API取得に必要な情報を一緒に送る
$response_body = json_decode($response_body, true);
$all_the_products_num = $response_body["meta"]["total"];
//次に、1-50件、51-100件、と回していく
for($i = 0; $i < $all_the_products_num; $i++){
  $key_num = $i%50;
  if($i%50 == 1){
    $url = 'https://api.shop-pro.jp/v1/products.json?limit=50&offset='.($i-1);
    $response_body = file_get_contents($url, false, $context);
    $response_body = json_decode($response_body, true);
  }
  $product_ids[$i] = $response_body["products"][$i%50]["id"];
}
//productIDの一覧ができたので、それをもとに商品詳細のapiを叩く
$tmp .= "{\"product\":[";
for($i = 0; $i < count($product_ids); $i++){
    $url = 'https://api.shop-pro.jp/v1/products/'.$product_ids[$i].'.json';
    $response_body = file_get_contents($url, false, $context);//API取得に必要な情報を一緒に送る
    $result = json_decode($response_body);
    $tmp .= json_encode($result->{"product"});
    if($i != count($product_ids)-1){
      $tmp .= ",";
    }
}
$tmp .= "]}";
$file = '書き出し先のhetemlの絶対パス/cache.json';
// ファイルをオープンして既存のコンテンツを取得します
$current = file_get_contents($file);
// 結果をファイルに書き出します
file_put_contents($file, $tmp);
?>
5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?