PowerShell Requires Chilkat v11.0.0+
PowerShell
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 PowerShell Downloads
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"
$success = $false
# See Unlock Chilkat before making requests.
$http = New-Object Chilkat.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 = New-Object Chilkat.CkDateTime
$issued.SetFromCurrentSystemTime()
$resp = New-Object Chilkat.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 -ne $true) {
$("No HTTP response: " + $http.LastErrorText)
exit
}
if (($resp.StatusCode -lt 200) -or ($resp.StatusCode -ge 300)) {
$errorInfo = New-Object Chilkat.JsonObject
$errorInfo.Load($resp.BodyStr)
$("HTTP " + $resp.StatusCode + " " + $errorInfo.StringOf("error") + " " + $errorInfo.StringOf("error_description"))
$("PayPal debug ID: " + $errorInfo.StringOf("debug_id"))
exit
}
$result = New-Object Chilkat.JsonObject
$parsed = $result.Load($resp.BodyStr)
if ($parsed -ne $true) {
$("Expected a JSON response; HTTP " + $resp.StatusCode)
exit
}
$accessToken = $result.StringOf("access_token")
$lifetime = $result.IntOf("expires_in")
if (($result.HasMember("access_token") -ne $true) -or ($lifetime -le 0)) {
$("Missing token or lifetime.")
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 = New-Object Chilkat.JsonObject
$timing.UpdateString("issued_at",$issued.GetAsTimestamp($false))
$timing.UpdateInt("expires_in",$lifetime)
$savedTiming = $timing.WriteFile("paypal-token-timing.json")
if ($savedTiming -ne $true) {
$("Could not save token timing.")
exit
}
$("Token received; lifetime in seconds: " + $lifetime)