Skip to content

Commit

Permalink
create new token and get session code
Browse files Browse the repository at this point in the history
  • Loading branch information
ronknight committed Jun 26, 2024
1 parent 143f1dc commit 9eeae26
Show file tree
Hide file tree
Showing 16 changed files with 240 additions and 605 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
*.env
*.json
*.log
28 changes: 1 addition & 27 deletions initiate.py → 1initiate.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,30 +103,4 @@ def generate_sign(params, app_secret):

# Generate sign
sign = generate_sign(params, app_secret)
params['sign'] = sign

# Construct the exact URL with encoded parameters
encoded_params = urllib.parse.urlencode(params)
exact_url_format = f"https://gw.api.taobao.com/router/rest?{encoded_params}"

print(f"Making API call to: {exact_url_format}")

# Make API call with retry logic
max_retries = 5
for attempt in range(max_retries):
try:
response = requests.get(exact_url_format, timeout=10) # Set timeout to 10 seconds
response.raise_for_status() # Raise exception for bad response status
data = response.json() # Parse JSON response
print("API Response:", data)
break # Exit loop on successful response
except requests.exceptions.Timeout:
print(f"The request timed out. Attempt {attempt + 1} of {max_retries}")
if attempt < max_retries - 1:
time.sleep(2 ** attempt) # Exponential backoff
except requests.exceptions.RequestException as e:
print("API call failed:", e)
break # Exit loop on non-timeout request failure
except Exception as e:
print("An unexpected error occurred:", e)
break # Exit loop on unexpected error
params['sign'] = sign
15 changes: 0 additions & 15 deletions 1obtain.py

This file was deleted.

70 changes: 70 additions & 0 deletions 2createtoken.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import os
import requests
from dotenv import load_dotenv
import hashlib
import time
import json

# Load environment variables from .env file
load_dotenv()

# Retrieve variables from environment
APP_KEY = os.getenv('APP_KEY')
APP_SECRET = os.getenv('APP_SECRET')
AUTH_CODE = os.getenv('AUTH_CODE')

ALIBABA_SERVER_CALL_ENTRY = "https://eco.taobao.com/router/rest"
LOG_DIR = 'api_logs/' # Directory to store log files

# Create directory if it does not exist
os.makedirs(LOG_DIR, exist_ok=True)

# Create a sign
def create_sign(params, secret):
sorted_params = sorted(params.items())
basestring = secret + ''.join(f'{k}{v}' for k, v in sorted_params) + secret
return hashlib.md5(basestring.encode('utf-8')).hexdigest().upper()

# Prepare the request parameters
params = {
'method': 'taobao.top.auth.token.create',
'app_key': APP_KEY,
'timestamp': time.strftime("%Y-%m-%d %H:%M:%S"),
'format': 'json',
'v': '2.0',
'sign_method': 'md5',
'code': AUTH_CODE
}

# Generate the sign
params['sign'] = create_sign(params, APP_SECRET)

# Make the request
response = requests.get(ALIBABA_SERVER_CALL_ENTRY, params=params)

# Check if the response is successful
if response.status_code == 200:
response_data = response.json()

# Extract access_token from the response
try:
token_result = response_data['top_auth_token_create_response']['token_result']
token_result_dict = json.loads(token_result)
access_token = token_result_dict.get('access_token')

if access_token:
# Update .env file with session_key = access_token
with open('.env', 'a') as env_file:
env_file.write(f"\nSESSION_KEY={access_token}")

print(f"Session key (access_token) saved to .env file")
else:
print("Access token not found in the response")

except KeyError:
print("Invalid response format, access token could not be extracted")

# Optionally, save the entire response to a log file or process further

else:
print(f"Failed to retrieve data: {response.status_code}")
15 changes: 0 additions & 15 deletions 2extract.py

This file was deleted.

95 changes: 95 additions & 0 deletions 3productlist.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import os
import requests
import hashlib
import time
import urllib.parse
import json
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Retrieve variables from environment
app_key = os.getenv('APP_KEY')
app_secret = os.getenv('APP_SECRET')
session_key = os.getenv('SESSION_KEY')

# API endpoint and parameters
url = 'http://gw.api.taobao.com/router/rest'
params = {
'app_key': app_key,
'format': 'json', # Request JSON format
'method': 'alibaba.icbu.product.list', # API method
'partner_id': 'apidoc',
'session': session_key,
'sign_method': 'md5', # Sign method MD5
'timestamp': time.strftime("%Y-%m-%d %H:%M:%S"),
'v': '2.0',
'current_page': '1', # Example: Set current page
'page_size': '10', # Example: Set page size
'subject': '', # Example: Product name query
'language': 'ENGLISH',
}

# Calculate sign
def calculate_sign(params, secret):
sorted_params = sorted(params.items())
sign_string = secret + ''.join([f'{k}{v}' for k, v in sorted_params]) + secret
return hashlib.md5(sign_string.encode('utf-8')).hexdigest().upper()

# Add sign to parameters
params['sign'] = calculate_sign(params, app_secret)

try:
# Log the request details
print(f"Request URL: {url}")
print(f"Request Method: POST")
print("Request Headers:")
for key, value in params.items():
print(f"{key}: {value}")
print("Request Body:")
print(params)

# Make POST request
response = requests.post(url, data=params)

# Log the response details
print(f"Response Status Code: {response.status_code}")
print("Response Headers:")
for key, value in response.headers.items():
print(f"{key}: {value}")
print("Response Body:")
print(response.text)

# Check if request was successful
if response.status_code == 200:
try:
# Parse JSON response
data = response.json()

# Check if error response
if 'error_response' in data:
error = data['error_response']
code = error['code']
msg = error['msg']
sub_msg = error['sub_msg'] if 'sub_msg' in error else ''
print(f"API Error: {msg}. {sub_msg}")
else:
# Check if expected response structure is present
if 'alibaba_icbu_product_list_response' in data:
product_list_response = data['alibaba_icbu_product_list_response']
products = product_list_response.get('products', [])
if products:
for product in products:
subject = product.get('subject', '')
print(f"Product Subject: {subject}")
else:
print("No products found in response.")
else:
print("Unexpected JSON structure: alibaba_icbu_product_list_response not found.")
except json.JSONDecodeError as je:
print(f"Failed to parse JSON response: {je}")
else:
print(f"Request failed with status code: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"Request error: {e}")
73 changes: 73 additions & 0 deletions 4productschema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import os
import requests
import hashlib
import time
import json
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Retrieve variables from environment
app_key = os.getenv('APP_KEY')
app_secret = os.getenv('APP_SECRET')
session_key = os.getenv('SESSION_KEY')

# API endpoint and parameters
url = 'http://gw.api.taobao.com/router/rest'
method = 'alibaba.icbu.product.schema.get'
format = 'json' # Response format
sign_method = 'md5'
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
v = '2.0'

# Additional parameters specific to the API method
params = {
'app_key': app_key,
'method': method,
'format': format,
'sign_method': sign_method,
'timestamp': timestamp,
'v': v,
'session': session_key # Include session key here
}

# Calculate sign
def calculate_sign(params, secret):
sorted_params = sorted(params.items())
sign_string = secret + ''.join([f'{k}{v}' for k, v in sorted_params]) + secret
return hashlib.md5(sign_string.encode('utf-8')).hexdigest().upper()

# Add sign to parameters
params['sign'] = calculate_sign(params, app_secret)

try:
# Make POST request
response = requests.post(url, data=params)

# Check if request was successful
if response.status_code == 200:
try:
# Parse JSON response
data = response.json()

# Check for error response
if 'error_response' in data:
error = data['error_response']
code = error['code']
msg = error['msg']
sub_msg = error.get('sub_msg', '')
print(f"API Error: {msg}. {sub_msg}")
else:
# Process successful response
print("Successful Response:")
print(json.dumps(data, indent=2))

except json.JSONDecodeError as je:
print(f"Failed to parse JSON response: {je}")

else:
print(f"Request failed with status code: {response.status_code}")

except requests.exceptions.RequestException as e:
print(f"Request error: {e}")
68 changes: 0 additions & 68 deletions test/3exchange.py

This file was deleted.

Loading

0 comments on commit 9eeae26

Please sign in to comment.