Sample code for 30+ languages & platforms
Python Requires Chilkat v11.0.0+

PayPal: Get a sandbox access token

See more PayPal Examples

Exchange a sandbox REST app client ID and secret for a bearer token on a merchant-controlled backoffice workstation. PayPal supplies its lifetime in seconds. Store the token in a protected credential store; the companion expiry example reads only timing metadata.

PayPal documentation

Chilkat Python Downloads

Python
import sys
import chilkat2

success = False

# See Unlock Chilkat before making requests.
http = chilkat2.Http()
# Load these values from the credential store on the merchant backoffice workstation.
# Never embed the merchant secret in an app distributed to customers.
http.Login = "SANDBOX_CLIENT_ID"
http.Password = "SANDBOX_CLIENT_SECRET"
http.BasicAuth = True
issued = chilkat2.CkDateTime()
issued.SetFromCurrentSystemTime()
resp = chilkat2.HttpResponse()
success = http.HttpStr("POST","https://api-m.sandbox.paypal.com/v1/oauth2/token","grant_type=client_credentials","utf-8","application/x-www-form-urlencoded",resp)
if (success != True):
    print("No HTTP response: " + http.LastErrorText)
    sys.exit()

if ((resp.StatusCode < 200) or (resp.StatusCode >= 300)):
    errorInfo = chilkat2.JsonObject()
    errorInfo.Load(resp.BodyStr)
    print("HTTP " + str(resp.StatusCode) + " " + errorInfo.StringOf("error") + " " + errorInfo.StringOf("error_description"))
    print("PayPal debug ID: " + errorInfo.StringOf("debug_id"))
    sys.exit()

result = chilkat2.JsonObject()
parsed = result.Load(resp.BodyStr)
if (parsed != True):
    print("Expected a JSON response; HTTP " + str(resp.StatusCode))
    sys.exit()

accessToken = result.StringOf("access_token")
lifetime = result.IntOf("expires_in")
if ((result.HasMember("access_token") != True) or (lifetime <= 0)):
    print("Missing token or lifetime.")
    sys.exit()

# Supply accessToken to Http.AuthToken. Never log the bearer token or client secret.
# Save only timing metadata here, relative to the start of the token request.
timing = chilkat2.JsonObject()
timing.UpdateString("issued_at",issued.GetAsTimestamp(False))
timing.UpdateInt("expires_in",lifetime)
savedTiming = timing.WriteFile("paypal-token-timing.json")
if (savedTiming != True):
    print("Could not save token timing.")
    sys.exit()

print("Token received; lifetime in seconds: " + str(lifetime))