array( 'type' => 'text', 'label' => __('Client ID', 'ai-eshop-optimizer'), 'required' => true, 'help' => __('UPS Developer Portal → your app → Client ID.', 'ai-eshop-optimizer'), ), 'client_secret' => array('type' => 'password', 'label' => __('Client secret', 'ai-eshop-optimizer'), 'required' => true), 'account_number' => array( 'type' => 'text', 'label' => __('UPS account number (shipper number)', 'ai-eshop-optimizer'), 'required' => true, 'help' => __('Six characters. Must be the account enabled for the API in your UPS profile.', 'ai-eshop-optimizer'), ), 'service_code' => array( 'type' => 'text', 'label' => __('Service code', 'ai-eshop-optimizer'), 'help' => __('11 = UPS Standard, 07 = Express, 65 = Express Saver, 03 = Ground (US). Your UPS contract decides which apply.', 'ai-eshop-optimizer'), ), 'packaging_code' => array( 'type' => 'text', 'label' => __('Packaging code', 'ai-eshop-optimizer'), 'help' => __('02 is your own packaging, which is what most shops use.', 'ai-eshop-optimizer'), ), 'label_format' => array( 'type' => 'select', 'label' => __('Label format', 'ai-eshop-optimizer'), 'options' => array( 'GIF' => __('GIF — ordinary printer', 'ai-eshop-optimizer'), 'ZPL' => __('ZPL — thermal printer', 'ai-eshop-optimizer'), 'EPL' => __('EPL — older thermal', 'ai-eshop-optimizer'), ), 'help' => __('UPS does not offer PDF. GIF prints on any printer; ZPL only on a label printer.', 'ai-eshop-optimizer'), ), 'sender_name' => array('type' => 'text', 'label' => __('Sender name', 'ai-eshop-optimizer'), 'required' => true), 'sender_attention' => array('type' => 'text', 'label' => __('Sender contact person', 'ai-eshop-optimizer'), 'required' => true), 'sender_phone' => array('type' => 'text', 'label' => __('Sender phone', 'ai-eshop-optimizer'), 'required' => true), '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 / province code', 'ai-eshop-optimizer')), 'sender_zip' => array('type' => 'text', 'label' => __('Sender postcode', 'ai-eshop-optimizer'), 'required' => true), 'sender_country' => array('type' => 'text', 'label' => __('Sender country code', '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://www.ups.com/track?loc=en_US&tracknum=' . rawurlencode((string) $voucher_no); } public function authenticate(array $creds) { $cfg = array_merge($this->credentials(), $creds); $missing = array(); foreach (array('client_id', 'client_secret', 'account_number') as $req) { if (empty($cfg[$req])) { $missing[] = $req; } } if (!empty($missing)) { return array('ok' => false, 'error' => sprintf( __('UPS credentials missing: %s', 'ai-eshop-optimizer'), implode(', ', $missing) )); } $token = $this->basic_oauth_token($cfg); 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 basic_oauth_token(array $cfg) { $key = 'aieo_ff_tok_ups_' . md5($this->endpoint() . '|' . (string) $cfg['client_id']); $cached = get_transient($key); if (is_string($cached) && $cached !== '') { return $cached; } $resp = wp_remote_post($this->endpoint() . '/security/v1/oauth/token', array( 'timeout' => 30, 'redirection' => 0, 'headers' => array( 'Authorization' => 'Basic ' . base64_encode($cfg['client_id'] . ':' . $cfg['client_secret']), 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json', ), 'body' => array('grant_type' => 'client_credentials'), )); if (is_wp_error($resp)) { return new WP_Error('aieo_courier_transport', $resp->get_error_message()); } $raw = (string) wp_remote_retrieve_body($resp); $json = json_decode($raw, true); $code = (int) wp_remote_retrieve_response_code($resp); if ($code < 200 || $code >= 300 || empty($json['access_token'])) { $msg = $this->extract_error(is_array($json) ? $json : array(), $raw); return new WP_Error('aieo_courier_auth', $msg !== '' ? $msg : sprintf( __('UPS rejected the credentials (HTTP %d).', 'ai-eshop-optimizer'), $code )); } $ttl = isset($json['expires_in']) ? (int) $json['expires_in'] : 3600; set_transient($key, (string) $json['access_token'], max(60, $ttl - self::TOKEN_SAFETY_MARGIN)); return (string) $json['access_token']; } 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, 'transId' => substr(str_replace('-', '', wp_generate_uuid4()), 0, 32), 'transactionSrc' => 'aieo', ); } private function party(array $a) { $name = mb_substr((string) ($a['name'] ?? ''), 0, 35); $party = array( 'Name' => $name, 'AttentionName' => mb_substr((string) ($a['attention'] ?? $name), 0, 35), 'Address' => array( 'AddressLine' => array_values(array_filter(array( mb_substr(trim((string) ($a['address'] ?? '')), 0, 35), mb_substr(trim((string) ($a['address_2'] ?? '')), 0, 35), ))), 'City' => (string) ($a['city'] ?? ''), 'PostalCode' => (string) ($a['zip'] ?? ''), 'CountryCode' => strtoupper((string) ($a['country'] ?? 'GR')), ), ); $state = trim((string) ($a['state'] ?? '')); if ($state !== '') { $party['Address']['StateProvinceCode'] = strtoupper(mb_substr($state, 0, 5)); } $phone = $this->digits((string) ($a['phone'] ?? '')); if ($phone !== '') { $party['Phone'] = array('Number' => $phone); } $account = trim((string) ($a['account'] ?? '')); if ($account !== '') { $party['ShipperNumber'] = $account; } return $party; } private function sender_party() { $c = $this->credentials(); return $this->party(array( 'name' => $c['sender_name'] ?? '', 'attention' => $c['sender_attention'] ?? ($c['sender_name'] ?? ''), 'phone' => $c['sender_phone'] ?? '', 'address' => $c['sender_street'] ?? '', 'city' => $c['sender_city'] ?? '', 'state' => $c['sender_state'] ?? '', 'zip' => $c['sender_zip'] ?? '', 'country' => $c['sender_country'] ?? '', 'account' => $c['account_number'] ?? '', )); } private function payment_information(array $payload, array $recipient) { $ours = (string) ($this->credentials()['account_number'] ?? ''); $party = $this->charge_party($payload); $theirs = trim((string) ($payload['billing_account'] ?? '')); $charge = array('Type' => '01'); if (self::CHARGE_RECIPIENT === $party && $theirs !== '') { $charge['BillReceiver'] = array( 'AccountNumber' => $theirs, 'Address' => array('PostalCode' => (string) ($recipient['zip'] ?? '')), ); } elseif (self::CHARGE_THIRD_PARTY === $party && $theirs !== '') { $charge['BillThirdParty'] = array( 'AccountNumber' => $theirs, 'Address' => array( 'PostalCode' => (string) ($payload['billing_postcode'] ?? ($recipient['zip'] ?? '')), 'CountryCode' => strtoupper((string) ($payload['billing_country'] ?? ($recipient['country'] ?? 'GR'))), ), ); } else { $charge['BillShipper'] = array('AccountNumber' => $ours); } return array('ShipmentCharge' => $charge); } 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(); $weight = (float) ($payload['weight'] ?? 0.5); if ($weight <= 0) { $weight = 0.5; } $pieces = max(1, (int) ($payload['pieces'] ?? 1)); $per = round($weight / $pieces, 2); if ($per <= 0) { $per = $weight; } $desc = trim((string) ($payload['content_description'] ?? '')); if ($desc === '') { $desc = 'Goods'; } $desc = mb_substr($desc, 0, 50); $packages = array(); for ($i = 0; $i < $pieces; $i++) { $packages[] = array( 'Description' => $desc, 'Packaging' => array('Code' => (string) ($cfg['packaging_code'] ?: '02')), 'PackageWeight' => array( 'UnitOfMeasurement' => array('Code' => 'KGS'), 'Weight' => (string) $per, ), ); } $shipment = array( 'Description' => $desc, 'Shipper' => $this->sender_party(), 'ShipTo' => $this->party($rec), 'ShipFrom' => $this->sender_party(), 'PaymentInformation' => $this->payment_information($payload, $rec), 'Service' => array('Code' => (string) ($cfg['service_code'] ?: '11')), 'Package' => $packages, ); $ref = $this->reference($payload, 35); if ($ref !== '') { $shipment['ReferenceNumber'] = array(array('Code' => 'PO', 'Value' => $ref)); } $body = array( 'ShipmentRequest' => array( 'Shipment' => $shipment, 'LabelSpecification' => array( 'LabelImageFormat' => array('Code' => (string) ($cfg['label_format'] ?: 'GIF')), 'HTTPUserAgent' => 'Mozilla/5.0', ), ), ); $resp = $this->request('POST', '/api/shipments/v1/ship', $body, $this->auth_headers($auth['auth_token'])); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $results = $resp['ShipmentResponse']['ShipmentResults'] ?? array(); $tracking = (string) ($results['ShipmentIdentificationNumber'] ?? ''); $pkgs = $results['PackageResults'] ?? array(); if (isset($pkgs['TrackingNumber'])) { $pkgs = array($pkgs); } $subs = array(); foreach ((array) $pkgs as $pkg) { $n = (string) ($pkg['TrackingNumber'] ?? ''); if ($n === '') { continue; } if ($tracking === '') { $tracking = $n; continue; } if ($n !== $tracking) { $subs[] = $n; } } if ($tracking === '') { return array('ok' => false, 'error' => __('UPS accepted the request but returned no tracking number.', 'ai-eshop-optimizer'), 'raw' => $resp); } return array( 'ok' => true, 'voucher_no' => $tracking, 'subvouchers' => $subs, 'job_id' => null, 'raw' => $resp, ); } public function get_label_pdf($voucher_no, $format = 'A4') { return array( 'ok' => false, 'error' => __('UPS returns a label only when the shipment is created. Reprint it from the copy saved with the voucher, or void the shipment and create it again.', 'ai-eshop-optimizer'), ); } public function label_from_create(array $create_response) { $results = $create_response['raw']['ShipmentResponse']['ShipmentResults'] ?? array(); $pkgs = $results['PackageResults'] ?? array(); if (isset($pkgs['ShippingLabel'])) { $pkgs = array($pkgs); } foreach ((array) $pkgs as $pkg) { $b64 = (string) ($pkg['ShippingLabel']['GraphicImage'] ?? ''); if ($b64 !== '') { return $this->decode_label($b64); } } return array('ok' => false, 'pdf' => null, 'error' => __('No label in the UPS response.', 'ai-eshop-optimizer')); } protected function code_map() { return array( 'M' => 'created', 'MV' => 'created', 'P' => 'in_transit', 'I' => 'in_transit', 'O' => 'out_for_delivery', 'D' => 'delivered', 'X' => 'attempted', 'RS' => 'returning', 'NA' => 'on_hold', 'MP' => 'created', ); } public function track($voucher_no) { $auth = $this->authenticate(array()); if (empty($auth['ok'])) { return $auth; } $resp = $this->request( 'GET', '/api/track/v1/details/' . rawurlencode((string) $voucher_no), null, $this->auth_headers($auth['auth_token']) ); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $package = $resp['trackResponse']['shipment'][0]['package'][0] ?? array(); $checkpoints = array(); $latest = ''; $delivered_at = null; foreach ((array) ($package['activity'] ?? array()) as $a) { $date = (string) ($a['date'] ?? ''); $time = (string) ($a['time'] ?? ''); $ts = false; if ($date !== '') { $dt = DateTime::createFromFormat('Ymd His', $date . ' ' . str_pad($time !== '' ? $time : '000000', 6, '0', STR_PAD_LEFT)); if ($dt) { $ts = $dt->getTimestamp(); } } $type = (string) ($a['status']['type'] ?? ''); $loc = $a['location']['address'] ?? array(); $checkpoints[] = array( 'code' => $type, 'description' => (string) ($a['status']['description'] ?? ''), 'location' => trim(implode(' ', array_filter(array( (string) ($loc['city'] ?? ''), (string) ($loc['countryCode'] ?? ''), )))), 'checkpoint_at' => $ts ?: null, ); if ($type !== '' && $latest === '') { $latest = $type; } if ('D' === $type && $ts) { $delivered_at = $ts; } } return array( 'ok' => true, 'status_code' => $latest, 'checkpoints' => $checkpoints, 'consignee' => (string) ($package['deliveryInformation']['receivedBy'] ?? '') ?: null, 'delivered_at' => $delivered_at, ); } public function cancel($voucher_no) { $auth = $this->authenticate(array()); if (empty($auth['ok'])) { return $auth; } $resp = $this->request( 'DELETE', '/api/shipments/v1/void/cancel/' . rawurlencode((string) $voucher_no), null, $this->auth_headers($auth['auth_token']) ); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $status = (string) ($resp['VoidShipmentResponse']['SummaryResult']['Status']['Code'] ?? ''); if ($status !== '' && '1' !== $status) { return array('ok' => false, 'error' => $this->extract_error($resp) ?: __('UPS declined to void this shipment.', 'ai-eshop-optimizer')); } return array('ok' => true); } } add_filter('aieo_fulfillment_couriers', static function (array $drivers) { if (!isset($drivers['ups']) && class_exists('AIEO_Courier_Driver_UPS')) { $drivers['ups'] = new AIEO_Courier_Driver_UPS(); } return $drivers; });