Delphi ActiveX Requires Chilkat v11.0.0+
Delphi ActiveX
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 Delphi ActiveX Downloads
var
success: Integer;
http: TChilkatHttp;
issued: TCkDateTime;
resp: TChilkatHttpResponse;
errorInfo: TChilkatJsonObject;
result: TChilkatJsonObject;
parsed: Integer;
accessToken: WideString;
lifetime: Integer;
timing: TChilkatJsonObject;
savedTiming: Integer;
begin
success := 0;
// See Unlock Chilkat before making requests.
http := TChilkatHttp.Create(Self);
// 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 := 1;
issued := TCkDateTime.Create(Self);
issued.SetFromCurrentSystemTime();
resp := TChilkatHttpResponse.Create(Self);
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.ControlInterface);
if (success <> 1) then
begin
Memo1.Lines.Add('No HTTP response: ' + http.LastErrorText);
Exit;
end;
if ((resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
begin
errorInfo := TChilkatJsonObject.Create(Self);
errorInfo.Load(resp.BodyStr);
Memo1.Lines.Add('HTTP ' + IntToStr(resp.StatusCode) + ' ' + errorInfo.StringOf('error') + ' ' + errorInfo.StringOf('error_description'));
Memo1.Lines.Add('PayPal debug ID: ' + errorInfo.StringOf('debug_id'));
Exit;
end;
result := TChilkatJsonObject.Create(Self);
parsed := result.Load(resp.BodyStr);
if (parsed <> 1) then
begin
Memo1.Lines.Add('Expected a JSON response; HTTP ' + IntToStr(resp.StatusCode));
Exit;
end;
accessToken := result.StringOf('access_token');
lifetime := result.IntOf('expires_in');
if ((result.HasMember('access_token') <> 1) or (lifetime <= 0)) then
begin
Memo1.Lines.Add('Missing token or lifetime.');
Exit;
end;
// 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 := TChilkatJsonObject.Create(Self);
timing.UpdateString('issued_at',issued.GetAsTimestamp(0));
timing.UpdateInt('expires_in',lifetime);
savedTiming := timing.WriteFile('paypal-token-timing.json');
if (savedTiming <> 1) then
begin
Memo1.Lines.Add('Could not save token timing.');
Exit;
end;
Memo1.Lines.Add('Token received; lifetime in seconds: ' + IntToStr(lifetime));