获取 Ebay OAuth 令牌

问题描述 投票:0回答:3

这周的大部分时间我都在研究 ebaySDK。我已成功将交易和购物 API 集成到我的项目中。对于交易 API,我使用的是 Auth n Auth 令牌,其有效期长达 18 个月。我销售 API 所需的 OAuth 令牌仅在一天内有效,因此我需要在其过期之前定期获取它。 我按照网站上的文档进行操作,甚至尝试查看 github 上的 python 存储库,但到目前为止我还无法继续前进。这是我的请求代码的快速片段,我做错了什么?

import requests, json, base64, xmltodict

AppSettings = {
    'app_id' : 'my_app_id',
    'app_secret' : 'my_app_secret',
    'dev_id': 'my_dev_id',
    'ruName': 'the_ruName_for_my_app'
}
authHeaderData =  AppSettings['app_id']+':'+AppSettings['app_secret']
encodedAuthHeader = base64.b64encode(authHeaderData)

session = requests.Session()

print encodedAuthHeader 
url = 'https://api.ebay.com/identity/v1/oauth2/token'

session.headers.update({
    'Content-Type':'application/x-www-form-urlencoded',
    'Authorization':'Basic '+encodedAuthHeader
    })

data = {
    'grant_type':'client_credentials',
    'redirect_uri': AppSettings['ruName'],
    'scope':'https://api.ebay.com/oauth/api_scope'
}

response = session.post(url, data=data).json()
print response

我得到的回复是:

{u'error_description': u'client authentication failed', u'error': u'invalid_client'}

我检查了所有的钥匙。我什至尝试通过 eBay 提供的生产登录来获取令牌,但无济于事。我从 ebay 提供的 url 得到的响应是 html 和 js 代码(没有 JSON 或任何数据)。

有人遇到过类似的问题吗?我该如何解决这个问题?我的请求有误吗?任何见解都将不胜感激

python django oauth ebay-api
3个回答
13
投票

因为遍历 eBay 文档来找到这个答案真是一场噩梦,所以我想我应该发布解决这个问题的函数。

import requests, urllib, base64

def getAuthToken():
     AppSettings = {
          'client_id':'<client_id>',
          'client_secret':'<client_secret>',
          'ruName':'<ruName>'}

     authHeaderData = AppSettings['client_id'] + ':' + AppSettings['client_secret']
     encodedAuthHeader = base64.b64encode(str.encode(authHeaderData))

     headers = {
          "Content-Type" : "application/x-www-form-urlencoded", 
          "Authorization" : "Basic " + str(encodedAuthHeader)
          }

     body= {
          "grant_type" : "client_credentials",
          "redirect_uri" : AppSettings['ruName'],
          "scope" : "https://api.ebay.com/oauth/api_scope"
      }

     data = urllib.parse.urlencode(body)

     tokenURL = "https://api.ebay.com/identity/v1/oauth2/token"

     response = requests.post(tokenURL, headers=headers, data=data) 
     return response.json()


response = getAuthToken()
print(response)
response['access_token'] #access keys as required
response['error_description'] #if errors

2
投票

@sunny babau 我和你有同样的问题。这确实是由 b' 和尾随的 ' 引起的。在上面的代码中添加以下行(删除这些字符)后,它对我有用:

encodedAuthHeader = str(encodedAuthHeader)[2:len(str(encodedAuthHeader))-1]

0
投票

我使用 Python 脚本创建了一个解决方案来解决此问题,该脚本可自动执行 eBay OAuth 用户身份验证、令牌检索和编码授权代码的解码。

这是 Github 存储库:

https://github.com/johnchervanev/ebay_authentication_token

这是代码:

import requests
from base64 import b64encode
from urllib.parse import urlparse, parse_qs
import webbrowser

# Prompt the user to enter their eBay production application credentials and redirect URI
client_id = input("Enter your eBay client ID: ")
client_secret = input("Enter your eBay client secret: ")
redirect_uri = input("Enter your eBay redirect URI: ")

# Define all the scopes based on your requirements
scopes = (
    "https://api.ebay.com/oauth/api_scope "
    "https://api.ebay.com/oauth/api_scope/sell.marketing.readonly "
    "https://api.ebay.com/oauth/api_scope/sell.marketing "
    "https://api.ebay.com/oauth/api_scope/sell.inventory.readonly "
    "https://api.ebay.com/oauth/api_scope/sell.inventory "
    "https://api.ebay.com/oauth/api_scope/sell.account.readonly "
    "https://api.ebay.com/oauth/api_scope/sell.account "
    "https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly "
    "https://api.ebay.com/oauth/api_scope/sell.fulfillment "
    "https://api.ebay.com/oauth/api_scope/sell.analytics.readonly "
    "https://api.ebay.com/oauth/api_scope/sell.finances "
    "https://api.ebay.com/oauth/api_scope/sell.payment.dispute "
    "https://api.ebay.com/oauth/api_scope/commerce.identity.readonly "
    "https://api.ebay.com/oauth/api_scope/sell.reputation "
    "https://api.ebay.com/oauth/api_scope/sell.reputation.readonly "
    "https://api.ebay.com/oauth/api_scope/commerce.notification.subscription "
    "https://api.ebay.com/oauth/api_scope/commerce.notification.subscription.readonly "
    "https://api.ebay.com/oauth/api_scope/sell.stores "
    "https://api.ebay.com/oauth/api_scope/sell.stores.readonly"
)

# Set the target endpoint for the consent request in production
consent_endpoint_production = "https://auth.ebay.com/oauth2/authorize"
token_endpoint = "https://api.ebay.com/identity/v1/oauth2/token"

# Define the consent URL
consent_url = (
    f"{consent_endpoint_production}?"
    f"client_id={client_id}&"
    f"redirect_uri={redirect_uri}&"
    f"response_type=code&"
    f"scope={scopes}"
)

# Open the consent URL in the default web browser
webbrowser.open(consent_url)

print("Opening the browser. Please grant consent in the browser.")

# Retrieve the authorization code from the user after they grant consent
authorization_code_url = input("Enter the authorization code URL: ")

# Parse the URL to extract the authorization code
parsed_url = urlparse(authorization_code_url)
query_params = parse_qs(parsed_url.query)
authorization_code = query_params.get('code', [])[0]

# Make the authorization code grant request to obtain the token
payload = {
    "grant_type": "authorization_code",
    "code": authorization_code,
    "redirect_uri": redirect_uri
}

# Encode the client credentials for the Authorization header
credentials = f"{client_id}:{client_secret}"
encoded_credentials = b64encode(credentials.encode()).decode()

# Set the headers for the token request
token_headers = {
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": f"Basic {encoded_credentials}"
}

# Make the POST request to the token endpoint
response = requests.post(token_endpoint, headers=token_headers, data=payload)

# Check the response
if response.status_code == 200:
    # Parse and print the response JSON
    response_json = response.json()
    print("Response containing the User access token:")
    print(response_json)
else:
    print(f"Error: {response.status_code}, {response.text}")
© www.soinside.com 2019 - 2024. All rights reserved.