我正处于将我们的网络应用程序与 PayPal 的快速结帐 API 集成的第一阶段。要进行购买,我当然必须使用我们的客户 ID 和客户密码获取 Bearer token 。

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

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 

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

请您参考如下方法:

遇到同样的问题。基于Get access token from Paypal in Python - Using urllib2 or requests library工作的 python 代码是:

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 libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the servers don't do "totally standard authentication" then the libraries won't work.


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!