data.netsyms.net/lib/UPSAPIs.lib.php

58 lines
2.1 KiB
PHP
Raw Normal View History

2025-04-23 14:57:31 -06:00
<?php
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/EmptyPHP.php to edit this template
*/
class UPSAPIs {
2025-04-23 14:57:57 -06:00
//const BASEURL = "https://wwwcie.ups.com";
const BASEURL = "https://onlinetools.ups.com";
2025-04-23 14:57:31 -06:00
public static function getBearerToken(bool $force = false): string {
global $memcache;
$clientid = env("ups_client_id");
$clientsecret = env("ups_client_secret");
if (!$force && $memcache->get("logistics.tracking.ups_bearer_token") != false) {
return $memcache->get("logistics.tracking.ups_bearer_token");
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, static::BASEURL . "/security/v1/oauth/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
2025-04-23 15:07:41 -06:00
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic ' . base64_encode("$clientid:$clientsecret")
2025-04-23 14:57:31 -06:00
]);
2025-04-23 15:07:41 -06:00
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
2025-04-23 14:57:31 -06:00
$response = curl_exec($ch);
curl_close($ch);
2025-04-29 18:58:02 -06:00
2025-04-23 14:57:31 -06:00
$data = json_decode($response, true);
$memcache->set("logistics.tracking.ups_bearer_token", $data["access_token"], ($data["expires_in"] * 1) - 120);
return $data["access_token"];
}
public static function getAPIRequest($endpoint) {
$headers = [
2025-04-23 15:00:47 -06:00
"Authorization: Bearer " . UPSAPIs::getBearerToken(false),
2025-04-23 14:57:31 -06:00
"transId: " . uniqid(),
"transactionSrc: Netsyms"
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 45);
2025-04-29 18:58:02 -06:00
curl_setopt($ch, CURLOPT_URL, static::BASEURL . "/api/$endpoint");
2025-04-23 14:57:31 -06:00
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING, "");
$response = curl_exec($ch);
return $response;
}
}