Добавлен новый файл call_validation_promo_api.py для валидации промокодов через API. Реализована логика получения JWT токена и проверки валидности промокода. Обновлены модели в integration_models.py для поддержки запросов и ответов на валидацию промокодов. Добавлен новый эндпоинт /validationPromo в integration_api.py для обработки запросов на валидацию промокодов.

This commit is contained in:
Redsandyg 2025-06-22 14:39:14 +03:00
parent a6308582cb
commit 2c8cbe753e
3 changed files with 90 additions and 2 deletions

View File

@ -0,0 +1,63 @@
import requests
import json
# Конфигурация API
BASE_URL = "http://127.0.0.1:8001"
API_KEY = "9efb2df0-03d7-4212-93db-0ae6418667e1" # API-ключ
PROMOCODE = "brw0OMOz"
# Данные для запроса на валидацию промокода
validation_data = {
"promocode": PROMOCODE,
}
# Эндпоинты
token_endpoint = f"{BASE_URL}/token"
validation_endpoint = f"{BASE_URL}/validationPromo"
# Шаг 1: Получение JWT токена
print(f"Отправка запроса на получение токена на {token_endpoint}")
token_headers = {
"X-API-Key": API_KEY,
"Content-Type": "application/json"
}
try:
token_response = requests.post(token_endpoint, headers=token_headers)
token_response.raise_for_status()
token_data = token_response.json()
jwt_token = token_data["access_token"]
print("JWT токен успешно получен.")
except requests.exceptions.RequestException as e:
print(f"Произошла ошибка при получении токена: {e}")
if hasattr(e, 'response') and e.response is not None:
try:
print("Тело ответа с ошибкой:", e.response.json())
except json.JSONDecodeError:
print("Тело ответа с ошибкой (не JSON):", e.response.text)
exit() # Прерываем выполнение, если не удалось получить токен
# Шаг 2: Вызов эндпоинта /validationPromo с использованием полученного JWT токена
headers_with_jwt = {
"Authorization": f"Bearer {jwt_token}",
"Content-Type": "application/json"
}
print(f"Отправка запроса на {validation_endpoint} с данными: {validation_data}")
try:
validation_response = requests.post(validation_endpoint, headers=headers_with_jwt, data=json.dumps(validation_data))
validation_response.raise_for_status() # Вызовет исключение для ошибок HTTP (4xx или 5xx)
print("Статус ответа:", validation_response.status_code)
print("Тело ответа:", validation_response.json())
except requests.exceptions.RequestException as e:
print(f"Произошла ошибка при вызове API validationPromo: {e}")
if hasattr(e, 'response') and e.response is not None:
try:
print("Тело ответа с ошибкой:", e.response.json())
except json.JSONDecodeError:
print("Тело ответа с ошибкой (не JSON):", e.response.text)

View File

@ -8,7 +8,7 @@ from random import choices
import string
from sql_models import Company, IntegrationToken, Ref, Sale, AgentTransaction, PartnerTransaction, AgentBalance, TgAgent, CompanyBalance, SaleCategory
from integration_models import Token, SaleCreateRequest, SaleCreateResponse, TransactionStatus, WithdrawRequest, WithdrawResponse
from integration_models import Token, SaleCreateRequest, SaleCreateResponse, TransactionStatus, WithdrawRequest, WithdrawResponse, PromoValidationRequest, PromoValidationResponse
from bff_models import RegisterResponse, TgAuthResponse
from tg_models import RefAddRequest, RefResponse, RefAddResponse, RefStatResponse, RegisterRequest, StatResponse
from helpers_bff import AUTH_DB_ENGINE, get_integration_db, create_integration_jwt_token, get_current_company_from_jwt, get_tg_agent_by_tg_id, get_current_tg_agent
@ -289,6 +289,25 @@ async def create_sale(
"crediting": new_sale.crediting
}
@app.post("/validationPromo", tags=["integration"], response_model=PromoValidationResponse)
async def validate_promocode(
req: PromoValidationRequest,
company: Company = Depends(get_current_company_from_jwt),
db: Session = Depends(get_integration_db)
):
"""
Проверяет валидность промокода для текущей компании.
"""
referral = db.exec(select(Ref).where(Ref.promocode == req.promocode)).first()
if not referral:
return {"validation": False}
tg_agent = db.exec(select(TgAgent).where(TgAgent.id == referral.tg_agent_id, TgAgent.company_id == company.id)).first()
if not tg_agent:
return {"validation": False}
return {"validation": True}
@app.post("/register", tags=["agent-tg"], response_model=RegisterResponse)
def register(req: RegisterRequest, db: Session = Depends(get_integration_db)):
"""

View File

@ -43,3 +43,9 @@ class TransactionStatus(str, Enum):
DONE = "done"
CANCELED = "canceled"
ERROR = "error"
class PromoValidationRequest(BaseModel):
promocode: str
class PromoValidationResponse(BaseModel):
validation: bool