Lua Requires Chilkat v11.0.0+
Lua
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.
Chilkat Lua Downloads
local chilkat = require("chilkat")
-- See Unlock Chilkat before making requests.
local http = chilkat.Http.new()
-- 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.basic_auth = true
local issued = chilkat.DateTime.new()
issued:set_from_current_system_time()
local resp = chilkat.HttpResponse.new()
local success = http:http_str("POST", "https://api-m.sandbox.paypal.com/v1/oauth2/token", "grant_type=client_credentials", "utf-8", "application/x-www-form-urlencoded", resp)
if not success then
print("No HTTP response: " .. http.last_error_text)
return
end
if (resp.status_code < 200) or (resp.status_code >= 300) then
local errorInfo = chilkat.JsonObject.new()
errorInfo:load(resp.body_str)
print("HTTP " .. resp.status_code .. " " .. errorInfo:string_of("error") .. " " .. errorInfo:string_of("error_description"))
print("PayPal debug ID: " .. errorInfo:string_of("debug_id"))
return
end
local result = chilkat.JsonObject.new()
local parsed = result:load(resp.body_str)
if not parsed then
print("Expected a JSON response; HTTP " .. resp.status_code)
return
end
local accessToken = result:string_of("access_token")
local lifetime = result:int_of("expires_in")
if (not result:has_member("access_token")) or (lifetime <= 0) then
print("Missing token or lifetime.")
return
end
-- 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.
local timing = chilkat.JsonObject.new()
timing:update_string("issued_at", issued:get_as_timestamp(false))
timing:update_int("expires_in", lifetime)
local savedTiming = timing:write_file("paypal-token-timing.json")
if not savedTiming then
print("Could not save token timing.")
return
end
print("Token received; lifetime in seconds: " .. lifetime)