gpt4 book ai didi

python - 异常值 : HTTP Error 400: Bad Request after a Python/urllib2 request to PayPal Sandbox Site

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:28 25 4
gpt4 key购买 nike

我正在尝试将 PayPal REST API 集成到我的网站中。作为第一步,我尝试将 cURL 命令转换为 Python,但我收到了一个Exception Value: HTTP Error 400

我使用的代码(基于 https://stackoverflow.com/a/2003832/2675537 ):

def basic_authorization(user, password):
s = user + ":" + password
return "Basic " + s.encode("base64").rstrip()

req = urllib2.Request("https://api.sandbox.paypal.com/v1/oauth2/token",
headers = {
"Authorization": basic_authorization("EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM", "EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM"),
"Accept": "application/json",
"Accept": "*/*",
"User-Agent": "my-python-app/1",
},
data = '{"message":{"body":' + 'grant_type=client_credentials' + '}}' )

f = urllib2.urlopen(req)
return HttpResponse(f)

这相当于(我猜):

curl https://api.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-u "EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM:EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM" \
-d "grant_type=client_credentials"

追溯在这里:(编辑:断开的链接)

According to PayPal我应该得到这样的回应:

{"scope":"https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-card https://api.paypal.com/v1/vault/credit-card/.* https://api.paypal.com/v1/developer/.*","access_token":"OABI8rm75u.5EIuK7.JrI2sLhnv3rhDgLElKAwTfyys","token_type":"Bearer","app_id":"APP-2EJ531395M785864S","expires_in":28800}

我的代码有错误吗?有更好的方法吗?

最佳答案

首先,我建议您不要在代码示例中以明文形式发布 key 。

您收到“HTTP 错误 400:错误请求”的错误是由于格式错误的请求。

根据文档,请求的格式是:

urllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable])

data may be a string specifying additional data to send to the server, or None if no such data is needed.

headers should be a dictionary, and will be treated as if add_header() was called with each key and value as arguments.

所以你的数据字段传递的是字典而不是字符串,这样会更易读如果您将字段分隔在 Request 类之外。当你有多个标题时要填写的字段,我发现使用 add_header 方法更好,如下所示。

import urllib, urllib2


def basic_authorization(user, password):
s = user + ":" + password
return "Basic " + s.encode("base64").rstrip()

url = "https://api.sandbox.paypal.com/v1/oauth2/token"
params = { "grant_type": client_credentials}
data = urllib.urlencode(params)

req = urllib2.Request(url, data)
req.add_header("Authorization",basic_authorization("XXX"))
req.add_header("Accept", "application/json")
req.add_header("User-Agent", "my-python-app/1")

response = urllib2.urlopen(req)

关于python - 异常值 : HTTP Error 400: Bad Request after a Python/urllib2 request to PayPal Sandbox Site,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20407205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com