Get access token from Paypal in Python - Using urllib2 or requests library

假装没事ソ 提交于 2019-12-23 04:48:46

问题


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"

Parameters: -u take client_id:client_secret

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

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

Traceback:

result = urllib2.urlopen(request)

 HTTPError: HTTP Error 400: Bad Request

Can you inform me whats wrong with my python code?


回答1:


I would suggest using requests:

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)



回答2:


It needs URL encoding:

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

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


来源:https://stackoverflow.com/questions/31476540/get-access-token-from-paypal-in-python-using-urllib2-or-requests-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!