Commit d21e9eec authored by Vũ Hoàng Anh's avatar Vũ Hoàng Anh

Update mock API routes and prefixes

parent 49f43a45
......@@ -2,14 +2,16 @@
Canifa API Service
Xử lý các logic liên quan đến API của Canifa (Magento)
"""
import logging
from typing import Any
import httpx
from typing import Optional, Dict, Any
logger = logging.getLogger(__name__)
# URL API Canifa
CANIFA_CUSTOMER_API = "https://canifa.com/v1/magento/customer"
CANIFA_CUSTOMER_API = "https://vsf2.canifa.com/v1/magento/customer"
# GraphQL Query Body giả lập (để lấy User Info)
CANIFA_QUERY_BODY = [
......@@ -17,87 +19,84 @@ CANIFA_QUERY_BODY = [
"customer": "customer-custom-query",
"metadata": {
"fields": "\n customer {\n gender\n customer_id\n phone_number\n date_of_birth\n default_billing\n default_shipping\n email\n firstname\n is_subscribed\n lastname\n middlename\n prefix\n suffix\n taxvat\n addresses {\n city\n country_code\n default_billing\n default_shipping\n extension_attributes {\n attribute_code\n value\n }\n custom_attributes {\n attribute_code\n value\n }\n firstname\n id\n lastname\n postcode\n prefix\n region {\n region_code\n region_id\n region\n }\n street\n suffix\n telephone\n vat_id\n }\n is_subscribed\n }\n "
}
},
},
{}
{},
]
async def verify_canifa_token(token: str) -> Optional[Dict[str, Any]]:
async def verify_canifa_token(token: str) -> dict[str, Any] | None:
"""
Verify token với API Canifa (Magento).
Dùng token làm cookie `vsf-customer` để gọi API lấy thông tin customer.
Args:
token: Giá trị của cookie vsf-customer (lấy từ Header Authorization)
Returns:
Dict info user hoặc None nếu lỗi
"""
if not token:
return None
headers = {
"accept": "application/json, text/plain, */*",
"content-type": "application/json",
"Cookie": f"vsf-customer={token}" # Quan trọng: Gửi token dưới dạng Cookie
"Cookie": f"vsf-customer={token}", # Quan trọng: Gửi token dưới dạng Cookie
}
try:
async with httpx.AsyncClient(timeout=10.0) as client:
response = await client.post(
CANIFA_CUSTOMER_API,
json=CANIFA_QUERY_BODY,
headers=headers
)
response = await client.post(CANIFA_CUSTOMER_API, json=CANIFA_QUERY_BODY, headers=headers)
if response.status_code == 200:
data = response.json()
logger.debug(f"Canifa API Raw Response: {data}")
# Response format: {"data": {"customer": {...}}, "loading": false, ...}
if isinstance(data, dict):
# Trả về toàn bộ data để extract_user_id xử lý
return data
# Nếu Canifa trả list (batch request)
return data
else:
logger.warning(f"Canifa API Failed: {response.status_code} - {response.text}")
return None
logger.warning(f"Canifa API Failed: {response.status_code} - {response.text}")
return None
except Exception as e:
logger.error(f"Error calling Canifa API: {e}")
return None
async def extract_user_id_from_canifa_response(data: Any) -> Optional[str]:
async def extract_user_id_from_canifa_response(data: Any) -> str | None:
"""
Bóc customer_id từ response data của Canifa.
"""
if not data:
return None
try:
# Dự phòng các format data trả về khác nhau
customer = None
# Format 1: data['customer']
if isinstance(data, dict):
customer = data.get('customer') or data.get('data', {}).get('customer')
customer = data.get("customer") or data.get("data", {}).get("customer")
# Format 2: data là list (nếu query batch)
elif isinstance(data, list) and len(data) > 0:
item = data[0]
if isinstance(item, dict):
customer = item.get('result', {}).get('customer') or item.get('data', {}).get('customer')
customer = item.get("result", {}).get("customer") or item.get("data", {}).get("customer")
if customer and isinstance(customer, dict):
user_id = customer.get('customer_id') or customer.get('id')
user_id = customer.get("customer_id") or customer.get("id")
if user_id:
return str(user_id)
return None
except Exception as e:
logger.error(f"Error parsing user_id from Canifa response: {e}")
return None
......@@ -12,4 +12,6 @@ docker restart chatbot-backend && docker logs -f chatbot-backend
docker logs -f chatbot-backend
docker restart chatbot-backend
\ No newline at end of file
docker restart chatbot-backend
sudo docker compose -f docker-compose.prod.yml up -d --build
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment