5
4

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 5 years have passed since last update.

node.jsを試した(EコマースAPI)②

Last updated at Posted at 2014-03-05

前回に加えSignature発行が必要な セブンアフィリエイトAPIの通信モジュールについて書きたいと思います。

common.js

var http        = require('http')
,querystring  = require('querystring')
,xml2js = require('xml2js')
,crypto = require('crypto');

function common(path)
{
  this.host = 'api.7netshopping.jp';
  this.path = path;
  this.secret_key = '発行した鍵';

  // Default Options
  this.options = function(){
    return {ApiUserId: '登録ユーザーID'
    ,Timestamp: null
    ,Version:'2010-08-01'
    ,ResponseFormat: 'JSON'};
  };

  Date.prototype.toUTCString = function(){
      return [
          this.getUTCFullYear(),
          this.getUTCMonth() + 1,
          this.getUTCDate()
          ].join( '-' ) + 'T'
          + [
             this.getUTCHours(),
             this.getUTCMinutes(),
             this.getUTCSeconds()
          ].join( ':' ) + 'Z'
  }
}

common.prototype = {

  generateURL: function (addOptions) {
    var options = this.options();
    for(var key in addOptions){
      options[key] = addOptions[key];
    }
    options['Timestamp'] = new Date().toUTCString();
    options['Signature'] = createSignature('http://' +this.host + this.path, options, this.secret_key);
    var url = 'http://' +this.host + this.path + '?' +
          require('querystring').stringify(options);
    console.log(url);
    return url;
  },

  get: function (options, callback) {
        var req = http.get(this.generateURL(options), function(res){
            res.setEncoding('utf8');
            var data = '';
            res.on('data', function(str) {data += str;});
            res.on('end',function(){
                callback(JSON.parse(data));
            });
        });
   },
};

var createSignature = function(url, request, secret_key){
    var str = "GET|" + url;
    keys = Object.keys(request);
    keys.sort();
    for ( var i = 0; i < keys.length; i++) {
         str += "|"  + keys[i] + "=" + request[keys[i]];
    }
    str = encodeURIComponent(str);

    return crypto.createHmac('sha256', secret_key).update(str).digest('base64');
}

module.exports = common;

amazonのapiと認証方式とだいぶ似てるので、コピペ可能かと。
(自作せずとも、node-apacというモジュールでamazonAPIが使えます。)
UTC形式のタイムスタンプが必要なので、強引にDateクラスのtoUTCStringをねじ込んでます。
肝心の Signatureの発行ですが、node-cryptoを利用すれば簡単です。

後は、これに各api用のクラスを作成しましょう。

SearchProduct.js

var common = require('./common.js');

function api () {
    //このパス部分を各apiにて書き換える
    common.apply(this, ['/ws/affiliate/rest/SearchProduct']);
}
api.prototype = Object.create(common.prototype);
api.prototype.constructor = api;

api.prototype.execute = function(obj, callback){
  this.get(obj, callback);
}

後は、これに検索条件であるリクエストを渡して実行

使い方
module.exports = api;
var api = require('./SearchProduct.js');
// カテゴリ「rock」で検索
new api().execute({CategoryCode: 'rock'},function(res){console.log(res.SearchProductResponse.Products.Product);});

後で、API絡みのモジュールはgithubでも登録しておこう。

5
4
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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?