C++ Requires Chilkat v11.0.0+
C++
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 C++ Downloads
#include <CkHttp.h>
#include <CkDateTime.h>
#include <CkHttpResponse.h>
#include <CkJsonObject.h>
void ChilkatSample(void)
{
bool success = false;
// See Unlock Chilkat before making requests.
CkHttp 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.put_Login("SANDBOX_CLIENT_ID");
http.put_Password("SANDBOX_CLIENT_SECRET");
http.put_BasicAuth(true);
CkDateTime issued;
issued.SetFromCurrentSystemTime();
CkHttpResponse resp;
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) {
std::cout << "No HTTP response: " << http.lastErrorText() << "\r\n";
return;
}
if ((resp.get_StatusCode() < 200) || (resp.get_StatusCode() >= 300)) {
CkJsonObject errorInfo;
errorInfo.Load(resp.bodyStr());
std::cout << "HTTP " << resp.get_StatusCode() << " " << errorInfo.stringOf("error") << " " << errorInfo.stringOf("error_description") << "\r\n";
std::cout << "PayPal debug ID: " << errorInfo.stringOf("debug_id") << "\r\n";
return;
}
CkJsonObject result;
bool parsed = result.Load(resp.bodyStr());
if (parsed != true) {
std::cout << "Expected a JSON response; HTTP " << resp.get_StatusCode() << "\r\n";
return;
}
const char *accessToken = result.stringOf("access_token");
int lifetime = result.IntOf("expires_in");
if ((result.HasMember("access_token") != true) || (lifetime <= 0)) {
std::cout << "Missing token or lifetime." << "\r\n";
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;
timing.UpdateString("issued_at",issued.getAsTimestamp(false));
timing.UpdateInt("expires_in",lifetime);
bool savedTiming = timing.WriteFile("paypal-token-timing.json");
if (savedTiming != true) {
std::cout << "Could not save token timing." << "\r\n";
return;
}
std::cout << "Token received; lifetime in seconds: " << lifetime << "\r\n";
}