2

我正处于将我们的网络应用程序与 PayPal 的快速结帐 API 集成的第一阶段。对于我进行购买,我当然必须使用我们的客户 ID 和我们的客户密码来获得一个不记名令牌。

我使用以下 curl 命令成功获取该令牌:

curl https://api.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-u "ourID:ourSecret" \
-d "grant_type=client_credentials"

现在我正在尝试使用 urllib2 在 python 中实现相同的结果。我得到了以下代码,它产生了 401 HTTP Unauthorized 异常。

    import urllib
    import urllib2

    url = "https://api.sandbox.paypal.com/v1/oauth2/token"

    PAYPAL_CLIENT_ID = "ourID"
    PAYPAL_CLIENT_SECRET = "ourSecret"

    passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
    passman.add_password(None, url, PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET)
    authhandler = urllib2.HTTPBasicAuthHandler(passman)
    opener = urllib2.build_opener(authhandler)
    urllib2.install_opener(opener)

    req = urllib2.Request( url=url,
      headers={
            "Accept": "application/json",
            "Accept-Language": "en_US",
            },
      data =urllib.urlencode({
            "grant_type":"client_credentials",
            }),)

    result = urllib2.urlopen(req).read()
    print result

有谁知道我在上面做错了什么?非常感谢您的任何见解

4

1 回答 1

0

在这里遇到同样的问题。基于Get access token from Paypal in Python - Using urllib2 or requests library working python code是:

import urllib
import urllib2
import base64
token_url = 'https://api.sandbox.paypal.com/v1/oauth2/token'
client_id = '.....'
client_secret = '....'

credentials = "%s:%s" % (client_id, client_secret)
encode_credential = base64.b64encode(credentials.encode('utf-8')).decode('utf-8').replace("\n", "")

header_params = {
    "Authorization": ("Basic %s" % encode_credential),
    "Content-Type": "application/x-www-form-urlencoded",
    "Accept": "application/json"
}
param = {
    'grant_type': 'client_credentials',
}
data = urllib.urlencode(param)

request = urllib2.Request(token_url, data, header_params)
response = urllib2.urlopen(request).open()
print response

我相信,原因在Python urllib2 Basic Auth Problem中有解释

Python 库,根据 HTTP 标准,首先发送一个未经身份验证的请求,然后只有当它被 401 重试回答时,才会发送正确的凭据。如果服务器不执行“完全标准的身份验证”,那么库将无法工作。

于 2015-10-05T15:34:57.747 回答