Shopify自定义应用创建草稿订单时遇商品变体未找到API错误
问题
开发Shopify自定义应用时,创建草稿订单遇到API错误:
{ "errors": { "base": [ "The merchandise variant referenced by this term condition could not be found." ] } }
代码实现如下:
# Create a Shopify session access_token = '<ACCESS_TOKEN>' shop_url = "<URL>" # session = shopify.Session(cart.storeId, GLOBAL_SHOPIFY_API_VERSION, access_token) # shopify.ShopifyResource.activate_session(session) # # Create a new draft order # new_draft_order = shopify.DraftOrder() # new_draft_order.line_items = { # "variant_id": cart.cartItem.get("variantId"), # "quantity": cart.cartItem.get("quantity") # } # await new_draft_order.save() # Set the headers and the data for the request headers = { 'X-Shopify-Access-Token': access_token, 'Content-Type': 'application/json', } json_data = { 'draft_order': { 'line_items': [ { 'varianct_id': cart.cartItem.get("variantId"), 'quantity': cart.cartItem.get("quantity"), }, ], }, } response = requests.post( f'https://{shop_url}/admin/api/{GLOBAL_SHOPIFY_API_VERSION}/draft_orders.json', headers=headers, json=json_data, ) # Check if the request was successful if response.status_code == 200: return response.json() if response.status_code == 202: return response.json() return response.json()
已确认API访问令牌有效,且Variant ID可在Shopify平台正常查看,但仍触发该错误,求解决方案。
解决方案
- 修复字段拼写错误:代码中
json_data里的varianct_id是拼写错误,正确字段名为variant_id。拼写错误会导致Shopify API无法识别变体引用,直接触发错误。修正后代码片段:'line_items': [ { 'variant_id': cart.cartItem.get("variantId"), 'quantity': cart.cartItem.get("quantity"), }, ], - 确认Variant ID类型:确保
cart.cartItem.get("variantId")返回整数类型,而非字符串。Shopify API要求variant_id为数值,可显式转换类型:'variant_id': int(cart.cartItem.get("variantId")), - 验证变体归属与状态:确认该Variant ID属于当前请求的店铺,且变体处于活跃状态(未被删除或设置为不可销售)。
- 检查API权限与版本:确保访问令牌拥有
write_draft_orders权限,且使用的GLOBAL_SHOPIFY_API_VERSION为Shopify当前支持的稳定版本。
内容的提问来源于stack exchange,提问作者Prakhar Rathi
相关产品推荐
相关产品推荐

