gogo2/debug_mexc_auth.py
2025-05-28 11:17:41 +03:00

149 lines
4.7 KiB
Python

#!/usr/bin/env python3
"""
Debug script for MEXC API authentication
"""
import os
import hmac
import hashlib
import time
import requests
from urllib.parse import urlencode
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
def debug_mexc_auth():
"""Debug MEXC API authentication step by step"""
api_key = os.getenv('MEXC_API_KEY')
api_secret = os.getenv('MEXC_SECRET_KEY')
print("="*60)
print("MEXC API AUTHENTICATION DEBUG")
print("="*60)
print(f"API Key: {api_key}")
print(f"API Secret: {api_secret[:10]}...{api_secret[-10:]}")
print()
# Test 1: Public API (no auth required)
print("1. Testing Public API (ping)...")
try:
response = requests.get("https://api.mexc.com/api/v3/ping")
print(f" Status: {response.status_code}")
print(f" Response: {response.json()}")
print(" ✅ Public API works")
except Exception as e:
print(f" ❌ Public API failed: {e}")
return
print()
# Test 2: Get server time
print("2. Testing Server Time...")
try:
response = requests.get("https://api.mexc.com/api/v3/time")
server_time_data = response.json()
server_time = server_time_data['serverTime']
print(f" Server Time: {server_time}")
print(" ✅ Server time retrieved")
except Exception as e:
print(f" ❌ Server time failed: {e}")
return
print()
# Test 3: Manual signature generation and account request
print("3. Testing Authentication (manual signature)...")
# Get server time for accurate timestamp
try:
server_response = requests.get("https://api.mexc.com/api/v3/time")
server_time = server_response.json()['serverTime']
print(f" Using Server Time: {server_time}")
except:
server_time = int(time.time() * 1000)
print(f" Using Local Time: {server_time}")
# Parameters for account endpoint
params = {
'timestamp': server_time,
'recvWindow': 10000 # Increased receive window
}
print(f" Timestamp: {server_time}")
print(f" Params: {params}")
# Generate signature manually
# According to MEXC documentation, parameters should be sorted
sorted_params = sorted(params.items())
query_string = urlencode(sorted_params)
print(f" Query String: {query_string}")
# MEXC documentation shows signature in lowercase
signature = hmac.new(
api_secret.encode('utf-8'),
query_string.encode('utf-8'),
hashlib.sha256
).hexdigest()
print(f" Generated Signature (hex): {signature}")
print(f" API Secret used: {api_secret[:5]}...{api_secret[-5:]}")
print(f" Query string length: {len(query_string)}")
print(f" Signature length: {len(signature)}")
print(f" Generated Signature: {signature}")
# Add signature to params
params['signature'] = signature
# Make the request
headers = {
'X-MEXC-APIKEY': api_key
}
print(f" Headers: {headers}")
print(f" Final Params: {params}")
try:
response = requests.get(
"https://api.mexc.com/api/v3/account",
params=params,
headers=headers
)
print(f" Status Code: {response.status_code}")
print(f" Response Headers: {dict(response.headers)}")
if response.status_code == 200:
account_data = response.json()
print(f" ✅ Authentication successful!")
print(f" Account Type: {account_data.get('accountType', 'N/A')}")
print(f" Can Trade: {account_data.get('canTrade', 'N/A')}")
print(f" Can Withdraw: {account_data.get('canWithdraw', 'N/A')}")
print(f" Can Deposit: {account_data.get('canDeposit', 'N/A')}")
print(f" Number of balances: {len(account_data.get('balances', []))}")
# Show USDT balance
for balance in account_data.get('balances', []):
if balance['asset'] == 'USDT':
print(f" 💰 USDT Balance: {balance['free']} (locked: {balance['locked']})")
break
else:
print(f" ❌ Authentication failed!")
print(f" Response: {response.text}")
# Try to parse error
try:
error_data = response.json()
print(f" Error Code: {error_data.get('code', 'N/A')}")
print(f" Error Message: {error_data.get('msg', 'N/A')}")
except:
pass
except Exception as e:
print(f" ❌ Request failed: {e}")
if __name__ == "__main__":
debug_mexc_auth()