ShopifyとEC運営の基幹に据えて、ShopifyもAmazonも配送はFBAにしている。小規模ならそんなEC運用も可能です。大事なのは自社の規模にあったEC運用をすること。
EC事業開始直後で売上が小さいうちは、一元管理ツールなどへの先行投資をしぶりがち。とはいえ、在庫管理ができていないとクレームや売上機会の損失になり得るので、例え一元管理ツールを使わないにしても、在庫連携くらいはしておくべきだろう。
今回はPythonとGraphQLを使ってShopifyの在庫をAmazonに連携する方法を紹介する。前提として、ShopifyのSKUとAmazonのSKUが一致していることが、在庫連携の必須条件だ。
def get_inventory_item_ids():
"""
Shopifyより在庫を取得
"""
token = 'hogehoge'
shop_url = 'hogehoge'
pagenation_url = None #初回リクエスト時はNone
limit = 250 #一度に在庫取得する商品数の上限。これ以上の場合は繰り返し処理が必要
headers = {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': token,
}
cursor = pagenation_url
data = '{ inventoryItems(first: ' + str(limit) + ','
if cursor != None:
data += 'after: ' + '"' + cursor + '"'
data += ''') {
edges {
#cursor
node {
id
sku
}
}
pageInfo{
hasNextPage
endCursor
}
}
}'''
url = 'https://' + shop_url + '.myshopify.com/admin/api/2023-01/graphql.json'
response = requests.post(url, headers=headers, json={'query': data})
if response.status_code == 200:
json_data = json.loads(response.text)
取得したShopifyの在庫情報はJsonやDB、CSVなど環境に応じて保存または維持する。次にAmazonへ在庫を反映する。Amazonへの在庫反映はlistings APIを使う。
def put_item_stock(inventory_data):
"""
listing APIで在庫更新 path
inventory_data : {"sku": "hogehoge", "quantity": 23}
"""
seller_id = 'hogehoge' #
produc_type = 'PRODUCT'
MarketplaceIds = 'hogehoge'
method = 'PATCH'
canonical_uri = '/listings/2021-08-01/items/' + seller_id + '/' + inventory_data['sku']
endpoint = 'https://sellingpartnerapi-fe.amazon.com' + canonical_uri
#patchするデータの作成
patches = []
patch_operation = {}
patch_operation['op'] = 'replace'
patch_operation['path'] = '/attributes/fulfillment_availability'
patch_operation['value'] = [
{ 'fulfillment_channel_code': 'DEFAULT',
'quantity': inventory_data['quantity'],
}
]
patches.append(patch_operation)
patch_data = {
'productType': product_type, #The Amazon product type of the listings item.
'patches': patches, #One or more JSON Patch operations to perform on the listings item.
}
request_parameters_unencode = {
'marketplaceIds':MarketplaceIds,
}
request_parameters = urllib.parse.urlencode(sorted(request_parameters_unencode.items()))
request_url = endpoint + '?' + request_parameters
body_data = json.dumps(patch_data)
headers = {'x-amz-access-token': token,
'user-agent': user_agent,
'Content-Type': content_type,
'X-Amz-Date': amz_date,
'Authorization': authorization_header
}
#patchでリクエスト
response = requests.patch(request_url, data=body_data, headers=headers)
return response




