array( 'type' => 'text', 'label' => __('API key (client ID)', 'ai-eshop-optimizer'), 'required' => true, 'help' => __('FedEx Developer Portal → your project → API Key.', 'ai-eshop-optimizer'), ), 'client_secret' => array( 'type' => 'password', 'label' => __('Secret key', 'ai-eshop-optimizer'), 'required' => true, ), 'account_number' => array( 'type' => 'text', 'label' => __('Shipping account number', 'ai-eshop-optimizer'), 'required' => true, ), 'service_type' => array( 'type' => 'text', 'label' => __('Service code', 'ai-eshop-optimizer'), 'help' => __('e.g. FEDEX_GROUND for domestic, INTERNATIONAL_PRIORITY for cross-border. Your FedEx account decides which are available to you.', 'ai-eshop-optimizer'), ), 'packaging_type' => array( 'type' => 'text', 'label' => __('Packaging code', 'ai-eshop-optimizer'), 'help' => __('Defaults to YOUR_PACKAGING — your own boxes.', 'ai-eshop-optimizer'), ), 'pickup_type' => array( 'type' => 'text', 'label' => __('Pickup type', 'ai-eshop-optimizer'), 'help' => __('USE_SCHEDULED_PICKUP if FedEx calls daily, DROPOFF_AT_FEDEX_LOCATION if you take parcels in.', 'ai-eshop-optimizer'), ), 'label_stock' => array( 'type' => 'select', 'label' => __('Label size', 'ai-eshop-optimizer'), 'options' => array( 'PAPER_4X6' => __('4×6 thermal', 'ai-eshop-optimizer'), 'PAPER_LETTER' => __('Letter / A4 sheet', 'ai-eshop-optimizer'), 'STOCK_4X6' => __('4×6 stock', 'ai-eshop-optimizer'), ), ), 'sender_name' => array('type' => 'text', 'label' => __('Sender name', '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.fedex.com/fedextrack/?trknbr=' . rawurlencode((string) $voucher_no); } public function authenticate(array $creds) { $cfg = array_merge($this->credentials(), $creds); foreach (array('client_id', 'client_secret', 'account_number') as $req) { if (empty($cfg[$req])) { return array('ok' => false, 'error' => sprintf( __('FedEx: %s is missing.', 'ai-eshop-optimizer'), $req )); } } $token = $this->oauth_token('/oauth/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, 'X-locale' => 'en_US'); } private function party(array $a) { list($first, $last) = $this->split_name((string) ($a['name'] ?? '')); return array( 'contact' => array( 'personName' => trim($first . ' ' . $last), 'phoneNumber' => $this->digits((string) ($a['phone'] ?? '')), 'companyName' => (string) ($a['company'] ?? ''), ), 'address' => array( 'streetLines' => array_values(array_filter(array( trim((string) ($a['address'] ?? '')), trim((string) ($a['address_2'] ?? '')), ))), 'city' => (string) ($a['city'] ?? ''), 'stateOrProvinceCode' => (string) ($a['state'] ?? ''), 'postalCode' => (string) ($a['zip'] ?? ''), 'countryCode' => strtoupper((string) ($a['country'] ?? 'GR')), 'residential' => empty($a['company']), ), ); } private function sender_party() { $c = $this->credentials(); return $this->party(array( 'name' => $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'] ?? '', 'company' => $c['sender_name'] ?? '', )); } private function charges_payment(array $payload) { $party = $this->charge_party($payload); $account = (string) ($this->credentials()['account_number'] ?? ''); $map = array( self::CHARGE_SENDER => 'SENDER', self::CHARGE_RECIPIENT => 'RECIPIENT', self::CHARGE_THIRD_PARTY => 'THIRD_PARTY', ); $type = isset($map[$party]) ? $map[$party] : 'SENDER'; $billed = trim((string) ($payload['billing_account'] ?? '')); if ('SENDER' !== $type && $billed === '') { $billed = $account; } if ($billed === '') { $type = 'SENDER'; $billed = $account; } return array( 'paymentType' => $type, 'payor' => array( 'responsibleParty' => array( 'accountNumber' => array('value' => $billed), ), ), ); } 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; } $ref = $this->reference($payload, 40); $items = array(); for ($i = 0; $i < $pieces; $i++) { $line = array( 'weight' => array('units' => 'KG', 'value' => $per), ); if ($ref !== '') { $line['customerReferences'] = array(array( 'customerReferenceType' => 'CUSTOMER_REFERENCE', 'value' => $ref, )); } $items[] = $line; } $body = array( 'labelResponseOptions' => 'LABEL', 'accountNumber' => array('value' => (string) ($cfg['account_number'] ?? '')), 'requestedShipment' => array( 'shipper' => $this->sender_party(), 'recipients' => array($this->party($rec)), 'shipDatestamp' => wp_date('Y-m-d'), 'serviceType' => (string) ($cfg['service_type'] ?: 'FEDEX_GROUND'), 'packagingType' => (string) ($cfg['packaging_type'] ?: 'YOUR_PACKAGING'), 'pickupType' => (string) ($cfg['pickup_type'] ?: 'USE_SCHEDULED_PICKUP'), 'blockInsightVisibility' => false, 'shippingChargesPayment' => $this->charges_payment($payload), 'labelSpecification' => array( 'imageType' => 'PDF', 'labelStockType' => (string) ($cfg['label_stock'] ?: 'PAPER_4X6'), ), 'requestedPackageLineItems' => $items, ), ); $cod = (float) ($payload['cod_amount'] ?? 0); if ($cod > 0) { $body['requestedShipment']['shipmentSpecialServices'] = array( 'specialServiceTypes' => array('COD'), 'shipmentCODDetail' => array( 'codCollectionAmount' => array( 'amount' => $cod, 'currency' => get_woocommerce_currency(), ), 'codCollectionType' => 'CASH', ), ); } $resp = $this->request('POST', '/ship/v1/shipments', $body, $this->auth_headers($auth['auth_token'])); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $shipment = $resp['output']['transactionShipments'][0] ?? array(); $tracking = (string) ($shipment['masterTrackingNumber'] ?? ''); $subs = array(); foreach ((array) ($shipment['pieceResponses'] ?? array()) as $piece) { $n = (string) ($piece['trackingNumber'] ?? ''); if ($n !== '' && $n !== $tracking) { $subs[] = $n; } if ($tracking === '' && $n !== '') { $tracking = $n; } } if ($tracking === '') { return array('ok' => false, 'error' => __('FedEx 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' => __('FedEx only returns a label at the moment 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) { $docs = $create_response['raw']['output']['transactionShipments'][0]['pieceResponses'][0]['packageDocuments'][0] ?? array(); $b64 = (string) ($docs['encodedLabel'] ?? ''); if ($b64 === '') { return array('ok' => false, 'pdf' => null, 'error' => __('No label in the FedEx response.', 'ai-eshop-optimizer')); } return $this->decode_label($b64); } protected function code_map() { return array( 'OC' => 'created', 'PU' => 'in_transit', 'AR' => 'in_transit', 'DP' => 'in_transit', 'IT' => 'in_transit', 'AF' => 'in_transit', 'OD' => 'out_for_delivery', 'DL' => 'delivered', 'DE' => 'attempted', 'SE' => 'on_hold', 'HL' => 'on_hold', 'CA' => 'canceled', 'RS' => 'returning', ); } public function track($voucher_no) { $auth = $this->authenticate(array()); if (empty($auth['ok'])) { return $auth; } $resp = $this->request('POST', '/track/v1/trackingnumbers', array( 'includeDetailedScans' => true, 'trackingInfo' => array(array( 'trackingNumberInfo' => array('trackingNumber' => (string) $voucher_no), )), ), $this->auth_headers($auth['auth_token'])); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $result = $resp['output']['completeTrackResults'][0]['trackResults'][0] ?? array(); if (!empty($result['error'])) { return array('ok' => false, 'error' => $this->extract_error($result['error'])); } $checkpoints = array(); $delivered_at = null; foreach ((array) ($result['scanEvents'] ?? array()) as $e) { $ts = isset($e['date']) ? strtotime((string) $e['date']) : false; $loc = $e['scanLocation'] ?? array(); $checkpoints[] = array( 'code' => (string) ($e['eventType'] ?? ''), 'description' => (string) ($e['eventDescription'] ?? ''), 'location' => trim(implode(' ', array_filter(array( (string) ($loc['city'] ?? ''), (string) ($loc['countryCode'] ?? ''), )))), 'checkpoint_at' => $ts ?: null, ); if ('DL' === (string) ($e['eventType'] ?? '') && $ts) { $delivered_at = $ts; } } return array( 'ok' => true, 'status_code' => (string) ($result['latestStatusDetail']['derivedCode'] ?? ''), 'checkpoints' => $checkpoints, 'consignee' => (string) ($result['deliveryDetails']['receivedByName'] ?? '') ?: null, 'delivered_at' => $delivered_at, ); } public function cancel($voucher_no) { $auth = $this->authenticate(array()); if (empty($auth['ok'])) { return $auth; } $resp = $this->request('PUT', '/ship/v1/shipments/cancel', array( 'accountNumber' => array('value' => (string) ($this->credentials()['account_number'] ?? '')), 'trackingNumber' => (string) $voucher_no, 'deletionControl' => 'DELETE_ALL_PACKAGES', ), $this->auth_headers($auth['auth_token'])); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } if (isset($resp['output']['cancelledShipment']) && !$resp['output']['cancelledShipment']) { return array('ok' => false, 'error' => $this->extract_error($resp) ?: __('FedEx declined to cancel this shipment.', 'ai-eshop-optimizer')); } return array('ok' => true); } } add_filter('aieo_fulfillment_couriers', static function (array $drivers) { if (!isset($drivers['fedex']) && class_exists('AIEO_Courier_Driver_FedEx')) { $drivers['fedex'] = new AIEO_Courier_Driver_FedEx(); } return $drivers; });