Authenticating Multiple UPS Accounts with UPS REST API

PHP Sample Code#

The following code implements the oauth workflow described at: https://developer.ups.com/api/reference/oauth/authorization-code. This allows you to generate API tokens to make requests on behalf of multiple UPS users/accounts.

The access_token returned here can be plugged into the RocketShipIt key parameter to make requests on behalf of the user.

<?php

// oauth.php

// See: https://developer.ups.com/api/reference/oauth/authorization-code

// Connect multiple UPS accounts to your single client_id/client_secret

// CHANGE THESE SETTINGS HERE
// $client_id = 'YOUR_CLIENT_ID'; 
// $client_secret = 'YOUR_CLIENT_SECRET'; 
// $redirect_uri has to match what you set in the UPS developer portal for your callback URL
$redirect_uri = 'https://abc123.ngrok-free.app/oauth.php'; // Replace with your redirect URI
// END OF SETTINGS

// Step 1: Redirect the user to the UPS login screen
if (!isset($_GET['code'])) {
    $state = bin2hex(random_bytes(16)); // Generate a random state
    $scope = 'read'; // Specify the desired scope

    $auth_url = 'https://wwwcie.ups.com/security/v1/oauth/authorize?client_id=' . urlencode($client_id) .
                '&redirect_uri=' . urlencode($redirect_uri) .
                '&response_type=code' .
                '&state=' . urlencode($state) .
                '&scope=' . urlencode($scope);

    header('Location: ' . $auth_url);
    exit;
}

// Step 4: Retrieve the Auth-Code from the redirected URL
$auth_code = $_GET['code'];

// Step 5: Retrieve the access token and refresh token
$token_url = 'https://wwwcie.ups.com/security/v1/oauth/token';
$auth_header = 'Basic ' . base64_encode($client_id . ':' . $client_secret);

$data = http_build_query([
    'grant_type' => 'authorization_code',
    'code' => $auth_code,
    'redirect_uri' => $redirect_uri,
]);

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => $token_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => $data,
    CURLOPT_HTTPHEADER => [
        'Authorization: ' . $auth_header,
        'Content-Type: application/x-www-form-urlencoded',
    ],
]);

$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($http_code == 200) {
    $token_data = json_decode($response, true);
    $access_token = $token_data['access_token'];
    $refresh_token = $token_data['refresh_token'];

    // Step 7: Save the access token and refresh token to a temporary file
    // TODO: this just illustrates capturing the token, you will probably want
    // to save to a database instead
    $temp_file = 'temp_tokens.txt';
    $data = "access_token=$access_token\nrefresh_token=$refresh_token";
    file_put_contents($temp_file, $data);

    echo 'Access token and refresh token saved to ' . $temp_file;
} else {
    echo 'Error retrieving access token: ' . $response;
}

curl_close($curl);