使用urllib2进行简单https身份验证时出现问题(用于获取PayPal OAUTH承载令牌)

2024-06-17 11:30:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正处于将我们的web应用程序与PayPal的express checkout 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中实现相同的结果。我已经得到了下面的代码,它产生了401HTTP未经授权的异常。在

^{pr2}$

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


Tags: https命令apiwebid应用程序客户curl
1条回答
网友
1楼 · 发布于 2024-06-17 11:30:22

在这里也遇到了同样的问题。基于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.

相关问题 更多 >