Sample code for 30+ languages & platforms
C# 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 C# Downloads

C#
bool success = false;

//  See Unlock Chilkat before making requests.
Chilkat.Http http = new 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;
Chilkat.CkDateTime issued = new Chilkat.CkDateTime();
issued.SetFromCurrentSystemTime();
Chilkat.HttpResponse resp = new 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 != true) {
    Debug.WriteLine("No HTTP response: " + http.LastErrorText);
    return;
}

if ((resp.StatusCode < 200) || (resp.StatusCode >= 300)) {
    Chilkat.JsonObject errorInfo = new Chilkat.JsonObject();
    errorInfo.Load(resp.BodyStr);
    Debug.WriteLine("HTTP " + Convert.ToString(resp.StatusCode) + " " + errorInfo.StringOf("error") + " " + errorInfo.StringOf("error_description"));
    Debug.WriteLine("PayPal debug ID: " + errorInfo.StringOf("debug_id"));
    return;
}

Chilkat.JsonObject result = new Chilkat.JsonObject();
bool parsed = result.Load(resp.BodyStr);
if (parsed != true) {
    Debug.WriteLine("Expected a JSON response; HTTP " + Convert.ToString(resp.StatusCode));
    return;
}

string accessToken = result.StringOf("access_token");
int lifetime = result.IntOf("expires_in");
if ((result.HasMember("access_token") != true) || (lifetime <= 0)) {
    Debug.WriteLine("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.
Chilkat.JsonObject timing = new Chilkat.JsonObject();
timing.UpdateString("issued_at",issued.GetAsTimestamp(false));
timing.UpdateInt("expires_in",lifetime);
bool savedTiming = timing.WriteFile("paypal-token-timing.json");
if (savedTiming != true) {
    Debug.WriteLine("Could not save token timing.");
    return;
}

Debug.WriteLine("Token received; lifetime in seconds: " + Convert.ToString(lifetime));