Class: TaobaoBy::Tbk

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTbk

Returns a new instance of Tbk.



16
17
18
19
20
# File 'lib/taobao_by.rb', line 16

def initialize
  @appkey = ENV['TBK_APPKEY']
  @secret = ENV['TBK_SECRET']
  @url = 'http://gw.api.taobao.com/router/rest'
end

Instance Attribute Details

#appkeyObject

Returns the value of attribute appkey.



12
13
14
# File 'lib/taobao_by.rb', line 12

def appkey
  @appkey
end

#secretObject

Returns the value of attribute secret.



13
14
15
# File 'lib/taobao_by.rb', line 13

def secret
  @secret
end

#urlObject

Returns the value of attribute url.



14
15
16
# File 'lib/taobao_by.rb', line 14

def url
  @url
end

Instance Method Details

#dg_material_optional(params) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/taobao_by.rb', line 22

def dg_material_optional(params)
  json = JSON.parse request('taobao.tbk.dg.material.optional', params)
  unless json['error_response'].nil?
    raise Error, json['error_response']['msg'] unless json['error_response']['code'].nil?
  end
  json['tbk_dg_material_optional_response']
end

#request(method, params) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/taobao_by.rb', line 30

def request(method, params)

  # 设置公共参数
  params[:app_key] = @appkey
  params[:method] = method
  params[:format] = 'json'
  params[:v] = '2.0'
  params[:timestamp] = Time.now.strftime('%F %T')
  params[:sign_method] = 'hmac'

  # 签名
  params[:sign] = OpenSSL::HMAC.hexdigest('MD5', @secret, params.sort.join).upcase

  # 发送请求
  url = URI(@url)
  http = Net::HTTP.new(url.host, url.port)
  request = Net::HTTP::Post.new(url)
  request['Content-Type'] = 'application/x-www-form-urlencoded'
  request.body = URI.encode_www_form(params)
  response = http.request(request)

  # 返回JSON数据
  response.read_body

end