array( 'type' => 'text', 'label' => __('Consumer key', 'ai-eshop-optimizer'), 'required' => true, 'help' => __('USPS Developer Portal → your app → Consumer Key.', 'ai-eshop-optimizer'), ), 'client_secret' => array('type' => 'password', 'label' => __('Consumer secret', 'ai-eshop-optimizer'), 'required' => true), 'crid' => array('type' => 'text', 'label' => __('CRID', 'ai-eshop-optimizer'), 'required' => true, 'help' => __('Customer Registration ID for the business account.', 'ai-eshop-optimizer')), 'mid' => array('type' => 'text', 'label' => __('MID', 'ai-eshop-optimizer'), 'required' => true, 'help' => __('Mailer ID issued with your CRID.', 'ai-eshop-optimizer')), 'account_number' => array('type' => 'text', 'label' => __('Payment account number', 'ai-eshop-optimizer'), 'required' => true, 'help' => __('The EPS account postage is drawn from.', 'ai-eshop-optimizer')), 'mail_class' => array( 'type' => 'text', 'label' => __('Mail class', 'ai-eshop-optimizer'), 'help' => __('e.g. USPS_GROUND_ADVANTAGE, PRIORITY_MAIL, PRIORITY_MAIL_EXPRESS.', 'ai-eshop-optimizer'), ), 'processing_category' => array( 'type' => 'text', 'label' => __('Processing category', 'ai-eshop-optimizer'), 'help' => __('MACHINABLE for ordinary parcels; NONMACHINABLE for awkward shapes.', 'ai-eshop-optimizer'), ), 'rate_indicator' => array( 'type' => 'text', 'label' => __('Rate indicator', 'ai-eshop-optimizer'), 'help' => __('SP for single-piece. Your USPS agreement lists the rest.', 'ai-eshop-optimizer'), ), 'sender_name' => array('type' => 'text', 'label' => __('Sender name', 'ai-eshop-optimizer'), 'required' => true), 'sender_firm' => array('type' => 'text', 'label' => __('Sender company', 'ai-eshop-optimizer')), 'sender_phone' => array('type' => 'text', 'label' => __('Sender phone', 'ai-eshop-optimizer')), 'sender_street' => array('type' => 'text', 'label' => __('Sender street', 'ai-eshop-optimizer'), 'required' => true), 'sender_city' => array('type' => 'text', 'label' => __('Sender city', 'ai-eshop-optimizer'), 'required' => true), 'sender_state' => array('type' => 'text', 'label' => __('Sender state code', 'ai-eshop-optimizer'), 'required' => true), 'sender_zip' => array('type' => 'text', 'label' => __('Sender ZIP', 'ai-eshop-optimizer'), 'required' => true), ), $this->common_schema()); } public function tracking_url($voucher_no) { $own = parent::tracking_url($voucher_no); if ($own !== '') { return $own; } return 'https://tools.usps.com/go/TrackConfirmAction?tLabels=' . rawurlencode((string) $voucher_no); } public function authenticate(array $creds) { $cfg = array_merge($this->credentials(), $creds); $missing = array(); foreach (array('client_id', 'client_secret', 'crid', 'mid', 'account_number') as $req) { if (empty($cfg[$req])) { $missing[] = $req; } } if (!empty($missing)) { return array('ok' => false, 'error' => sprintf( __('USPS credentials missing: %s', 'ai-eshop-optimizer'), implode(', ', $missing) )); } $token = $this->oauth_token('/oauth2/v3/token', array( 'grant_type' => 'client_credentials', 'client_id' => (string) $cfg['client_id'], 'client_secret' => (string) $cfg['client_secret'], )); if (is_wp_error($token)) { return array('ok' => false, 'error' => $token->get_error_message()); } return array('ok' => true, 'auth_token' => $token, 'expires_at' => null); } private function credentials() { return class_exists('AIEO_Fulfillment_Settings') ? (array) AIEO_Fulfillment_Settings::get('courier_' . $this->code(), array()) : array(); } private function auth_headers($token) { return array('Authorization' => 'Bearer ' . $token); } private function address(array $a) { list($first, $last) = $this->split_name((string) ($a['name'] ?? '')); $out = array( 'firstName' => mb_substr($first, 0, 30), 'lastName' => mb_substr($last !== '' ? $last : $first, 0, 30), 'streetAddress' => mb_substr(trim((string) ($a['address'] ?? '')), 0, 50), 'city' => (string) ($a['city'] ?? ''), 'state' => strtoupper(mb_substr((string) ($a['state'] ?? ''), 0, 2)), 'ZIPCode' => '', 'countryISOCode' => strtoupper((string) ($a['country'] ?? 'US')), ); $zip = preg_replace('/[^0-9]/', '', (string) ($a['zip'] ?? '')); $out['ZIPCode'] = substr($zip, 0, 5); if (strlen($zip) > 5) { $out['ZIPPlus4'] = substr($zip, 5, 4); } $firm = trim((string) ($a['company'] ?? '')); if ($firm !== '') { $out['firm'] = mb_substr($firm, 0, 50); } $line2 = trim((string) ($a['address_2'] ?? '')); if ($line2 !== '') { $out['secondaryAddress'] = mb_substr($line2, 0, 50); } $phone = $this->digits((string) ($a['phone'] ?? '')); if ($phone !== '') { $out['phone'] = substr($phone, -10); } return $out; } private function sender_address() { $c = $this->credentials(); return $this->address(array( 'name' => $c['sender_name'] ?? '', 'company' => $c['sender_firm'] ?? '', 'phone' => $c['sender_phone'] ?? '', 'address' => $c['sender_street'] ?? '', 'city' => $c['sender_city'] ?? '', 'state' => $c['sender_state'] ?? '', 'zip' => $c['sender_zip'] ?? '', 'country' => 'US', )); } public function create_voucher(array $payload) { $auth = $this->authenticate(array()); if (empty($auth['ok'])) { return $auth; } $cfg = $this->credentials(); $rec = isset($payload['recipient']) && is_array($payload['recipient']) ? $payload['recipient'] : array(); $kg = (float) ($payload['weight'] ?? 0.5); if ($kg <= 0) { $kg = 0.5; } $lb = round($kg * 2.20462, 2); if ($lb <= 0) { $lb = 0.1; } $body = array( 'imageInfo' => array( 'imageType' => 'PDF', 'labelType' => '4X6LABEL', 'receiptOption' => 'NONE', ), 'toAddress' => $this->address($rec), 'fromAddress' => $this->sender_address(), 'packageDescription' => array( 'mailClass' => (string) ($cfg['mail_class'] ?: 'USPS_GROUND_ADVANTAGE'), 'rateIndicator' => (string) ($cfg['rate_indicator'] ?: 'SP'), 'processingCategory' => (string) ($cfg['processing_category'] ?: 'MACHINABLE'), 'weight' => $lb, 'weightUOM' => 'lb', 'length' => 8, 'width' => 6, 'height' => 4, 'dimensionsUOM' => 'in', 'mailingDate' => wp_date('Y-m-d'), ), 'paymentAuthorization' => array( 'crid' => (string) ($cfg['crid'] ?? ''), 'mid' => (string) ($cfg['mid'] ?? ''), 'accountNumber' => (string) ($cfg['account_number'] ?? ''), 'accountType' => 'EPS', ), ); $ref = $this->reference($payload, 30); if ($ref !== '') { $body['packageDescription']['customerReference'] = array( array('referenceNumber' => $ref, 'printReferenceNumber' => true), ); } $resp = $this->request('POST', '/labels/v3/label', $body, array_merge( $this->auth_headers($auth['auth_token']), array('Accept' => 'application/json') )); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $tracking = (string) ($resp['labelMetadata']['trackingNumber'] ?? ''); if ($tracking === '') { return array('ok' => false, 'error' => __('USPS accepted the request but returned no tracking number.', 'ai-eshop-optimizer'), 'raw' => $resp); } return array( 'ok' => true, 'voucher_no' => $tracking, 'subvouchers' => array(), 'job_id' => null, 'raw' => $resp, ); } public function get_label_pdf($voucher_no, $format = 'A4') { return array( 'ok' => false, 'error' => __('USPS returns a label only when it is created. Reprint it from the copy saved with the voucher.', 'ai-eshop-optimizer'), ); } public function label_from_create(array $create_response) { $b64 = (string) ($create_response['raw']['labelImage'] ?? ''); if ($b64 === '') { return array('ok' => false, 'pdf' => null, 'error' => __('No label in the USPS response.', 'ai-eshop-optimizer')); } return $this->decode_label($b64); } public function map_status($raw_code) { $raw = strtoupper((string) $raw_code); if ($raw === '') { return 'unknown'; } if (strpos($raw, 'OUT FOR DELIVERY') !== false) { return 'out_for_delivery'; } if (strpos($raw, 'ORIGINAL SENDER') !== false) { return 'returned'; } if (strpos($raw, 'DELIVERED') !== false) { return 'delivered'; } if (strpos($raw, 'RETURN') !== false) { return 'returning'; } if (strpos($raw, 'UNDELIVERABLE') !== false) { return 'attempted'; } if (strpos($raw, 'NOTICE LEFT') !== false) { return 'attempted'; } if (strpos($raw, 'ALERT') !== false) { return 'on_hold'; } if (strpos($raw, 'HELD') !== false) { return 'on_hold'; } if (strpos($raw, 'ACCEPT') !== false) { return 'in_transit'; } if (strpos($raw, 'IN TRANSIT') !== false) { return 'in_transit'; } if (strpos($raw, 'ARRIVED') !== false) { return 'in_transit'; } if (strpos($raw, 'DEPARTED') !== false) { return 'in_transit'; } if (strpos($raw, 'PRE-SHIPMENT') !== false) { return 'created'; } return 'unknown'; } public function track($voucher_no) { $auth = $this->authenticate(array()); if (empty($auth['ok'])) { return $auth; } $resp = $this->request( 'GET', '/tracking/v3/tracking/' . rawurlencode((string) $voucher_no) . '?expand=DETAIL', null, $this->auth_headers($auth['auth_token']) ); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $checkpoints = array(); $delivered_at = null; foreach ((array) ($resp['trackingEvents'] ?? array()) as $e) { $stamp = trim((string) ($e['eventTimestamp'] ?? '')); $ts = $stamp !== '' ? strtotime($stamp) : false; $desc = (string) ($e['eventType'] ?? ''); $checkpoints[] = array( 'code' => $desc, 'description' => $desc, 'location' => trim(implode(' ', array_filter(array( (string) ($e['eventCity'] ?? ''), (string) ($e['eventState'] ?? ''), )))), 'checkpoint_at' => $ts ?: null, ); if ('delivered' === $this->map_status($desc) && $ts) { $delivered_at = $ts; } } return array( 'ok' => true, 'status_code' => (string) ($resp['statusSummary'] ?? ($resp['status'] ?? '')), 'checkpoints' => $checkpoints, 'consignee' => null, 'delivered_at' => $delivered_at, ); } } add_filter('aieo_fulfillment_couriers', static function (array $drivers) { if (!isset($drivers['usps']) && class_exists('AIEO_Courier_Driver_USPS')) { $drivers['usps'] = new AIEO_Courier_Driver_USPS(); } return $drivers; });