Authentication overview
The Shopee Open Platform secures its APIs to ensure only authorized applications and users can access and modify seller data. Authentication is a prerequisite for nearly all API interactions, enabling applications to perform actions such as managing products, processing orders, or retrieving sales reports on behalf of Shopee sellers. The platform primarily utilizes a signature-based authentication mechanism combined with API keys and unique identifiers, a common practice for securing web APIs against unauthorized access and data tampering (PayPal API signature verification).
This approach verifies both the identity of the calling application and the integrity of the request data. By signing each request, developers confirm that the request has not been altered in transit and originates from a legitimate source. Understanding and correctly implementing Shopee's authentication flow is crucial for successful integration and maintaining the security of seller accounts and transactional data.
Supported authentication methods
Shopee's Open Platform primarily relies on a request-signing mechanism using HMAC-SHA256, in conjunction with API keys and various IDs. This method ensures that requests are authenticated and verifies their integrity. The specific credentials and process vary slightly depending on the API endpoint and the scope of access required.
| Method | When to Use | Security Level |
|---|---|---|
| HMAC-SHA256 Signature with API Key & Partner ID | For all public API requests requiring application-level authorization and data integrity verification. | High: Protects against unauthorized access and request tampering. |
| Access Token (OAuth 2.0-like) | After successful authorization by a seller, to perform actions on behalf of a specific shop. | High: Grants granular permissions to specific shops for a limited duration. |
| Refresh Token | To obtain a new Access Token after the current one expires, without requiring the seller to re-authorize. | Moderate: Extends access without re-authentication, but requires secure storage. |
| Partner Key | Used in conjunction with the Partner ID to generate the HMAC-SHA256 signature for API requests. | High: Critical for request signing; must be kept confidential. |
The core authentication process involves generating a signature for each API request. This signature is computed using a combination of the API endpoint, request parameters, a timestamp, and a secret key (Partner Key). The server then independently computes the same signature using the provided data and its stored secret. If the signatures match, the request is deemed authentic and processed (Shopee API authentication documentation).
Getting your credentials
To begin authenticating with Shopee's Open Platform, you need to register as a developer and create an application. This process will provide you with the necessary credentials.
- Register as a Developer: Navigate to the Shopee Open Platform website and sign up for a developer account. This typically involves agreeing to terms of service and providing basic contact information.
- Create an Application: Once registered, you will be able to create a new application (sometimes referred to as a "shop" or "partner" application). During this step, you will define the application's purpose and request specific API permissions (scopes).
-
Obtain Partner ID and Partner Key: Upon successful application creation, the platform will issue you a unique
Partner IDand a confidentialPartner Key. The Partner ID identifies your application, while the Partner Key is a secret used for signing API requests. The Partner Key should be treated with the same confidentiality as a password. -
Authorize Shops and Get Shop ID & Access Token: For your application to interact with a specific seller's shop, the seller must authorize your application. This usually involves an OAuth 2.0-like flow where the seller grants permission. Upon authorization, your application receives a
Shop ID(identifying the seller's store) and anAccess Token. The Access Token is time-limited and grants your application temporary permission to perform actions on behalf of that specific shop. ARefresh Tokenis also provided to obtain new Access Tokens without repeated seller authorization.
It is critical to securely store your Partner Key and Refresh Tokens, as their compromise could lead to unauthorized access to your application and associated seller accounts. Shopee's documentation provides detailed steps for application creation and authorization (Shopee partner onboarding guide).
Authenticated request example
An authenticated request to the Shopee Open Platform typically involves a few key components: the base URL, the API endpoint, request parameters, a timestamp, and a generated signature. Here's a conceptual example using Python:
import hashlib
import hmac
import time
import requests
import json
# --- Your Credentials ---
PARTNER_ID = 1000000 # Replace with your actual Partner ID
PARTNER_KEY = "YOUR_PARTNER_KEY" # Replace with your actual Partner Key
SHOP_ID = 2000000 # Replace with the authorized Shop ID
ACCESS_TOKEN = "YOUR_ACCESS_TOKEN" # Replace with the valid Access Token
# --- API Configuration ---
BASE_URL = "https://partner.shopeemobile.com"
API_PATH = "/api/v2/product/get_category"
# --- Request Parameters ---
timestamp = int(time.time())
# All parameters, including common_params and biz_params, in a sorted dictionary
# for signature generation.
# Note: Shopee's docs specify the exact order for signature calculation.
# For this example, we'll use a simplified payload structure for demonstration.
common_params = {
"partner_id": PARTNER_ID,
"timestamp": timestamp,
"access_token": ACCESS_TOKEN,
"shop_id": SHOP_ID
}
# For get_category, often no specific biz_params are needed, or they might be included
# directly in the common_params or as part of the path depending on API version.
# Let's assume for this example, common_params are sufficient for the signature.
# --- Signature Generation ---
# The base string for signing is often the API_PATH + JSON-stringified body for POST,
# or normalized query params for GET. Shopee's documentation specifies concatenation
# of partner_id, api_path, timestamp, access_token/shop_id, and JSON body for POST/PUT.
# For GET, it's typically partner_id, api_path, timestamp, access_token/shop_id.
# For a GET request without a body, the base string might be:
# partner_id + api_path + timestamp + access_token + shop_id
# Construct the base string for signature. Refer to Shopee docs for precise order.
# Example for v2 GetCategory: partner_id + api_path + timestamp + access_token + shop_id
# For simplicity here, we'll demonstrate a common pattern.
# The actual string might be constructed from sorted query parameters.
# For V2 APIs, the base string typically is:
# partner_id + API_PATH + timestamp + access_token + shop_id (if applicable)
# + request_body (if POST/PUT and not empty)
# Let's build the base string as per Shopee v2 GetCategory example:
base_string = f"{PARTNER_ID}{API_PATH}{timestamp}{ACCESS_TOKEN}{SHOP_ID}"
hmac_signature = hmac.new(
PARTNER_KEY.encode('utf-8'),
base_string.encode('utf-8'),
hashlib.sha256
).hexdigest()
# --- Constructing the Request URL ---
# Add common parameters and signature to the URL query string
params = {
"partner_id": PARTNER_ID,
"timestamp": timestamp,
"access_token": ACCESS_TOKEN,
"shop_id": SHOP_ID,
"sign": hmac_signature
}
request_url = f"{BASE_URL}{API_PATH}"
# --- Making the Request ---
try:
response = requests.get(request_url, params=params)
response.raise_for_status() # Raise an exception for HTTP errors
data = response.json()
print(json.dumps(data, indent=2))
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}")
print(f"Response body: {err.response.text}")
except Exception as err:
print(f"An error occurred: {err}")
Note on Signature Base String: The exact construction of the signature base string (the data that gets hashed) is critical and highly specific to each API version and endpoint. Developers must consult the official Shopee API Reference for v2 authentication to ensure the correct concatenation order and inclusion of parameters (including potential request body for POST/PUT requests). Incorrect signature generation is the most common cause of authentication failures.
Security best practices
Adhering to security best practices is essential when integrating with the Shopee Open Platform to protect sensitive data and prevent unauthorized access.
- Keep Credentials Confidential: Your Partner Key, Access Tokens, and Refresh Tokens are critical. Never hardcode them directly into your source code. Use environment variables, secure configuration files, or a dedicated secret management service (Google Cloud Secret Manager) to store them.
- Secure Storage: If storing Refresh Tokens or Access Tokens (for short durations), ensure they are encrypted at rest and accessible only by authorized processes. Avoid storing them in publicly accessible locations or client-side storage.
- HTTPS/TLS Enforcement: Always communicate with Shopee APIs over HTTPS to ensure that all data in transit is encrypted and protected from eavesdropping and tampering. Shopee's API endpoints enforce HTTPS (IETF RFC 7230 on HTTP/1.1 Message Syntax).
- Least Privilege Principle: Request only the necessary API scopes for your application's functionality. This limits the potential impact if your application's credentials are compromised.
- Token Expiry and Rotation: Pay attention to Access Token expiry times. Implement proper refresh token mechanisms to obtain new Access Tokens before the current ones expire. Consider regular rotation of your Partner Key if your security policy requires it.
- Timestamp Verification: Shopee's authentication mechanism often relies on timestamps to prevent replay attacks. Ensure your system's clock is synchronized with a reliable time source (e.g., NTP) to avoid signature validation failures due to time discrepancies.
- Error Handling: Implement robust error handling for authentication failures. Generic error messages should be returned to end-users, while detailed logs (without exposing sensitive credentials) can aid in debugging.
- Logging and Monitoring: Log API access attempts and authentication failures. Monitor these logs for suspicious patterns that might indicate an attempted breach or misuse of credentials.
- Input Validation: Sanitize and validate all input data before sending it to Shopee APIs to prevent injection attacks and ensure data integrity.