Perl Requires Chilkat v11.0.0+
Perl
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 Perl Downloads
use strict;
use warnings;
use Chilkat2;
# See Unlock Chilkat before making requests.
my $http = Chilkat2::Http->new;
# 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);
my $issued = Chilkat2::DateTime->new;
$issued->SetFromCurrentSystemTime();
my $resp = Chilkat2::HttpResponse->new;
my $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) {
print 'No HTTP response: ', $http->LastErrorText, "\n";
exit;
}
if (($resp->StatusCode < 200) || ($resp->StatusCode >= 300)) {
my $errorInfo = Chilkat2::JsonObject->new;
$errorInfo->Load($resp->BodyStr);
print 'HTTP ', $resp->StatusCode, ' ', $errorInfo->StringOf('error'), ' ', $errorInfo->StringOf('error_description'), "\n";
print 'PayPal debug ID: ', $errorInfo->StringOf('debug_id'), "\n";
exit;
}
my $result = Chilkat2::JsonObject->new;
my $parsed = $result->Load($resp->BodyStr);
if (!$parsed) {
print 'Expected a JSON response; HTTP ', $resp->StatusCode, "\n";
exit;
}
my $accessToken = $result->StringOf('access_token');
my $lifetime = $result->IntOf('expires_in');
if ((!$result->HasMember('access_token')) || ($lifetime <= 0)) {
print "Missing token or lifetime.\n";
exit;
}
# 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.
my $timing = Chilkat2::JsonObject->new;
$timing->UpdateString('issued_at', $issued->GetAsTimestamp(0));
$timing->UpdateInt('expires_in', $lifetime);
my $savedTiming = $timing->WriteFile('paypal-token-timing.json');
if (!$savedTiming) {
print "Could not save token timing.\n";
exit;
}
print 'Token received; lifetime in seconds: ', $lifetime, "\n";