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
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?
Enter the https://api-m.sandbox.paypal.com/v1/oauth2/token request URL. On the Authorization tab, select the Basic Auth type. Type your client ID in the Username box, and type your secret in the Password box. On the Body tab, select x-www-form-urlencoded .
Obtaining the API token To get the API token for a user, an HTTP POST request should be sent to the Token resource. In the post body, username and password are specified in JSON format, and the response body contains a token key with an actual API Token as the value.
To send a GET request with a Bearer Token authorization header using Python, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.
The API uses standard verbs and returns HTTP response codes and JSON-encoded responses. To get started with the PayPal REST API, first create a developer account on the Developer Dashboard. From there you can generate your credentials, authentication token and sandbox accounts.
Late answer, but as of 2021, I use the following python code to generate a new bearer token:
If you haven't done so, create a new live app on developer.paypal.com
You'll receive a Client ID
and a Secret
, which you'll use to generate the Bearer Token.
Python Code:
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']
Sources:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With