275 lines
10 KiB
Python
275 lines
10 KiB
Python
import requests
|
||
from datetime import datetime, timedelta
|
||
from models import *
|
||
import re
|
||
import time
|
||
import uuid
|
||
from dotenv import load_dotenv
|
||
import os
|
||
load_dotenv()
|
||
|
||
KCRM =os.getenv('KEYCRM_API')
|
||
|
||
CLIENT_ID = os.getenv('CLIENT_ID')
|
||
USERNAME = os.getenv('USERNAME')
|
||
PASSWORD = os.getenv('PASSWORD')
|
||
CLIENT_SECRET = os.getenv('CLIENT_SECRET')
|
||
|
||
def datass():
|
||
# Получение текущей даты
|
||
current_date = datetime.now()
|
||
|
||
# Форматирование даты в формат YYYY-MM-DD
|
||
formatted_date = current_date.strftime('%Y-%m-%d')
|
||
|
||
# print(formatted_date)
|
||
return formatted_date
|
||
|
||
def datass_pymb():
|
||
# Получение текущей даты
|
||
current_date = datetime.now()
|
||
|
||
# Форматирование даты в формат YYYY-MM-DD
|
||
formatted_date = current_date.strftime('%d.%m.%Y')
|
||
|
||
# print(formatted_date)
|
||
return formatted_date
|
||
|
||
def oplata(order_ids):
|
||
# Получение всех записей
|
||
# orders = Transaction.select()
|
||
order = Transaction.get_or_none(Transaction.id == order_ids)
|
||
# for order in orders:
|
||
if order:
|
||
numbers = re.findall(r'\d+', order.description)
|
||
if numbers: # Проверяем, что список не пуст
|
||
first_number = numbers[0] # Получаем первое значение из списка
|
||
print(first_number, order.amount, order.uuid)
|
||
# formatted_datetime = datetime.strptime(order.created_at, "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%Y-%m-%d %H:%M:%S")
|
||
|
||
# print(first_number, order.amount, formatted_datetime, order.description)
|
||
headers = {
|
||
'accept': 'application/json',
|
||
'Authorization': f'Bearer {KCRM}',
|
||
}
|
||
# response = requests.get(f'https://openapi.keycrm.app/v1/order/17', headers=headers)
|
||
json_data = {
|
||
'payment_method_id': 3,
|
||
'payment_method': 'Банковский перевод',
|
||
'amount': order.amount,
|
||
'status': 'paid',
|
||
'description': order.description,
|
||
'payment_date': order.created_at,
|
||
}
|
||
|
||
response = requests.post(f'https://openapi.keycrm.app/v1/order/{first_number}/payment', headers=headers, json=json_data)
|
||
|
||
# response = requests.put('https://openapi.keycrm.app/v1/order/17/payment/1161', headers=headers, json=json_data)
|
||
print(response.json())
|
||
else:
|
||
print(f"Order with ID {order_id} not found.")
|
||
|
||
|
||
|
||
|
||
|
||
def trans():
|
||
headers = {
|
||
'accept': 'application/json',
|
||
'Authorization': f'Bearer {KCRM}',
|
||
|
||
}
|
||
|
||
params = {
|
||
'limit': '30',
|
||
'page': '1',
|
||
'include': 'payment_method',
|
||
'filter[created_between]': f'{datass()} 00:00:00, {datass()} 23:59:59',
|
||
# 'filter[created_between]': f'2024-08-20 00:00:00, 2024-08-20 23:59:59',
|
||
|
||
}
|
||
|
||
response = requests.get('https://openapi.keycrm.app/v1/payments/external-transactions', params=params, headers=headers)
|
||
|
||
aaa = response.json()['data']
|
||
# print(aaa)
|
||
for aa in aaa:
|
||
ids = aa['id']
|
||
payments_data = aa['payments_data']
|
||
amount = aa['amount']
|
||
description =aa['description']
|
||
uuid = aa ['uuid']
|
||
created_at = aa ['transaction_date']
|
||
timestamp = datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%S.%fZ") # Преобразование строки в datetime
|
||
new_timestamp = timestamp + timedelta(hours=3) # Добавление 3 часов
|
||
gateway_id = aa ['gateway_id']
|
||
# print(f'{ids} {uuid} {amount} {description}')
|
||
# Проверка существования записи с таким id
|
||
if not Transaction.select().where(Transaction.id == ids).exists():
|
||
# Запись данных в таблицу, если id не существует
|
||
new_transaction = Transaction.create(id=ids, uuid=uuid, amount=amount, description=description, created_at = new_timestamp,gateway_id=gateway_id)
|
||
# print(f'Запись добавлена: {new_transaction.id} {new_transaction.uuid} {new_transaction.amount} {new_transaction.description}')
|
||
numbers = re.findall(r'\d+', description)
|
||
if gateway_id == 1:
|
||
# Выводим все численные значения
|
||
if numbers: # Проверяем, что список не пуст
|
||
first_number = numbers[0] # Получаем первое значение из списка
|
||
print(first_number)
|
||
headers = {
|
||
'accept': 'application/json',
|
||
'Authorization': f'Bearer {KCRM}',
|
||
|
||
}
|
||
|
||
response = requests.get(f'https://openapi.keycrm.app/v1/order/{first_number}', headers=headers)
|
||
resp = response.json()
|
||
|
||
if 'message' in resp:
|
||
print('NOT ORDERS')
|
||
else:
|
||
# Дальше идет обработка данных заказа
|
||
|
||
print(resp)
|
||
oplata(ids)
|
||
else:
|
||
pass
|
||
else:
|
||
print(f'Запись с id {ids} уже существует, пропускаем.')
|
||
db.close()
|
||
|
||
def pymb():
|
||
token_url = "https://auth.fuib.com/auth/realms/VegaNet/protocol/openid-connect/token"
|
||
|
||
# Параметры запроса
|
||
data = {
|
||
'grant_type': 'password',
|
||
'client_id': CLIENT_ID,
|
||
'username': USERNAME,
|
||
'password': PASSWORD,
|
||
'client_secret': CLIENT_SECRET
|
||
}
|
||
|
||
# Заголовки запроса
|
||
headers = {
|
||
'Content-Type': 'application/x-www-form-urlencoded'
|
||
}
|
||
|
||
# Выполнение POST-запроса
|
||
response = requests.post(token_url, data=data, headers=headers)
|
||
# print(response.json())
|
||
# Проверка статуса ответа
|
||
if response.status_code == 200:
|
||
# Получение токена из ответа
|
||
token_info = response.json()
|
||
access_token = token_info.get('access_token')
|
||
|
||
# print(f"Access Token: {access_token}")
|
||
session_id = token_info.get('session_state')
|
||
# print(f"Access Token: {session_id}")
|
||
|
||
else:
|
||
print(f"Failed to get token. Status code: {response.status_code}, Response: {response.text}")
|
||
|
||
request_guid = str(uuid.uuid4()) # Генерация уникального RequiestGUID
|
||
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
|
||
fingerprint_id = user_agent # Используем UserAgent в качестве FingerprintId
|
||
|
||
#Запрос на получение транзакций
|
||
api_url = "https://service.fuib.com:4103/war_veganet_api/document/period-transactions"
|
||
|
||
headers = {
|
||
'Content-Type': 'application/json',
|
||
'Authorization': f'Bearer {access_token}',
|
||
'X-App-Channel': 'pure-api',
|
||
'X-Flow-ID': f'{request_guid}:{session_id}:{fingerprint_id}'
|
||
}
|
||
|
||
data = {
|
||
"accountId": 191214708,
|
||
# "documentType": ["UNKNOWN"], # Типы документов (обязательный)
|
||
# "dateFrom": "21.08.2024 00:00:00",
|
||
"dateFrom": f"{datass_pymb()} 00:00:00",
|
||
"dateTo": f"{datass_pymb()} 23:59:00"
|
||
}
|
||
|
||
# # Выполнение POST-запроса
|
||
response = requests.post(api_url, json=data, headers=headers)
|
||
|
||
# Проверка статуса ответа
|
||
if response.status_code == 200:
|
||
# Успешный ответ
|
||
response_data = response.json()['transactions'] # Ответ в формате JSON
|
||
# print(f"Filtered Account Data: {response_data}")
|
||
for datas in response_data:
|
||
flag = datas['dcFlag']
|
||
amount = datas['amount']
|
||
narrative = datas['narrative']
|
||
documentDate = datas['documentDate']
|
||
documentNumber = datas['documentNumber']
|
||
transactionId = datas['transactionId']
|
||
|
||
document_date = datetime.strptime(documentDate, "%d.%m.%Y %H:%M:%S")
|
||
|
||
# Convert to the desired format (Y-m-d H:i:s)
|
||
formatted_date = document_date.strftime("%Y-%m-%d %H:%M:%S")
|
||
|
||
|
||
if not Transaction.select().where(Transaction.id == transactionId).exists():
|
||
# Запись данных в таблицу, если id не существует
|
||
new_transaction = Transaction.create(id=transactionId, uuid=documentNumber, amount=amount, description=narrative, created_at = formatted_date,gateway_id=flag)
|
||
numbers = re.findall(r'\d+', narrative)
|
||
if numbers: # Проверяем, что список не пуст
|
||
first_number = numbers[0] # Получаем первое значение из списка
|
||
print(first_number)
|
||
headers = {
|
||
'accept': 'application/json',
|
||
'Authorization': f'Bearer {KCRM}',
|
||
|
||
}
|
||
|
||
response = requests.get(f'https://openapi.keycrm.app/v1/order/{first_number}', headers=headers)
|
||
resp = response.json()
|
||
|
||
if 'message' in resp:
|
||
print('NOT ORDERS')
|
||
else:
|
||
# Дальше идет обработка данных заказа
|
||
|
||
print(resp)
|
||
oplata(transactionId)
|
||
else:
|
||
print(f'Запись с id {transactionId} уже существует, пропускаем.')
|
||
|
||
|
||
|
||
|
||
else:
|
||
# Ошибка
|
||
print(f"Failed to get filtered account data. Status code: {response.status_code}, Response: {response.text}")
|
||
|
||
db.close()
|
||
|
||
|
||
|
||
|
||
def mains():
|
||
|
||
while True:
|
||
try:
|
||
trans()
|
||
pymb()
|
||
except Exception as e:
|
||
# print(e.with_traceback())
|
||
print(e)
|
||
print("PAUSE")
|
||
time.sleep(600)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
mains()
|
||
|
||
|
||
|
||
|
||
|