CkJava Requires Chilkat v11.0.0+
CkJava
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 CkJava Downloads
import com.chilkatsoft.*;
public class ChilkatExample {
static {
try {
System.loadLibrary("chilkat");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load.\n" + e);
System.exit(1);
}
}
public static void main(String argv[])
{
boolean success = false;
// See Unlock Chilkat before making requests.
CkHttp http = new CkHttp();
// Load these values from the credential store on the merchant backoffice workstation.
// Never embed the merchant secret in an app distributed to customers.
http.put_Login("SANDBOX_CLIENT_ID");
http.put_Password("SANDBOX_CLIENT_SECRET");
http.put_BasicAuth(true);
CkDateTime issued = new CkDateTime();
issued.SetFromCurrentSystemTime();
CkHttpResponse resp = new CkHttpResponse();
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) {
System.out.println("No HTTP response: " + http.lastErrorText());
return;
}
if ((resp.get_StatusCode() < 200) || (resp.get_StatusCode() >= 300)) {
CkJsonObject errorInfo = new CkJsonObject();
errorInfo.Load(resp.bodyStr());
System.out.println("HTTP " + resp.get_StatusCode() + " " + errorInfo.stringOf("error") + " " + errorInfo.stringOf("error_description"));
System.out.println("PayPal debug ID: " + errorInfo.stringOf("debug_id"));
return;
}
CkJsonObject result = new CkJsonObject();
boolean parsed = result.Load(resp.bodyStr());
if (parsed != true) {
System.out.println("Expected a JSON response; HTTP " + resp.get_StatusCode());
return;
}
String accessToken = result.stringOf("access_token");
int lifetime = result.IntOf("expires_in");
if ((result.HasMember("access_token") != true) || (lifetime <= 0)) {
System.out.println("Missing token or lifetime.");
return;
}
// 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.
CkJsonObject timing = new CkJsonObject();
timing.UpdateString("issued_at",issued.getAsTimestamp(false));
timing.UpdateInt("expires_in",lifetime);
boolean savedTiming = timing.WriteFile("paypal-token-timing.json");
if (savedTiming != true) {
System.out.println("Could not save token timing.");
return;
}
System.out.println("Token received; lifetime in seconds: " + lifetime);
}
}