Skip to content

Commit

Permalink
combine API calls
Browse files Browse the repository at this point in the history
  • Loading branch information
ronknight committed Jun 24, 2024
1 parent a1f568e commit 143f1dc
Show file tree
Hide file tree
Showing 3 changed files with 180 additions and 1 deletion.
2 changes: 1 addition & 1 deletion 2extract.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from urllib.parse import urlparse, parse_qs

# Given URL
url = "https://cbk.4sgm.us/?code=1_mf5Xxw7UFpoquSWMxmeg3p22730&state=1212"
url = "https://cbk.4sgm.us/?code=1_J3LNDUnqkQeDmjr6JY35XRQ41070&state=1212"

# Parse the URL to extract the query parameters
parsed_url = urlparse(url)
Expand Down
132 changes: 132 additions & 0 deletions initiate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import os
import hashlib
import datetime
import urllib.parse
import requests
from dotenv import load_dotenv
from urllib.parse import urlparse, parse_qs
import time

# Load environment variables from .env file
load_dotenv()

# Function to generate the sign parameter
def generate_sign(params, app_secret):
# Sort parameters by key
sorted_params = sorted(params.items())

# Concatenate all key-value pairs
sign_string = app_secret
for key, value in sorted_params:
sign_string += f"{key}{value}"

# Append app_secret again
sign_string += app_secret

# Calculate MD5 hash
sign = hashlib.md5(sign_string.encode('utf-8')).hexdigest().upper()
return sign

# Get parameters from environment variables
app_key = os.getenv('APP_KEY')
app_secret = os.getenv('APP_SECRET')
redirect_uri = os.getenv('REDIRECT_URI') # Your redirect URI

# URL to redirect the user for authorization
auth_url = f"https://oauth.alibaba.com/authorize?response_type=code&client_id={app_key}&redirect_uri={redirect_uri}&State=1212&view=web&sp=ICBU"

print("Please visit the following URL to authorize the application:")
print(auth_url)

# Get the redirected URL from the user (assuming manual input for simplicity)
redirected_url = input("Please enter the redirected URL after authorization: ")

# Parse the URL to extract the query parameters
parsed_url = urlparse(redirected_url)
query_params = parse_qs(parsed_url.query)

# Extract the authorization code and state
auth_code = query_params.get('code', [None])[0]
state = query_params.get('state', [None])[0]

# Print extracted values
print(f"Authorization Code: {auth_code}")
print(f"State: {state}")

# Ensure AUTH_CODE and STATE are available
if not auth_code or not state:
print("Authorization code or state is missing.")
exit(1)

# Read the current .env file
env_path = '.env'
env_vars = {}
if os.path.exists(env_path):
with open(env_path, 'r') as env_file:
for line in env_file:
line = line.strip()
if line and not line.startswith('#'):
key, value = line.split('=', 1)
env_vars[key] = value

# Update the env_vars with new values
env_vars['AUTH_CODE'] = auth_code
env_vars['STATE'] = state

# Write the updated environment variables back to the .env file
with open(env_path, 'w') as env_file:
for key, value in env_vars.items():
env_file.write(f'{key}={value}\n')

print("Authorization code and state have been updated in the .env file.")

# Ensure APP_SECRET is set
if not app_secret:
print("APP_SECRET is missing or not set.")
exit(1)

# Generate timestamp
timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%d+%H%%3A%M%%3A%S') # Format timestamp according to URL encoding

# Construct parameters dictionary
params = {
'app_key': app_key,
'method': 'taobao.top.auth.token.create',
'v': '2.0',
'sign_method': 'md5',
'format': 'json',
'timestamp': timestamp,
'partner_id': 'top-apitools',
'code': auth_code,
'uuid': '4sgm' # Hardcoded value according to the provided URL
}

# 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
47 changes: 47 additions & 0 deletions test2/testcurl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import requests
from dotenv import load_dotenv
import os
import datetime
import hashlib

# Load environment variables from .env file
load_dotenv()

# Get environment variables
app_key = os.getenv("APP_KEY")
app_secret = os.getenv("APP_SECRET")
auth_code = os.getenv("AUTH_CODE")

# Generate timestamp
timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%d+%H%%3A%M%%3A%S') # Format timestamp according to URL encoding

# Function to generate the sign
def generate_sign(params, secret):
sorted_params = sorted(params.items())
concatenated_string = secret + ''.join(f'{k}{v}' for k, v in sorted_params) + secret
return hashlib.md5(concatenated_string.encode('utf-8')).hexdigest().upper()

# Construct parameters dictionary
params = {
'app_key': app_key,
'method': 'taobao.top.auth.token.create',
'v': '2.0',
'sign_method': 'md5',
'format': 'json',
'timestamp': timestamp,
'partner_id': 'top-apitools',
'code': auth_code,
'uuid': '4sgm' # Hardcoded value according to the provided URL
}

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

# Make the GET request
url = "https://gw.api.taobao.com/router/rest"
response = requests.get(url, params=params)

# Print response
print(response.status_code)
print(response.json())

0 comments on commit 143f1dc

Please sign in to comment.