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

PHP
<?php

use Chilkat2\DateTime;
use Chilkat2\Http;
use Chilkat2\HttpResponse;
use Chilkat2\JsonObject;

// See Unlock Chilkat before making requests.
$http = new 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;
$issued = new DateTime();
$issued->SetFromCurrentSystemTime();
$resp = new HttpResponse();
try {
    $http->HttpStr('POST', 'https://api-m.sandbox.paypal.com/v1/oauth2/token', 'grant_type=client_credentials', 'utf-8', 'application/x-www-form-urlencoded', $resp);
} catch (\Chilkat2\Exception $e) {
    echo 'No HTTP response: ', $e->getMessage(), "\n";
    exit;
}

if (($resp->StatusCode < 200) || ($resp->StatusCode >= 300)) {
    $errorInfo = new JsonObject();
    $errorInfo->Load($resp->BodyStr);
    echo 'HTTP ', $resp->StatusCode, ' ', $errorInfo->StringOf('error'), ' ', $errorInfo->StringOf('error_description'), "\n";
    echo 'PayPal debug ID: ', $errorInfo->StringOf('debug_id'), "\n";
    exit;
}

$result = new JsonObject();
try {
    $result->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
    echo 'Expected a JSON response; HTTP ', $resp->StatusCode, "\n";
    exit;
}

$accessToken = $result->StringOf('access_token');
$lifetime = $result->IntOf('expires_in');
if ((!$result->HasMember('access_token')) || ($lifetime <= 0)) {
    echo "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.
$timing = new JsonObject();
$timing->UpdateString('issued_at', $issued->GetAsTimestamp(false));
$timing->UpdateInt('expires_in', $lifetime);
try {
    $timing->WriteFile('paypal-token-timing.json');
} catch (\Chilkat2\Exception $e) {
    echo "Could not save token timing.\n";
    exit;
}

echo 'Token received; lifetime in seconds: ', $lifetime, "\n";