curl -v https://api.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-u "client_id:client_secret" \
-d "grant_type=client_credentials"
参数:-u
取client_id
:client_secret
[我在这里传递了client_id
和client_secret
,它在cURL中正常工作。
我正在尝试在Python上实现相同的功能
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',
}
request = urllib2.Request(token_url, param, header_params)
response = urllib2.urlopen(request)
print "Response______", response
追踪:
结果= urllib2.urlopen(请求)
HTTPError: HTTP Error 400: Bad Request
你能告诉我我的python代码有什么问题吗?
我建议使用请求:
import requests
import base64
client_id = ""
client_secret = ""
credentials = "%s:%s" % (client_id, client_secret)
encode_credential = base64.b64encode(credentials.encode('utf-8')).decode('utf-8').replace("\n", "")
headers = {
"Authorization": ("Basic %s" % encode_credential),
'Accept': 'application/json',
'Accept-Language': 'en_US',
}
param = {
'grant_type': 'client_credentials',
}
url = 'https://api.sandbox.paypal.com/v1/oauth2/token'
r = requests.post(url, headers=headers, data=param)
print(r.text)
它需要URL编码:
param = {
'grant_type': 'client_credentials',
}
data = urllib.urlencode(param)
request = urllib2.Request(token_url, data, header_params)
最新答案,但从2020年开始,我使用以下python代码生成一个新的承载令牌。
如果您还没有这样做,请create a new live app on developer.paypal.com
您将收到一个developer.paypal.com
和一个Client ID
,用于生成不记名令牌。
Secret
Python代码:
来源:
import requests
d = {"grant_type" : "client_credentials"}
h = {"Accept": "application/json", "Accept-Language": "en_US"}
cid = "ASOGsGWr7yxepDuthbkKL-WoGNVAS7O0XlZ2ejcWsBA8ZXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
secret = "EJTKAFEYfN9IaVHc4Y-MECzgBivt2MfW6rcyfbVky0T07yRwuuTdXOczuCoEIXXXXXXXXXXXXXXX"
r = requests.post('https://api.paypal.com/v1/oauth2/token', auth=(cid, secret), headers=h, data=d).json()
access_token = r['access_token']