在Python中从Paypal获取访问令牌 - 使用urllib2或请求库 [英] Get access token from Paypal in Python - Using urllib2 or requests library

查看:889
本文介绍了在Python中从Paypal获取访问令牌 - 使用urllib2或请求库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 take client_id client_secret

Parameters: -u take client_id:client_secret

我通过我的 client_id client_secret ,它在cURL中正常工作。

Here I pass my client_id and client_secret, It's worked properly in cURL.

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

I am trying to same things implement on 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)

result = urllib2.urlopen(request)

 HTTPError: HTTP Error 400: Bad Request


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

Can you inform me whats wrong with my python code?

推荐答案

我建议使用请求:

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)

这篇关于在Python中从Paypal获取访问令牌 - 使用urllib2或请求库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆