Paypal Rest API - 使用Paypal账户创建支付资源
我正在使用Python和Django,想通过REST API账户支付资源在PayPal上创建一个支付。用curl命令时一切正常。我在Django的视图中成功获取了令牌,但当我尝试用这个令牌进行支付时,却出现了“HTTP错误401:未授权”的错误。
这是我能正常工作的curl命令:
curl -v https://api.sandbox.paypal.com/v1/payments/payment -H 'Content-Type:application/json' -H 'Authorization:Bearer ***my_token***' -d '{ "intent":"sale", "redirect_urls":{ "return_url":"http://www.myurl.com", "cancel_url":"http://www.myurl.com"}, "payer":{ "payment_method":"paypal" },"transactions":[{"amount":{ "total":"0.10", "currency":"USD"},"description":"This is the Test payment transaction description."}]}'
这是我在Django视图中遇到问题的代码:
import urllib2, base64
token = "***my_token***"
values = {
"intent":"sale",
"redirect_urls":{
"return_url":"http://www.myurl.com",
"cancel_url":"http://www.myurl.com"
},
"payer":{
"payment_method":"paypal"
},
"transactions":[
{
"amount":{
"total":"0.10",
"currency":"USD"
},
"description":"This is the Test payment transaction description."
}
]}
data = urllib.urlencode(values)
request1 = urllib2.Request("https://api.sandbox.paypal.com/v1/payments/payment")
base64string = base64.encodestring('%s' % token).replace('\n', '')
request1.add_header("Content-Type", "application/json")
request1.add_header("Authorization", "Bearer %s" % base64string)
result1 = urllib2.urlopen(request1 , data)
response = result1.read()
换句话说,我想把curl的功能在我的视图中实现。
谢谢。
2 个回答
-2
首先,你需要向 https://api.sandbox.paypal.com/v1/oauth2/token
发送一个请求,使用基本的身份验证来获取一个叫做 Bearer token 的东西。拿到这个 token 后,再用它去调用另一个接口 https://api.sandbox.paypal.com/v1/payments/payment
。
你可以使用 PayPal 的 SDK paypalrestsdk 来简化你的 Python 代码,这样写起来会更简单。
0
我不确定你遇到的情况是不是和我一样,但我当时是在尝试为一个第三方的PayPal账户创建支付,而我并没有正确请求权限。结果发现我需要使用权限API来请求正确的权限。