python
import requests
import json
class AlibabaProductAPI:
def __init__(self, app_key, app_secret):
self.app_key = app_key
self.app_secret = app_secret
self.api_url = "https://api.1688.com/router/rest"
def get_access_token(self):
url = "https://oauth.taobao.com/token"
params = {
"grant_type": "client_credential",
"client_id": self.app_key,
"client_secret": self.app_secret,
"scope": "item_detail"
}
response = requests.get(url, params=params)
return response.json()["access_token"]
def get_product_detail(self, product_id, language="en"):
access_token = self.get_access_token()
params = {
"method": "alibaba.product.get",
"app_key": self.app_key,
"timestamp": "2025-11-07 15:59:14", # 动态生成当前时间
"format": "json",
"v": "2.0",
"product_id": product_id,
"language": language,
"access_token": access_token
}
# 生成签名(需按ASCII码排序参数并拼接AppSecret)
sorted_params = sorted(params.items(), key=lambda x: x[0])
query_string = "&".join([f"{k}={v}" for k, v in sorted_params])
sign_str = self.app_secret + query_string + self.app_secret
import hashlib
import hmac
signature = hmac.new(
self.app_secret.encode('utf-8'),
sign_str.encode('utf-8'),
hashlib.sha1
).hexdigest().upper()
params["sign"] = signature
response = requests.get(self.api_url, params=params)
data = response.json()
if "error_response" in data:
raise Exception(f"API Error: {data['error_response']['msg']}")
return data["alibaba_product_get_response"]["product"]
# 示例调用
api = AlibabaProductAPI("YOUR_APPKEY", "YOUR_APPSECRET")
product_data = api.get_product_detail("123456789", "en")
print(f"Title: {product_data['title']}")
print(f"Price: {product_data['priceInfo']['price']}")