/
amazon_mws.rb
407 lines (341 loc) · 13.5 KB
/
amazon_mws.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
require 'base64'
require 'openssl'
require 'time'
require 'cgi'
module ActiveMerchant
module Fulfillment
class AmazonMarketplaceWebService < Service
APPLICATION_IDENTIFIER = "active_merchant_mws/0.01 (Language=ruby)"
SIGNATURE_VERSION = 2
SIGNATURE_METHOD = "SHA256"
VERSION = "2010-10-01"
SUCCESS, FAILURE, ERROR = 'Accepted', 'Failure', 'Error'
MESSAGES = {
:status => {
'Accepted' => 'Success',
'Failure' => 'Failed',
'Error' => 'An error occurred'
},
:create => {
'Accepted' => 'Successfully submitted the order',
'Failure' => 'Failed to submit the order',
'Error' => 'An error occurred while submitting the order'
},
:list => {
'Accepted' => 'Successfully submitted request',
'Failure' => 'Failed to submit request',
'Error' => 'An error occurred while submitting request'
}
}
ENDPOINTS = {
:ca => 'mws.amazonservices.ca',
:cn => 'mws.amazonservices.com.cn',
:de => 'mws-eu.amazonservices.ca',
:es => 'mws-eu.amazonservices.ca',
:fr => 'mws-eu.amazonservices.ca',
:it => 'mws-eu.amazonservices.ca',
:jp => 'mws.amazonservices.jp',
:uk => 'mws-eu.amazonservices.ca',
:us => 'mws.amazonservices.com'
}
LOOKUPS = {
:destination_address => {
:name => "DestinationAddress.Name",
:address1 => "DestinationAddress.Line1",
:address2 => "DestinationAddress.Line2",
:city => "DestinationAddress.City",
:state => "DestinationAddress.StateOrProvinceCode",
:country => "DestinationAddress.CountryCode",
:zip => "DestinationAddress.PostalCode"
},
:line_items => {
:comment => "Item.member.%d.DisplayableComment",
:gift_message => "Item.member.%d.GiftMessage",
:currency_code => "Item.member.%d.PerUnitDeclaredValue.CurrencyCode",
:value => "Item.member.%d.PerUnitDeclaredValue.Value",
:quantity => "Item.member.%d.Quantity",
:order_id => "Item.member.%d.SellerFulfillmentOrderItemId",
:sku => "Item.member.%d.SellerSKU",
:network_sku => "Item.member.%d.FulfillmentNetworkSKU",
:item_disposition => "Item.member.%d.OrderItemDisposition"
},
:list_inventory => {
:sku => "SellerSkus.member.%d"
}
}
ACTIONS = {
:outbound => "FulfillmentOutboundShipment",
:inventory => "FulfillmentInventory"
}
OPERATIONS = {
:outbound => {
:status => 'GetServiceStatus',
:create => 'CreateFulfillmentOrder',
:list => 'ListAllFulfillmentOrders',
:tracking => 'GetFulfillmentOrder'
},
:inventory => {
:get => 'ListInventorySupply',
:list => 'ListInventorySupply',
:list_next => 'ListInventorySupplyByNextToken'
}
}
# The first is the label, and the last is the code
# Standard: 3-5 business days
# Expedited: 2 business days
# Priority: 1 business day
def self.shipping_methods
[
[ 'Standard Shipping', 'Standard' ],
[ 'Expedited Shipping', 'Expedited' ],
[ 'Priority Shipping', 'Priority' ]
].inject(ActiveSupport::OrderedHash.new){|h, (k,v)| h[k] = v; h}
end
def self.sign(aws_secret_access_key, auth_string)
Base64.encode64(OpenSSL::HMAC.digest(@@digest, aws_secret_access_key, auth_string)).strip
end
def initialize(options = {})
requires!(options, :login, :password)
options
super
end
def seller_id=(seller_id)
@seller_id = seller_id
end
def endpoint
ENDPOINTS[@options[:endpoint] || :us]
end
def fulfill(order_id, shipping_address, line_items, options = {})
requires!(options, :order_date, :comment, :shipping_method)
commit :post, :outbound, :create, build_fulfillment_request(order_id, shipping_address, line_items, options)
end
def status
commit :post, :outbound, :status, build_status_request
end
def fetch_current_orders
commit :post, :outbound, :status, build_get_current_fulfillment_orders_request
end
def fetch_stock_levels(options = {})
if options[:sku]
commit :post, :inventory, :get, build_get_current_fulfillment_orders_request(options)
else
response = commit :post, :inventory, :list, build_inventory_list_request(options)
while token = response.params['next_token'] do
next_page = commit :post, :inventory, :list_next, build_next_inventory_list_request(token)
next_page.stock_levels.merge!(response.stock_levels)
response = next_page
end
response
end
end
def fetch_tracking_numbers(order_ids, options = {})
order_ids.reduce(nil) do |previous, order_id|
response = commit :post, :outbound, :tracking, build_tracking_request(order_id, options)
if !response.success?
if response.faultstring.match(/^Requested order \'[A-Za-z0-9]+\' not found$/)
response = Response.new(true, nil, {
:status => SUCCESS,
:tracking_numbers => {}
})
else
return response
end
end
response.tracking_numbers.merge!(previous.tracking_numbers) if previous
response
end
end
def commit(verb, service, op, params)
uri = URI.parse("https://#{endpoint}/#{ACTIONS[service]}/#{VERSION}")
signature = sign(verb, uri, params)
query = build_query(params) + "&Signature=#{signature}"
headers = build_headers(query)
data = ssl_post(uri.to_s, query, headers)
response = parse_response(service, op, data)
Response.new(success?(response), message_from(response), response)
rescue ActiveMerchant::ResponseError => e
response = parse_error(e.response)
Response.new(false, message_from(response), response)
end
def success?(response)
response[:response_status] == SUCCESS
end
def message_from(response)
response[:response_message]
end
## PARSING
def parse_response(service, op, xml)
begin
document = REXML::Document.new(xml)
rescue REXML::ParseException
return { :success => FAILURE }
end
case service
when :outbound
case op
when :tracking
parse_tracking_response(document)
else
parse_fulfillment_response(op, document)
end
when :inventory
parse_inventory_response(document)
else
raise ArgumentError, "Unknown service #{service}"
end
end
def parse_tracking_response(document)
response = {}
response[:tracking_numbers] = {}
tracking_node = REXML::XPath.first(document, "//FulfillmentShipmentPackage/member/TrackingNumber")
if tracking_node
id_node = REXML::XPath.first(document, "//FulfillmentOrder/SellerFulfillmentOrderId")
response[:tracking_numbers][id_node.text.strip] = tracking_node.text.strip
end
response[:response_status] = SUCCESS
response
end
def parse_fulfillment_response(op, document)
response = {}
action = OPERATIONS[:outbound][op]
node = REXML::XPath.first(document, "//#{action}Response")
response[:response_status] = SUCCESS
response[:response_comment] = MESSAGES[op][SUCCESS]
response
end
def parse_inventory_response(document)
response = {}
response[:stock_levels] = {}
document.each_element('//InventorySupplyList/member') do |node|
params = node.elements.to_a.each_with_object({}) { |elem, hash| hash[elem.name] = elem.text }
response[:stock_levels][params['SellerSKU']] = params['TotalSupplyQuantity'].to_i
end
next_token = REXML::XPath.first(document, '//NextToken')
response[:next_token] = next_token ? next_token.text : nil
response[:response_status] = SUCCESS
response
end
def parse_error(http_response)
response = {}
response[:http_code] = http_response.code
response[:http_message] = http_response.message
document = REXML::Document.new(http_response.body)
node = REXML::XPath.first(document, '//Error')
error_code = REXML::XPath.first(node, '//Code')
error_message = REXML::XPath.first(node, '//Message')
response[:response_status] = FAILURE
response[:faultcode] = error_code ? error_code.text : ""
response[:faultstring] = error_message ? error_message.text : ""
response[:response_comment] = "#{response[:error_code]}: #{response[:error_message]}"
response
rescue REXML::ParseException => e
rescue NoMethodError => e
response[:http_body] = http_response.body
response[:response_status] = FAILURE
response[:response_comment] = "#{response[:http_code]}: #{response[:http_message]}"
response
end
def sign(http_verb, uri, options)
opts = build_basic_api_query(options)
string_to_sign = "#{http_verb.to_s.upcase}\n"
string_to_sign += "#{uri.host}\n"
string_to_sign += uri.path.length <= 0 ? "/\n" : "#{uri.path}\n"
string_to_sign += build_query(options)
# remove trailing newline created by encode64
escape(Base64.encode64(OpenSSL::HMAC.digest(SIGNATURE_METHOD, @options[:password], string_to_sign)).chomp)
end
def md5_content(content)
Base64.encode64(OpenSSL::Digest::Digest.new('md5', content).digest).chomp
end
def build_query(query_params)
query_params.sort.map{ |key, value| [escape(key.to_s), escape(value.to_s)].join('=') }.join('&')
end
def build_headers(querystr)
{
'User-Agent' => APPLICATION_IDENTIFIER,
'Content-MD5' => md5_content(querystr),
'Content-Type' => 'application/x-www-form-urlencoded'
}
end
def build_basic_api_query(options)
opts = Hash[options.map{ |k,v| [k.to_s, v.to_s] }]
opts["AWSAccessKeyId"] = @options[:login] unless opts["AWSAccessKey"]
opts["Timestamp"] = Time.now.utc.iso8601 unless opts["Timestamp"]
opts["Version"] = VERSION unless opts["Version"]
opts["SignatureMethod"] = "Hmac#{SIGNATURE_METHOD}" unless opts["SignatureMethod"]
opts["SignatureVersion"] = SIGNATURE_VERSION unless opts["SignatureVersion"]
opts["SellerId"] = @seller_id unless opts["SellerId"] || !@seller_id
opts
end
def build_fulfillment_request(order_id, shipping_address, line_items, options)
params = {
:Action => OPERATIONS[:outbound][:create],
:SellerFulfillmentOrderId => order_id.to_s,
:DisplayableOrderId => order_id.to_s
}
request = build_basic_api_query(params.merge(options))
request.merge build_address(shipping_address)
request.merge build_items(line_items)
request
end
def build_get_current_fulfillment_orders_request(options = {})
start_time = options.delete(:start_time) || 1.day.ago.utc
params = {
:Action => OPERATIONS[:outbound][:list],
:QueryStartDateTime => start_time.strftime("%Y-%m-%dT%H:%M:%SZ")
}
build_basic_api_query(params.merge(options))
end
def build_inventory_list_request(options = {})
start_time = options.delete(:start_time) || 1.day.ago
response_group = options.delete(:response_group) || "Basic"
params = {
:Action => OPERATIONS[:inventory][:list],
:ResponseGroup => response_group
}
if skus = options.delete(:skus)
skus.each_with_index do |sku, index|
params[LOOKUPS[:list_inventory][:sku] % (index + 1)] = sku
end
else
params[:QueryStartDateTime] = options.delete(:start_time) || 1.day.ago
end
build_basic_api_query(params.merge(options))
end
def build_next_inventory_list_request(token)
params = {
:NextToken => token
}
build_basic_api_query(params)
end
def build_tracking_request(order_id, options)
params = {:Action => OPERATIONS[:outbound][:tracking], :MerchantFulfillmentOrderId => order_id}
build_basic_api_query(params.merge(options))
end
def build_address(address)
requires!(address, :name, :address1, :city, :state, :country, :zip)
ary = address.map{ |key, value|
[escape(LOOKUPS[:destination_address][key]), escape(value.to_s)]
}
Hash[ary]
end
def build_items(line_items)
counter = 0
line_items.reduce({}) do |items, line_item|
counter += 1
line_item.keys.reduce(items) do |hash, key|
entry = escape(LOOKUPS[:line_items][key] % counter)
hash[entry] = escape(line_item[key].to_s)
hash
end
end
end
def build_status_request
build_basic_api_query({ :Action => OPERATIONS[:outbound][:status] })
end
def escape(str)
CGI.escape(str).gsub('+', '%20')
end
end
end
end