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
回溯:
result = urllib2.urlopen(request)
HTTPError: HTTP Error 400: Bad Request
你能告诉我我的python代码有什么问题吗?
答案 0 :(得分:7)
最新答案,但从2020年起,我使用以下python代码生成新的不记名令牌:
如果您尚未这样做,请create a new live app on 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']
来源:
答案 1 :(得分:1)
我建议使用请求:
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)
答案 2 :(得分:0)
它需要URL编码:
param = {
'grant_type': 'client_credentials',
}
data = urllib.urlencode(param)
request = urllib2.Request(token_url, data, header_params)
答案 3 :(得分:0)
这是对python 3.7有用的答案。我需要对我的身份验证凭据应用base64
编码:
import base64
import requests
from backend.config import Config
def get_paypal_access_token(client_id=Config.PAYPAL_CLIENT_ID, secret=Config.PAYPAL_SECRET):
url = "https://api.sandbox.paypal.com/v1/oauth2/token"
payload = 'grant_type=client_credentials'
encoded_auth = base64.b64encode((Config.PAYPAL_CLIENT_ID + ':' + Config.PAYPAL_SECRET).encode())
headers = {
'Authorization': f'Basic {encoded_auth.decode()}',
'Content-Type': 'application/x-www-form-urlencoded'
}
r = requests.request("POST", url, headers=headers, data=payload)
assert r.status_code == 200
return r.json()["access_token"]
我可以通过Config
文件处理我的客户ID和PayPal的机密信息,但是希望很简单,一旦注册了应用程序,便可以用自己的凭据换出这些信息。