### Complete Authorization Code Flow Example - Python Source: https://context7.com/ebay/ebay-oauth-python-client/llms.txt Demonstrates the full OAuth 2.0 authorization code flow. It initializes an EbayOAuthManager, generates an authorization URL, handles the exchange of an authorization code for access and refresh tokens, and provides a method for making authenticated API calls with automatic token refreshing. Dependencies include oauthclient library and requests. ```python from oauthclient.oauth2api import oauth2api from oauthclient.credentialutil import credentialutil from oauthclient.model.model import environment import requests from datetime import datetime class EbayOAuthManager: def __init__(self, config_path, env_type=environment.SANDBOX): # Load credentials credentialutil.load(config_path) self.oauth2api_inst = oauth2api() self.env_type = env_type self.access_token = None self.refresh_token = None self.token_expiry = None def get_authorization_url(self, scopes): """Generate URL for user authorization""" return self.oauth2api_inst.generate_user_authorization_url( self.env_type, scopes, state="csrf_protection_token" ) def authorize_user(self, authorization_code): """Exchange authorization code for tokens""" token = self.oauth2api_inst.exchange_code_for_access_token( self.env_type, authorization_code ) if token.error: raise Exception(f"Authorization failed: {token.error}") self.access_token = token.access_token self.refresh_token = token.refresh_token self.token_expiry = token.token_expiry return token def get_valid_token(self, scopes): """Get valid access token, refreshing if necessary""" # Check if token is expired or about to expire if not self.access_token or datetime.utcnow() >= self.token_expiry: if not self.refresh_token: raise Exception("No refresh token available, re-authorization required") # Refresh the token token = self.oauth2api_inst.get_access_token( self.env_type, self.refresh_token, scopes ) if token.error: raise Exception(f"Token refresh failed: {token.error}") self.access_token = token.access_token self.token_expiry = token.token_expiry return self.access_token def make_api_call(self, method, endpoint, scopes, **kwargs): """Make authenticated API call with automatic token refresh""" token = self.get_valid_token(scopes) headers = kwargs.get('headers', {}) headers['Authorization'] = f"Bearer {token}" kwargs['headers'] = headers base_url = "https://api.sandbox.ebay.com" if self.env_type == environment.SANDBOX else "https://api.ebay.com" url = f"{base_url}{endpoint}" response = requests.request(method, url, **kwargs) return response # Usage example if __name__ == "__main__": # Initialize manager manager = EbayOAuthManager('config/ebay-config.yaml', environment.SANDBOX) # Define scopes scopes = [ "https://api.ebay.com/oauth/api_scope", "https://api.ebay.com/oauth/api_scope/sell.inventory" ] # Step 1: Get authorization URL auth_url = manager.get_authorization_url(scopes) print(f"Visit: {auth_url}") # Step 2: User visits URL and grants consent, you capture the code # code = "v1_captured_code_from_callback" # Step 3: Exchange code for tokens # manager.authorize_user(code) # Step 4: Make API calls (token automatically refreshed if needed) # response = manager.make_api_call( # 'GET', # '/sell/inventory/v1/inventory_item', # scopes # ) # print(f"Status: {response.status_code}, Response: {response.json()}") ``` -------------------------------- ### Get eBay Application Token (Client Credentials) (Python) Source: https://context7.com/ebay/ebay-oauth-python-client/llms.txt Obtains an application-level access token using the client credentials grant type. This is for API calls that do not require user context. Requires pre-loaded credentials and specifies required scopes. Outputs an access token and expiry time or an error message. ```python from oauthclient.oauth2api import oauth2api from oauthclient.credentialutil import credentialutil from oauthclient.model.model import environment # Load credentials first credentialutil.load('config/ebay-config.yaml') # Define scopes required for your application app_scopes = [ "https://api.ebay.com/oauth/api_scope", "https://api.ebay.com/oauth/api_scope/buy.item.feed" ] # Create OAuth2 API instance oauth2api_inst = oauth2api() # Get application token for sandbox environment app_token = oauth2api_inst.get_application_token(environment.SANDBOX, app_scopes) # Check for errors if app_token.error: print("Error obtaining token:", app_token.error) else: print("Access Token:", app_token.access_token) print("Token Expires:", app_token.token_expiry) # Use token for API calls headers = { "Authorization": "Bearer " + app_token.access_token, "Content-Type": "application/json" } # For production environment prod_token = oauth2api_inst.get_application_token(environment.PRODUCTION, app_scopes) if not prod_token.error: print("Production token obtained successfully") print(prod_token) ``` -------------------------------- ### Safely Get eBay Application Token with Error Handling (Python) Source: https://context7.com/ebay/ebay-oauth-python-client/llms.txt This Python function securely obtains an application token from eBay's OAuth service. It includes comprehensive error handling for credential loading (IOError, ValueError) and token retrieval (CredentialNotLoadedError). The function validates the received token for errors and expiry, returning the token object on success or None on failure. It requires configuration details loaded via `credentialutil.load()` and uses `oauth2api` to interact with the OAuth API. ```python import logging from oauthclient.credentialutil import credentialutil from oauthclient.oauth2api import oauth2api from oauthclient.model.model import environment, CredentialNotLoadedError # Configure logging to view OAuth operations logging.basicConfig( level=logging.INFO, format="%(asctime)s: %(levelname)s - %(funcName)s: %(message)s" ) def safe_get_application_token(config_path, env_type, scopes): """Safely obtain application token with error handling""" try: # Load credentials credentialutil.load(config_path) except IOError as e: print(f"Configuration file not found: {e}") return None except ValueError as e: print(f"Invalid configuration format: {e}") return None except Exception as e: print(f"Error loading credentials: {e}") return None try: # Create OAuth instance and get token oauth2api_inst = oauth2api() token = oauth2api_inst.get_application_token(env_type, scopes) # Validate token if token.error: print(f"OAuth Error: {token.error}") if "invalid_scope" in token.error: print("One or more scopes are invalid or not authorized for this app") elif "401" in token.error: print("Invalid credentials - check your appid and certid") return None if not token.access_token: print("No access token received") return None # Token is valid print(f"Token obtained successfully, expires at: {token.token_expiry}") return token except CredentialNotLoadedError as e: print(f"Credentials not loaded: {e}") return None except Exception as e: print(f"Unexpected error: {e}") return None # Example usage with invalid scopes invalid_scopes = [ "https://api.ebay.com/oauth/api_scope", "https://api.ebay.com/oauth/api_scope/sell.inventory" # May not be authorized ] token = safe_get_application_token( 'config/ebay-config.yaml', environment.SANDBOX, invalid_scopes ) if token: print("Token is ready for use") print(f"Token string representation: {str(token)}") else: print("Failed to obtain token, check logs for details") # Example with valid scopes valid_scopes = [ "https://api.ebay.com/oauth/api_scope", "https://api.ebay.com/oauth/api_scope/buy.item.feed" ] token = safe_get_application_token( 'config/ebay-config.yaml', environment.PRODUCTION, valid_scopes ) ``` -------------------------------- ### Load eBay Application Credentials (Python) Source: https://context7.com/ebay/ebay-oauth-python-client/llms.txt Initializes the eBay OAuth Python Client Library by loading application credentials from a configuration file. Supports both YAML and JSON formats. Requires 'oauthclient.credentialutil' and 'oauthclient.model.model'. ```python from oauthclient.credentialutil import credentialutil from oauthclient.model.model import environment import os # Load credentials from YAML configuration file config_path = os.path.join('config', 'ebay-config.yaml') credentialutil.load(config_path) # Alternative: Load from JSON configuration file # config_path = os.path.join('config', 'ebay-config.json') # credentialutil.load(config_path) # Configuration file structure (YAML): """ api.sandbox.ebay.com: appid: your-app-id certid: your-cert-id devid: your-dev-id redirecturi: your-redirect-uri api.ebay.com: appid: your-production-app-id certid: your-production-cert-id devid: your-production-dev-id redirecturi: your-production-redirect-uri """ # Configuration file structure (JSON): """ { "api.sandbox.ebay.com": { "appid": "your-app-id", "certid": "your-cert-id", "devid": "your-dev-id", "redirecturi": "your-redirect-uri" }, "api.ebay.com": { "appid": "your-production-app-id", "certid": "your-production-cert-id", "devid": "your-production-dev-id", "redirecturi": "your-production-redirect-uri" } } """ ``` -------------------------------- ### eBay OAuth Environment Types and Credentials Management (Python) Source: https://context7.com/ebay/ebay-oauth-python-client/llms.txt This Python code snippet demonstrates how to interact with eBay's environment configurations (Sandbox and Production) and manage credentials using the `oauthclient` library. It shows how to access environment details like config IDs and endpoints, load credentials from a YAML file, retrieve specific environment credentials (client ID, dev ID, redirect URI), and work with `oAuth_token` objects, including their string representation and error handling. ```python from oauthclient.model.model import environment, env_type, credentials, oAuth_token from oauthclient.credentialutil import credentialutil # Understanding environment types print("Sandbox Configuration:") print(f" Config ID: {environment.SANDBOX.config_id}") print(f" Web Endpoint: {environment.SANDBOX.web_endpoint}") print(f" API Endpoint: {environment.SANDBOX.api_endpoint}") print("\nProduction Configuration:") print(f" Config ID: {environment.PRODUCTION.config_id}") print(f" Web Endpoint: {environment.PRODUCTION.web_endpoint}") print(f" API Endpoint: {environment.PRODUCTION.api_endpoint}") # Load and access credentials credentialutil.load('config/ebay-config.yaml') # Get sandbox credentials sandbox_cred = credentialutil.get_credentials(environment.SANDBOX) print(f"\nSandbox Credentials:") print(f" Client ID: {sandbox_cred.client_id}") print(f" Dev ID: {sandbox_cred.dev_id}") print(f" Redirect URI: {sandbox_cred.ru_name}") # Note: client_secret should not be logged # Get production credentials prod_cred = credentialutil.get_credentials(environment.PRODUCTION) print(f"\nProduction Credentials Loaded: {prod_cred.client_id is not None}") # Working with token objects token = oAuth_token( access_token="v1_example_token", refresh_token="v1_example_refresh", token_expiry=None, refresh_token_expiry=None ) # Token string representation print(f"\nToken representation: {str(token)}") # Error token example error_token = oAuth_token(error="401: Invalid credentials") print(f"Error token: {str(error_token)}") ``` -------------------------------- ### Generate eBay User Authorization URL with State Source: https://context7.com/ebay/ebay-oauth-python-client/llms.txt Generates a URL to redirect users to eBay for OAuth2 authorization. It includes optional state parameter for CSRF protection. Requires the `oauth2api` instance and user scopes. Outputs a URL string. ```python from oauthclient.oauth2api import oauth2api from oauthclient.credentialutil import credentialutil from oauthclient.model.model import environment # Example usage: signin_url_with_state = oauth2api_inst.generate_user_authorization_url( environment.SANDBOX, user_scopes, state="random_state_string_12345" ) ``` -------------------------------- ### OAuth Error Handling and Token Validation - Python Source: https://context7.com/ebay/ebay-oauth-python-client/llms.txt This snippet focuses on error handling within the OAuth process, including potential exceptions like 'CredentialNotLoadedError'. It imports necessary classes for OAuth operations and logging. This code forms part of a larger library for managing eBay API authentication. ```python from oauthclient.oauth2api import oauth2api from oauthclient.credentialutil import credentialutil, CredentialNotLoadedError from oauthclient.model.model import environment, oAuth_token import logging ``` -------------------------------- ### Exchange Authorization Code for Access Token Source: https://context7.com/ebay/ebay-oauth-python-client/llms.txt Exchanges an authorization code received from eBay after user consent for access and refresh tokens. This process requires the `oauth2api` instance and the authorization code. It outputs access token, expiry times, and refresh token, or an error message. Dependencies include `oauthclient` and `requests`. ```python from oauthclient.oauth2api import oauth2api from oauthclient.credentialutil import credentialutil from oauthclient.model.model import environment import requests # Load credentials credentialutil.load('config/ebay-config.yaml') # Create OAuth2 API instance oauth2api_inst = oauth2api() # Authorization code received from redirect callback authorization_code = "v1_abc123def456..." # Exchange code for tokens user_token = oauth2api_inst.exchange_code_for_access_token( environment.SANDBOX, authorization_code ) # Handle response if user_token.error: print("Error exchanging code:", user_token.error) else: print("Access Token:", user_token.access_token) print("Token Expires:", user_token.token_expiry) print("Refresh Token:", user_token.refresh_token) print("Refresh Token Expires:", user_token.refresh_token_expiry) # Store refresh token securely for future use stored_refresh_token = user_token.refresh_token # Use access token for API calls headers = { "Authorization": "Bearer " + user_token.access_token, "Content-Type": "application/json" } response = requests.get( "https://api.sandbox.ebay.com/sell/inventory/v1/inventory_item", headers=headers ) print("API Response:", response.status_code) ``` -------------------------------- ### Generate eBay User Authorization URL (Python) Source: https://context7.com/ebay/ebay-oauth-python-client/llms.txt Generates the authorization URL required for the OAuth 2.0 authorization code flow. Users are redirected to this URL to grant consent for your application. Requires pre-loaded credentials and specified user-level scopes. Outputs a URL for user redirection. ```python from oauthclient.oauth2api import oauth2api from oauthclient.credentialutil import credentialutil from oauthclient.model.model import environment # Load credentials credentialutil.load('config/ebay-config.yaml') # Define user-level scopes user_scopes = [ "https://api.ebay.com/oauth/api_scope", "https://api.ebay.com/oauth/api_scope/sell.inventory", "https://api.ebay.com/oauth/api_scope/sell.marketing", "https://api.ebay.com/oauth/api_scope/sell.account", "https://api.ebay.com/oauth/api_scope/sell.fulfillment" ] # Create OAuth2 API instance oauth2api_inst = oauth2api() # Generate authorization URL for sandbox signin_url = oauth2api_inst.generate_user_authorization_url( environment.SANDBOX, user_scopes ) print("Redirect user to:", signin_url) ``` -------------------------------- ### Refresh User Access Token with Refresh Token Source: https://context7.com/ebay/ebay-oauth-python-client/llms.txt Obtains a new access token using a refresh token when the current access token expires, avoiding user re-authentication. Requires the `oauth2api` instance, a stored refresh token, and the original scopes. Outputs a new access token and its expiry, or an error. Dependencies include `oauthclient` and `requests`. ```python from oauthclient.oauth2api import oauth2api from oauthclient.credentialutil import credentialutil from oauthclient.model.model import environment import requests # Load credentials credentialutil.load('config/ebay-config.yaml') # Create OAuth2 API instance oauth2api_inst = oauth2api() # Stored refresh token from previous authorization refresh_token = "v1_xyz789..." # Define required scopes (must match or be subset of original scopes) scopes = [ "https://api.ebay.com/oauth/api_scope", "https://api.ebay.com/oauth/api_scope/sell.inventory", "https://api.ebay.com/oauth/api_scope/sell.marketing" ] # Get new access token using refresh token new_token = oauth2api_inst.get_access_token( environment.SANDBOX, refresh_token, scopes ) # Handle response if new_token.error: print("Error refreshing token:", new_token.error) # Token may be expired, need to re-authorize user else: print("New Access Token:", new_token.access_token) print("Token Expires:", new_token.token_expiry) # Use new access token for API calls headers = { "Authorization": "Bearer " + new_token.access_token, "Content-Type": "application/json" } # Make authenticated API request response = requests.post( "https://api.sandbox.ebay.com/sell/inventory/v1/inventory_item", headers=headers, json={ "sku": "ITEM-001", "product": { "title": "Sample Product" } } ) ``` -------------------------------- ### Exchange Authorization Code for Access Token (Python) Source: https://github.com/ebay/ebay-oauth-python-client/blob/master/README.adoc This function exchanges an authorization code for an access token using the eBay OAuth API. It is typically used in the Authorization Code Grant flow. The access token is usually short-lived, and a refresh token can be used to obtain a new one if the current one expires. ```python from ebay_oauth import oauth2api # Assuming 'authorization_code' is obtained from the user's interaction access_token_data = oauth2api.exchange_code_for_access_token(authorization_code, redirect_uri) access_token = access_token_data['access_token'] refresh_token = access_token_data['refresh_token'] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.