Unicode C++ Requires Chilkat v11.0.0+
Unicode 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 Unicode C++ Downloads
#include <CkHttpW.h>
#include <CkDateTimeW.h>
#include <CkHttpResponseW.h>
#include <CkJsonObjectW.h>
void ChilkatSample(void)
{
bool success = false;
// See Unlock Chilkat before making requests.
CkHttpW 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(L"SANDBOX_CLIENT_ID");
http.put_Password(L"SANDBOX_CLIENT_SECRET");
http.put_BasicAuth(true);
CkDateTimeW issued;
issued.SetFromCurrentSystemTime();
CkHttpResponseW resp;
success = http.HttpStr(L"POST",L"https://api-m.sandbox.paypal.com/v1/oauth2/token",L"grant_type=client_credentials",L"utf-8",L"application/x-www-form-urlencoded",resp);
if (success != true) {
wprintf(L"No HTTP response: %s\n",http.lastErrorText());
return;
}
if ((resp.get_StatusCode() < 200) || (resp.get_StatusCode() >= 300)) {
CkJsonObjectW errorInfo;
errorInfo.Load(resp.bodyStr());
wprintf(L"HTTP %d %s %s\n",resp.get_StatusCode(),errorInfo.stringOf(L"error"),errorInfo.stringOf(L"error_description"));
wprintf(L"PayPal debug ID: %s\n",errorInfo.stringOf(L"debug_id"));
return;
}
CkJsonObjectW result;
bool parsed = result.Load(resp.bodyStr());
if (parsed != true) {
wprintf(L"Expected a JSON response; HTTP %d\n",resp.get_StatusCode());
return;
}
const wchar_t *accessToken = result.stringOf(L"access_token");
int lifetime = result.IntOf(L"expires_in");
if ((result.HasMember(L"access_token") != true) || (lifetime <= 0)) {
wprintf(L"Missing token or lifetime.\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.
CkJsonObjectW timing;
timing.UpdateString(L"issued_at",issued.getAsTimestamp(false));
timing.UpdateInt(L"expires_in",lifetime);
bool savedTiming = timing.WriteFile(L"paypal-token-timing.json");
if (savedTiming != true) {
wprintf(L"Could not save token timing.\n");
return;
}
wprintf(L"Token received; lifetime in seconds: %d\n",lifetime);
}