从Python中的Paypal获取访问令牌-使用urllib2或请求库

问题描述 投票:0回答:3

cURL

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"

参数:-uclient_idclient_secret

[我在这里传递了client_idclient_secret,它在cURL中正常工作。

我正在尝试在Python上实现相同的功能

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代码有什么问题吗?

python curl paypal payment-gateway paypal-sandbox
3个回答
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)

0
投票

它需要URL编码:

param = {
  'grant_type': 'client_credentials',
}

data = urllib.urlencode(param)
request = urllib2.Request(token_url, data, header_params)

0
投票

最新答案,但从2020年开始,我使用以下python代码生成一个新的承载令牌。

如果您还没有这样做,请create a new live app on developer.paypal.com您将收到一个developer.paypal.com和一个Client ID,用于生成不记名令牌。

Secret

Python代码:

enter image description here

来源:

  1. 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']
  2. https://developer.paypal.com/developer/applications/
© www.soinside.com 2019 - 2024. All rights reserved.