Class: Topsdk::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/topsdk/client.rb

Constant Summary collapse

DEBUG =
false

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Client

Returns a new instance of Client.



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/topsdk/client.rb', line 10

def initialize(params={})
  @params = { # 淘宝参数
    :app_key => ENV['TAOBAO_APP_KEY'],
    :format => :json, 
    :v => '2.0',
    :timestamp => timestamp
  }
  @params.merge!(params.clone) unless params.empty? # 參數合併
  @params[:sign] = generate_sign(@params)
  pp @params if DEBUG
end

Instance Method Details

#generate_sign(params = {}) ⇒ Object



53
54
55
56
# File 'lib/topsdk/client.rb', line 53

def generate_sign(params={})
  rand = ENV['TAOBAO_APP_SECRET'] + params.sort.flatten.join
  Digest::MD5.hexdigest(rand).upcase! # 數字簽名
end

#get(url = ) ⇒ Object



22
23
24
25
26
27
28
29
30
31
# File 'lib/topsdk/client.rb', line 22

def get(url=ENV['TAOBAO_REST_URL'])
  format = if @params.has_key?(:method) && ENV['TAOBAO_XML_ONLY'].include?(@params[:method]) # 淘寶接口格式限制
     :xml 
   else
    :json 
  end
  request = Nestful::Request.new(url, ({:method => :get, :format => format, :params => @params}))
  @result = request.execute
  parse
end

#parseObject

簡單解析一下



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/topsdk/client.rb', line 40

def parse # 簡單解析一下
  return false unless @result.is_a?(Hash)
  case
  when @result.has_key?(response_key)
    pp response_key if DEBUG
    result = @result[response_key]
  when @result.has_key?('error_response')
    @result['error_response']['msg']
  else
    @result
  end
end

#post(url = ) ⇒ Object



33
34
35
36
37
38
# File 'lib/topsdk/client.rb', line 33

def post(url=ENV['TAOBAO_REST_URL'])
  request = Nestful::Request.new(url, ({:method => :post, :format => :form, :params => @params}))
  @result = request.execute
  @result = JSON.parse(@result)
  parse
end

#response_keyObject

操作結果鍵



58
59
60
# File 'lib/topsdk/client.rb', line 58

def response_key # 操作結果鍵
  @params[:method][7..-1].gsub(/\./, '_') + "_response" unless  @params[:method].nil?
end

#root_keyObject

獲取對象的鍵



62
63
64
# File 'lib/topsdk/client.rb', line 62

def root_key # 獲取對象的鍵
  response_key.split('_')[0] unless  @params[:method].nil?
end

#timestampObject

时间戳



66
67
68
# File 'lib/topsdk/client.rb', line 66

def timestamp # 时间戳
  Time.now.strftime("%Y-%m-%d %H:%M:%S")
end