杰瑞科技汇

Python淘宝API如何调用?

Of course! Using a Python API for Taobao (淘宝) is a common requirement for developers, especially for e-commerce automation, data analysis, or creating affiliate marketing tools.

Python淘宝API如何调用?-图1
(图片来源网络,侵删)

The official way to interact with Taobao's ecosystem is through their Taobao Open Platform (淘宝开放平台). They provide a comprehensive set of APIs called Top (Taobao Open Platform API).

Here’s a complete guide on how to use the Taobao API with Python, covering the concepts, setup, and a practical code example.


Core Concepts: How the Taobao API Works

Before diving into code, you need to understand the fundamental concepts of the Taobao API ecosystem.

a. Application Registration (App Key & Secret)

You first need to register your application on the Taobao Open Platform. This will give you two critical credentials:

Python淘宝API如何调用?-图2
(图片来源网络,侵删)
  • App Key (App Key / appkey): A public identifier for your application.
  • App Secret (App Secret / secret): A private key used to sign your requests and prove your identity. Never expose this secret in your client-side code.

b. Authorization (OAuth 2.0)

You can't just call any API. You need permission from a Taobao user to access their data on their behalf (e.g., get their order history, manage items in their shop). This is done using the OAuth 2.0 protocol.

The flow looks like this:

  1. Redirect User: Your application redirects the user to a Taobao authorization page.
  2. User Grants Permission: The user logs into Taobao and agrees to let your app access certain data.
  3. Taobao Redirects Back: Taobao redirects the user back to your app with a temporary code.
  4. Exchange Code for Token: Your server-side code takes this code and exchanges it for an access_token and a refresh_token.
  5. Make API Calls: Use the access_token to make authenticated API calls on behalf of the user.

c. API Request Signature

Every API request must be digitally signed to ensure it's authentic and hasn't tampered with. You generate this signature using your App Secret and a combination of other request parameters.

d. The Python Library: top-sdk

Manually handling OAuth flows and generating signatures is complex. Taobao provides an official Python SDK called top-sdk that simplifies these tasks immensely. It handles session management, request signing, and parsing responses for you.

Python淘宝API如何调用?-图3
(图片来源网络,侵删)

Step-by-Step Setup Guide

Step 1: Register Your Application on Taobao Open Platform

  1. Go to the Taobao Open Platform and log in with your Taobao account.
  2. Navigate to the "管理中心" (Management Center) and create a new application.
  3. Fill in your application details (name, description, etc.).
  4. During the setup, you will be asked to set a Callback URL (回调地址). This is the URL on your server where Taobao will redirect the user after they grant permission. For local development, you can use a tool like ngrok to expose your local server to the internet.
  5. Once your application is created, you will find your App Key and App Secret in the application's details page.

Step 2: Install the Official Python SDK

Open your terminal or command prompt and install the library using pip:

pip install top-sdk

Step 3: Set Up Your Credentials

For security, it's best practice to store your credentials as environment variables rather than hardcoding them in your script.

Create a file named .env in your project directory:

.env

TAOBAO_APP_KEY=your_app_key_here
TAOBAO_APP_SECRET=your_app_secret_here
CALLBACK_URL=http://your-domain.com/callback  # The one you set in the Taobao console

You'll need a library to load these variables. Install it:

pip install python-dotenv

Practical Example: The OAuth 2.0 Flow

This example will demonstrate the complete OAuth flow: redirecting the user, getting the access_token, and finally, making a simple API call.

We'll use Python's built-in http.server for simplicity.

File Structure:

taobao_api_project/
├── .env
├── server.py
└── requirements.txt

requirements.txt

top-sdk
python-dotenv

server.py

This script will act as a simple web server to handle the OAuth callback.

import os
import sys
import urllib.parse
from http.server import HTTPServer, BaseHTTPRequestHandler
from dotenv import load_dotenv
# --- Configuration ---
load_dotenv() # Load environment variables from .env file
APP_KEY = os.getenv("TAOBAO_APP_KEY")
APP_SECRET = os.getenv("TAOBAO_APP_SECRET")
CALLBACK_URL = os.getenv("CALLBACK_URL")
# Check if credentials are set
if not all([APP_KEY, APP_SECRET, CALLBACK_URL]):
    print("Error: Please set TAOBAO_APP_KEY, TAOBAO_APP_SECRET, and CALLBACK_URL in your .env file.")
    sys.exit(1)
# --- Taobao SDK Initialization ---
from top.api import TopClient, Request
# --- Global variable to store the token ---
# In a real application, you would save this to a database
access_token = None
redirect_uri_for_auth = None
class TaobaoCallbackHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        global access_token, redirect_uri_for_auth
        # --- Part 1: Handle the initial authorization request ---
        if self.path == '/':
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(b"""
            <html>
                <body>
                    <h1>Taobao API Python Example</h1>
                    <p>Click the button below to authorize the application with Taobao.</p>
                    <button onclick="window.location.href='/auth'">Authorize with Taobao</button>
                </body>
            </html>
            """)
        # --- Part 2: Redirect to Taobao for authorization ---
        elif self.path == '/auth':
            # The URL Taobao will redirect back to
            # We use the same server for the callback
            callback = CALLBACK_URL
            # The scope defines what permissions you are requesting.
            # 'scopes' is a comma-separated string of permission codes.
            # For example: 'taobao.item.file.upload' for uploading item images.
            # You can find all scopes in the Taobao Open Platform documentation.
            scopes = 'taobao.user.get'
            # Construct the authorization URL
            auth_url = (
                f"https://oauth.taobao.com/authorize?response_type=code"
                f"&client_id={APP_KEY}"
                f"&redirect_uri={urllib.parse.quote(callback)}"
                f"&state=xyz123&scope={scopes}" # state is for CSRF protection
            )
            self.send_response(302) # Redirect
            self.send_header('Location', auth_url)
            self.end_headers()
        # --- Part 3: Handle the callback from Taobao ---
        elif self.path.startswith('/callback'):
            # Parse the query parameters from the callback URL
            query = urllib.parse.urlparse(self.path).query
            params = urllib.parse.parse_qs(query)
            if 'code' in params:
                auth_code = params['code'][0]
                # --- Part 4: Exchange the code for an access_token ---
                # This is where the SDK helps us.
                c = TopClient(APP_KEY, APP_SECRET)
                # The request object for getting the token
                req = Request()
                req.set_api_name("taobao.top.auth.token.get")
                req.set_charset("utf-8")
                # Set the parameters for the request
                req.set_param("grant_type", "authorization_code")
                req.set_param("code", auth_code)
                req.set_param("redirect_uri", CALLBACK_URL)
                try:
                    # Execute the request
                    token_result = c.execute(req)
                    # The result is a JSON string, parse it
                    import json
                    token_data = json.loads(token_result)
                    if 'taobao_top_auth_token_get_response' in token_data:
                        response = token_data['taobao_top_auth_token_get_response']
                        access_token = response.get('access_token')
                        user_id = response.get('taobao_user_id', 'N/A')
                        self.send_response(200)
                        self.send_header('Content-type', 'text/html')
                        self.end_headers()
                        response_html = f"""
                        <html>
                            <body>
                                <h1>Authorization Successful!</h1>
                                <p>You have been successfully authorized.</p>
                                <p>Your Access Token: <strong>{access_token[:20]}...</strong></p>
                                <p>Your Taobao User ID: <strong>{user_id}</strong></p>
                                <a href="/get_user">Click here to get user info</a>
                            </body>
                        </html>
                        """
                        self.wfile.write(response_html.encode('utf-8'))
                    else:
                        self.send_error(500, f"Failed to get token: {token_data}")
                except Exception as e:
                    self.send_error(500, f"Error during token exchange: {e}")
            else:
                self.send_error(400, "Authorization failed: No code received.")
        # --- Part 5: Use the token to make an API call ---
        elif self.path == '/get_user':
            if not access_token:
                self.send_response(302)
                self.send_header('Location', '/')
                self.end_headers()
                return
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            c = TopClient(APP_KEY, APP_SECRET)
            req = Request()
            req.set_api_name("taobao.user.get")
            req.set_charset("utf-8")
            req.set_param("fields", "user_id,nick") # Specify the fields you want
            req.set_param("session", access_token) # Use the access_token as the session
            try:
                user_result = c.execute(req)
                import json
                user_data = json.loads(user_result)
                response_html = f"""
                <html>
                    <body>
                        <h1>User Info API Call</h1>
                        <p>Successfully fetched user data using the access token.</p>
                        <pre>{json.dumps(user_data, indent=2, ensure_ascii=False)}</pre>
                    </body>
                </html>
                """
                self.wfile.write(response_html.encode('utf-8'))
            except Exception as e:
                error_html = f"""
                <html>
                    <body>
                        <h1>Error calling User API</h1>
                        <p>{e}</p>
                    </body>
                </html>
                """
                self.wfile.write(error_html.encode('utf-8'))
if __name__ == '__main__':
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, TaobaoCallbackHandler)
    print(f"Server running at http://localhost:8000")
    print(f"Please ensure your CALLBACK_URL in Taobao console is accessible (e.g., via ngrok).")
    httpd.serve_forever()

How to Run This Example

  1. Fill your .env file with your actual App Key, App Secret, and a valid Callback URL.
  2. Install dependencies:
    pip install -r requirements.txt
  3. Run the server:
    python server.py
  4. Use a tunnel for the callback (if developing locally): Since your local server is on localhost:8000, Taobao can't reach it. Use a tool like ngrok:
    # In a separate terminal
    ngrok http 8000

    Ngrok will give you a public URL (e.g., https://random-string.ngrok.io). Update your .env file's CALLBACK_URL to this new public URL.

  5. Interact with the app:
    • Open your browser and go to http://localhost:8000.
    • Click the "Authorize with Taobao" button.
    • You will be redirected to Taobao. Log in and grant permission.
    • Taobao will redirect you back to your server, which will display your access_token.
    • Click the link to get user info, which will make a real API call.

Important Considerations & Best Practices

  • Token Expiration: The access_token has a limited lifetime (e.g., a few days). The API also returns a refresh_token. You should implement logic to use the refresh token to get a new access_token without forcing the user to log in again.
  • Rate Limiting: Taobao APIs have rate limits (e.g., a certain number of calls per minute). Your application must handle these limits gracefully to avoid being blocked. Check the response headers for rate limit information.
  • API Documentation is King: The Taobao API documentation is extensive. For any specific API call you want to make (e.g., getting product details, searching orders), you must refer to the official documentation to find the correct API name, required parameters, and available fields. You can find it on the Taobao Open Platform.
  • Security: Never commit your .env file or your App Secret to a public Git repository. Use a .gitignore file to exclude it. Always run API calls from a secure server-side environment, not directly in the user's browser.
分享:
扫描分享到社交APP
上一篇
下一篇