feat: implement backend API clients for multi-marketplace integration and frontend service layer

This commit is contained in:
2026-05-12 13:16:14 +03:00
parent 6974af486a
commit ee39a3d83b
65 changed files with 2501 additions and 33 deletions

View File

@@ -0,0 +1,15 @@
from .client import AEClient
from .services.transactions import TransactionsService
from .services.products import ProductsService
class AliExpressAPI:
"""
Main entry point for AE Platform (AliExpress Russia) SDK.
Instantiates all services with a shared client.
"""
def __init__(self, api_token: str = None, user_id: str = None):
self.client = AEClient(api_token, user_id)
# Initialize services
self.transactions = TransactionsService(self.client)
self.products = ProductsService(self.client)

76
backend/ae_api/client.py Normal file
View File

@@ -0,0 +1,76 @@
import os
import requests
import time
from typing import Dict, Any, Optional
from .exceptions import AEAPIError, AEAuthError, AERateLimitError, AEBadRequestError, AENotFoundError
class AEClient:
"""Base client for interacting with AE Platform API."""
BASE_URL = "https://api2.aeplatform.ru/api/v1"
def __init__(self, api_token: Optional[str] = None, user_id: Optional[str] = None):
# Fetch from env if not provided
self.api_token = api_token or os.getenv('AE_API_TOKEN')
self.user_id = user_id or os.getenv('AE_USER_ID')
if not self.api_token:
raise ValueError("AE_API_TOKEN must be provided")
self.session = requests.Session()
# AE Platform API requires JWT token and locale
self.session.headers.update({
"Authorization": self.api_token, # Token from documentation is passed directly in Authorization header
"x-request-locale": "ru_RU",
"Content-Type": "application/json"
})
def request(self, method: str, path: str, data: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, Any]] = None, retries: int = 3) -> Dict[str, Any]:
"""Perform HTTP request to AE Platform API with automatic retries."""
url = f"{self.BASE_URL}{path}"
for attempt in range(retries):
try:
response = self.session.request(method, url, json=data, params=params)
# Check rate limiting
if response.status_code == 429:
if attempt < retries - 1:
time.sleep(2 ** attempt) # Exponential backoff
continue
raise AERateLimitError("Rate limit exceeded")
if response.status_code in (401, 403):
raise AEAuthError(f"Authentication failed: {response.text}")
if response.status_code in (400, 422):
raise AEBadRequestError(f"Bad Request / Unprocessable Entity: {response.text}")
if response.status_code == 404:
raise AENotFoundError(f"Not Found: {response.text}")
response.raise_for_status()
if response.content:
try:
return response.json()
except ValueError:
return {"status": "success", "text": response.text}
return {}
except requests.exceptions.RequestException as e:
if attempt < retries - 1:
time.sleep(2 ** attempt)
continue
raise AEAPIError(f"Request failed: {str(e)}")
raise AEAPIError("Request failed after max retries")
def post(self, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
return self.request("POST", path, data=data)
def get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
return self.request("GET", path, params=params)
def put(self, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
return self.request("PUT", path, data=data)

View File

@@ -0,0 +1,19 @@
class AEAPIError(Exception):
"""Base exception for all AE Platform API errors."""
pass
class AEAuthError(AEAPIError):
"""Raised when authentication fails (HTTP 401 or 403)."""
pass
class AERateLimitError(AEAPIError):
"""Raised when API rate limits are exceeded (HTTP 429)."""
pass
class AEBadRequestError(AEAPIError):
"""Raised when API returns HTTP 400 or 422."""
pass
class AENotFoundError(AEAPIError):
"""Raised when API returns HTTP 404."""
pass

View File

@@ -0,0 +1,30 @@
from typing import Dict, Any, Optional
from ..client import AEClient
class ProductsService:
"""Service to handle AE Platform Products and Links."""
def __init__(self, client: AEClient):
self.client = client
def get_link_info(self, link: str, user_id: Optional[str] = None, user_sub_id: Optional[str] = None) -> Dict[str, Any]:
"""
Get information about a product/link including commission rates.
Endpoint: POST /users/{userId}/link/info
"""
uid = user_id or self.client.user_id
if not uid:
raise ValueError("user_id must be provided either in the method call or client initialization.")
payload = {"link": link}
if user_sub_id:
payload["userSubId"] = user_sub_id
return self.client.post(f"/users/{uid}/link/info", data=payload)
def get_products_feeds(self, limit: int = 30) -> Dict[str, Any]:
"""
Get product feeds.
Endpoint: GET /productsfeeds/feeds
"""
return self.client.get("/productsfeeds/feeds", params={"limit": limit})

View File

@@ -0,0 +1,19 @@
from typing import Dict, Any, Optional
from ..client import AEClient
class TransactionsService:
"""Service to handle AE Platform Transactions (Orders)."""
def __init__(self, client: AEClient):
self.client = client
def get_list(self, user_id: Optional[str] = None, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""
Get list of transactions (orders) for a user.
Endpoint: GET /users/{user_id}/transactions
"""
uid = user_id or self.client.user_id
if not uid:
raise ValueError("user_id must be provided either in the method call or client initialization.")
return self.client.get(f"/users/{uid}/transactions", params=params)