python - 使用 urllib2 进行简单 https 身份验证时出现问题(获取 PayPal OAUTH 不记名 token )

标签 python oauth-2.0 paypal urllib2

我正处于将我们的网络应用程序与 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.

关于python - 使用 urllib2 进行简单 https 身份验证时出现问题(获取 PayPal OAUTH 不记名 token ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18236350/

相关文章:

模拟模式下的Python代码

python - Django Manager 的顺序会影响哪些功能?

.net - Postman 客户端凭据流与 Azure AD 保护资源

oauth - 授权服务器不支持使用此方法获取token

php - Paypal 集成 - 添加到购物车按钮

php - PayPal IPN 返回 item_number 为空

python - 无法在 ubuntu 中安装 lxml verison 3.3.5

python - 使用 Python 3.8 的 Jupyter Notebook - NotImplementedError

java - 如何在 android 中为 google api 交换 OAuth2 token 的授权码?

api - 在 Paypal API 与 Stripe API 中进行测试?