在 Python 中从 Paypal 获取访问令牌 - 使用 urllib2 或 requests 库

Jay*_*tel 5 python curl paypal payment-gateway paypal-sandbox

卷曲

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"
Run Code Online (Sandbox Code Playgroud)

参数: -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
Run Code Online (Sandbox Code Playgroud)

追溯:

结果 = urllib2.urlopen(请求)

 HTTPError: HTTP Error 400: Bad Request
Run Code Online (Sandbox Code Playgroud)

你能告诉我我的python代码有什么问题吗?

Ped*_*ito 10

迟到的答案,但截至 2020 年,我使用以下 python 代码生成新的不记名令牌:

如果您还没有这样做,请在 developer.paypal.com 上创建一个新的实时应用程序。
您将收到Client IDSecret,您将使用它们来生成不记名令牌。

在此处输入图片说明

蟒蛇代码:

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']
Run Code Online (Sandbox Code Playgroud)

资料来源:

  1. https://developer.paypal.com/developer/applications/
  2. https://www.paypal.com/smarthelp/article/how-do-i-get-an-access-token-ts2128


hei*_*nst 3

我建议使用请求:

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)
Run Code Online (Sandbox Code Playgroud)

  • @S͢kyD͢ream 因为它是 Python 最好的 HTTP 库,与标准库相比,你可以用更少的代码/库做更多的事情 (3认同)