Request UPS access token using cURL and PHP
January 21, 2024
$client_id = '######';
$client_secret = '######';
$UPS_credentials = base64_encode("$client_id:$client_secret");
$UPS_url = 'https://onlinetools.ups.com/security/v1/oauth/token?';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $UPS_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($curl, CURLOPT_HTTPHEADER, [
"accept: application/json",
"x-merchant-id: $client_id",
"Authorization: Basic $UPS_credentials",
"Content-Type: application/x-www-form-urlencoded"
]);
$error = curl_error($curl);
$response = curl_exec($curl);
curl_close($curl);
if($error){
echo $error;
}else{
$data = json_decode($response);
$UPS_get_token_status = $data -> status;
if($UPS_get_token_status !== "approved"){
echo 'Error: Token request not approved.';
}else{
// Token as been created
$UPS_access_token = $data -> access_token;
// do stuff here...
}
}