-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
create new token and get session code
- Loading branch information
Showing
16 changed files
with
240 additions
and
605 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
*.env | ||
*.json | ||
*.log |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}") |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}") |
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.