Last active
June 23, 2020 16:08
-
-
Save JoelLisenby/6221c35d2a8e27c0647bcda13ba098e2 to your computer and use it in GitHub Desktop.
Simple PHP function to check if USPS package has been accepted / picked up using official USPS API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function usps_picked_up( $tracking_number ) { | |
if( empty( $tracking_number ) || !ctype_alnum( $tracking_number ) ) { | |
return false; | |
} | |
$user_id = "YOUR_USER_ID"; | |
$usps_api_uri = "http://production.shippingapis.com/shippingAPI.dll"; | |
$xml = rawurlencode("<TrackRequest USERID=\"". $user_id ."\"> | |
<TrackID ID=\"". $tracking_number ."\" /> | |
</TrackRequest>"); | |
$request = $usps_api_uri ."?API=TrackV2&XML=". $xml; | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $request); | |
curl_setopt($ch, CURLOPT_HEADER, false); | |
curl_setopt($ch, CURLOPT_HTTPGET, true); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
$result = curl_exec($ch); | |
if ( curl_errno( $ch ) ) { | |
return false; | |
} | |
curl_close($ch); | |
$result_object = new SimpleXMLElement($result); | |
$picked_up = false; | |
if( !empty( $result_object->TrackInfo->TrackDetail ) ) { | |
foreach( $result_object->TrackInfo->TrackDetail as $track_detail ) { | |
if( strpos( $track_detail, 'USPS in possession' ) !== false || | |
strpos( $track_detail, 'Accepted at') !== false ) { | |
$picked_up = true; | |
} | |
} | |
} | |
return $picked_up; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment