ITで遊ぶ

カラーミーAPIを使う(受注商品数)

いやぁ、やっとできた。
なによりもですねカラーミーいじりたおしさんに感謝。
ここのおかげでoAuthの認証を突破することができました。

なので詳細は書きません。
やったこと。

1. カラーミーデベロッパー登録

2. OAuthアプリケーション登録
ここではリダイレクトURLに認証プログラム(xxxx.php)を登録。
クライアントIDとクライアントシークレットをゲット

3. クライアントIDとクライアントシークレットを使って、認可コードを入手する
サンプルコードはアプリケーションのウェブサーバーのサンプルという、斜め上のタイトルのサンプル。
「カラーミーいじりたおし」先生のおっしゃるように、サンプルの最後に

echo $response_body;

を追加します。

なお、コードの中に’scope’という変数があります。ここでどういうAPIを使うかを決めておきます。

うまく動作すると

Notice: file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded in  ?(略)
{"access_token":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","token_type":"bearer","scope":"read_products write_products read_sales write_sales"}

っていうので認可コード(access_token)が帰ってきます。

4. あくまで参考ね、参考。これは私用ですから。。。

気づいたことは;

  • 取引データの終わりがわからない。ここでは40個ずつとってくるって指定して、かえってきたデータが40個なかったら終わり、と判断した。
  • いつからかfromで指定しないと、ここ一週間?しかもってこない。
  • file_get_contents関数はfalseにしておくと、$http_response_headerという配列で状況を返す。一応、実装した。
  • 一応、パソコンでもスマホでも妥当な大きさになるよにはした。
<?php

function set_up($code){
  $request_options = array(
    'http' => array(
        'method'  => 'GET',
        'header'=> 'Authorization: Bearer '.$code."rn",
        'ignore_errors' => true, // i want to get http status code.
    )
  );
  $context = stream_context_create($request_options);
  return $context;
}

function request_sales($context, $lines, $offset){
  $url = 'https://api.shop-pro.jp/v1/sales.json';
  // not sent, active, id, trans, offset
  $request = '?$request = '?delivered=false&canceled=false&after=2014-01-01&fields=id&limit='.$lines.'&offset='.$offset;
  $response_body = file_get_contents($url.$request, false, $context);
  
  $pos = strpos($http_response_header[0],'200');
  
  if ($pos === false ){ // usually don't come here.
    echo '<pre>'. print_r($response_body).'</pre>';
    return NULL;
  } else {
  
    $response_json =  json_decode($response_body, true);// associated array.

    return $response_json['sales'];

  }
} // end function.

function request_detail($context, $trxid){
  $detailist = array();
  $url = 'https://api.shop-pro.jp/v1/sales/' ;

  $request = $trxid . '.json';
  $response_body = file_get_contents($url.$request, false, $context);
  $response_json = json_decode($response_body, true);
  $details = $response_json['sale']['details'];
  
  $pos = strpos($http_response_header[0],'200');
  
  if ($pos === false ){ //usually we don't see this message.
    echo '<pre>'. print_r($response_json).'</pre>';
    return NULL;
  }else{
  
    foreach ($details as $key => $row){
      $detaillist[$row['product_name']] = $row['product_num'];
    }
    return $detaillist;
  }

} // end function.


//---- Main ----

header("Content-Type:text/html; charset=UTF-8"); // force chars UTF-8

$context = set_up('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');

// Phase 1: get trxs.
$offset = 0;
$lines = 40;
$trxids = array();
while(true){
  $salesdata = request_sales($context, $lines, $offset);

  foreach ($salesdata as $key => $row){
    array_push($trxids, $row['id'] );
  }

  if ( count($salesdata) < $lines ) { // may be last call.
    break;
  } else { // should get next entries
    $offset += $lines;
  }
}

// phase 2 : get each sales trx detail.
$productlist = array();

for ( $i = 0; $i < count($trxids); $i++){
  // get detail producs from eac transaction.
  $detaillines = request_detail( $context, $trxids[$i] );
  
  // merge each transaction into final one.
  foreach ($detaillines as $key => $row){

    if (array_key_exists( $key, $productlist) ){ // duplicate entry
      $productlist[$key]+= $row;

    } else { // first entry

      $productlist[$key] = $row; 

    }
  }
 
}
// print_r($productlist);

$today = date('Y年n月j日');
$now = date('H時i分');
?>
<html>
<head><title>調達製品リスト</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<style type="text/css">
body {
  -webkit-text-size-adjust: 100%;
}
</style>
</head>
<body>
<h1>調達製品リスト</h1>
<p align="right"><?= $today ?><?= $now ?></p>

<table border=1>
<tr><th>製品</th><th>個数</th></tr>
<? foreach ($productlist as $key => $row): ?>

  <tr><td><?= $key ?></td><td align="right"><?= $row?></td></tr>

<? endforeach; ?>
</table>
</body>
</html>

実行例:

result

関連記事

  1. Time MachineのバックアップをNASに取る

  2. WindowsXPサポート切れで恐怖心を煽るなよな

  3. GoogleスプレッドシートAPI Ver.3 一部翻訳

  4. htmlでframeを使ってはいけない?

  5. AO722にUbuntuを入れたら

  6. 消え行くSNS(Mixi,GREE)

  7. マックブック延命

  8. WindowsのTEMPは大事

記事をプリント