array( 'type' => 'text', 'label' => __('Public key', 'ai-eshop-optimizer'), 'required' => true, 'help' => __('Sendcloud panel → Settings → Integrations → API.', 'ai-eshop-optimizer'), ), 'secret_key' => array('type' => 'password', 'label' => __('Secret key', 'ai-eshop-optimizer'), 'required' => true), 'shipping_method_id' => array( 'type' => 'number', 'label' => __('Shipping method ID', 'ai-eshop-optimizer'), 'required' => true, 'help' => __('The numeric id from your own Sendcloud account — it encodes the carrier, the service and the weight bracket together. Use "Test connection" below to list the ones your account has.', 'ai-eshop-optimizer'), ), 'sender_address_id' => array( 'type' => 'number', 'label' => __('Sender address ID', 'ai-eshop-optimizer'), 'help' => __('Optional. Leave empty to use the default sender address configured in Sendcloud.', 'ai-eshop-optimizer'), ), 'label_printer' => array( 'type' => 'select', 'label' => __('Label format', 'ai-eshop-optimizer'), 'options' => array( 'normal_printer' => __('A4 / A6 sheet', 'ai-eshop-optimizer'), 'label_printer' => __('Thermal label printer', 'ai-eshop-optimizer'), ), ), ); } public function tracking_url($voucher_no) { $own = parent::tracking_url($voucher_no); if ($own !== '') { return $own; } return 'https://tracking.sendcloud.sc/forward?code=' . rawurlencode((string) $voucher_no); } public function authenticate(array $creds) { $cfg = array_merge($this->credentials(), $creds); $missing = array(); foreach (array('public_key', 'secret_key') as $req) { if (empty($cfg[$req])) { $missing[] = $req; } } if (!empty($missing)) { return array('ok' => false, 'error' => sprintf( __('Sendcloud credentials missing: %s', 'ai-eshop-optimizer'), implode(', ', $missing) )); } $methods = $this->request('GET', '/shipping_methods', null, $this->auth_headers()); if (is_wp_error($methods)) { return array('ok' => false, 'error' => $methods->get_error_message()); } $names = array(); foreach ((array) ($methods['shipping_methods'] ?? array()) as $m) { $names[] = sprintf('%d — %s', (int) ($m['id'] ?? 0), (string) ($m['name'] ?? '')); if (count($names) >= 8) { $names[] = '…'; break; } } return array( 'ok' => true, 'auth_token' => null, 'expires_at' => null, 'message' => empty($names) ? __('Connected, but this account has no shipping methods enabled yet.', 'ai-eshop-optimizer') : sprintf( __('Connected. Shipping methods available: %s', 'ai-eshop-optimizer'), implode(' · ', $names) ), ); } private function credentials() { return class_exists('AIEO_Fulfillment_Settings') ? (array) AIEO_Fulfillment_Settings::get('courier_' . $this->code(), array()) : array(); } private function auth_headers() { $c = $this->credentials(); return array( 'Authorization' => 'Basic ' . base64_encode(($c['public_key'] ?? '') . ':' . ($c['secret_key'] ?? '')), ); } public function shop_list() { $auth = $this->authenticate(array()); if (empty($auth['ok'])) { return $auth; } $resp = $this->request('GET', '/shipping_methods', null, $this->auth_headers()); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $shops = array(); foreach ((array) ($resp['shipping_methods'] ?? array()) as $m) { $shops[] = array( 'id' => (int) ($m['id'] ?? 0), 'name' => (string) ($m['name'] ?? ''), 'carrier' => (string) ($m['carrier'] ?? ''), ); } return array('ok' => true, 'shops' => $shops); } 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(); $method = (int) ($cfg['shipping_method_id'] ?? 0); if ($method <= 0) { return array('ok' => false, 'error' => __('Sendcloud: set the shipping method ID first — it decides which carrier actually carries the parcel.', 'ai-eshop-optimizer')); } list($street, $house) = $this->split_address((string) ($rec['address'] ?? '')); $weight = (float) ($payload['weight'] ?? 0.5); if ($weight <= 0) { $weight = 0.5; } $parcel = array( 'name' => mb_substr((string) ($rec['name'] ?? ''), 0, 75), 'company_name' => mb_substr((string) ($rec['company'] ?? ''), 0, 75), 'address' => mb_substr($street !== '' ? $street : (string) ($rec['address'] ?? ''), 0, 75), 'house_number' => mb_substr($house, 0, 10), 'address_2' => mb_substr((string) ($rec['address_2'] ?? ''), 0, 50), 'city' => (string) ($rec['city'] ?? ''), 'postal_code' => (string) ($rec['zip'] ?? ''), 'country' => strtoupper(substr((string) ($rec['country'] ?? 'GR'), 0, 2)), 'telephone' => (string) ($rec['phone'] ?? ''), 'email' => (string) ($rec['email'] ?? ''), 'order_number' => $this->reference($payload, 50), 'weight' => number_format($weight, 3, '.', ''), 'request_label' => true, 'shipment' => array('id' => $method), 'quantity' => max(1, (int) ($payload['pieces'] ?? 1)), ); $sender = (int) ($cfg['sender_address_id'] ?? 0); if ($sender > 0) { $parcel['sender_address'] = $sender; } $cod = (float) ($payload['cod_amount'] ?? 0); if ($cod > 0) { $parcel['total_order_value'] = number_format($cod, 2, '.', ''); $parcel['total_order_value_currency'] = get_woocommerce_currency(); $parcel['is_return'] = false; } $resp = $this->request('POST', '/parcels', array('parcel' => $parcel), $this->auth_headers()); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $created = $resp['parcel'] ?? array(); $tracking = (string) ($created['tracking_number'] ?? ''); $id = (int) ($created['id'] ?? 0); $status = (string) ($created['status']['message'] ?? ''); if ($id === 0) { return array('ok' => false, 'error' => $this->extract_error($resp) ?: __('Sendcloud did not create the parcel.', 'ai-eshop-optimizer'), 'raw' => $resp); } if ($tracking === '') { return array( 'ok' => false, 'error' => $status !== '' ? sprintf( __('Sendcloud created the parcel but produced no tracking number: %s', 'ai-eshop-optimizer'), $status ) : __('Sendcloud created the parcel but produced no tracking number.', 'ai-eshop-optimizer'), 'raw' => $resp, ); } return array( 'ok' => true, 'voucher_no' => $tracking, 'subvouchers' => array(), 'job_id' => $id, 'raw' => $resp, ); } public function get_label_pdf($voucher_no, $format = 'A4') { $auth = $this->authenticate(array()); if (empty($auth['ok'])) { return $auth; } $id = ctype_digit((string) $voucher_no) ? (int) $voucher_no : 0; if ($id === 0 || strlen((string) $voucher_no) > 9) { $found = $this->request('GET', '/parcels?tracking_number=' . rawurlencode((string) $voucher_no), null, $this->auth_headers()); if (!is_wp_error($found) && !empty($found['parcels'][0]['id'])) { $id = (int) $found['parcels'][0]['id']; } } if ($id === 0) { return array('ok' => false, 'error' => __('Sendcloud does not recognise that parcel.', 'ai-eshop-optimizer')); } $printer = (string) ($this->credentials()['label_printer'] ?: 'normal_printer'); if (strtoupper($format) === 'THERMAL') { $printer = 'label_printer'; } $path = '/labels/' . $printer . '/' . $id . ('normal_printer' === $printer ? '?start_from=0' : ''); $bytes = $this->fetch_binary($this->endpoint() . $path, $this->auth_headers()); if (is_wp_error($bytes)) { return array('ok' => false, 'error' => $bytes->get_error_message()); } $sniff = $this->decode_label(base64_encode($bytes)); if (empty($sniff['ok'])) { return $sniff; } return array('ok' => true, 'pdf' => $sniff['pdf'], 'mime' => $sniff['mime'], 'pdf_url' => null); } public function label_from_create(array $create_response) { $id = (int) ($create_response['raw']['parcel']['id'] ?? 0); if ($id === 0) { return array('ok' => false, 'pdf' => null, 'error' => __('No parcel id in the Sendcloud response.', 'ai-eshop-optimizer')); } return $this->get_label_pdf((string) $id); } public function map_status($raw_code) { $raw = strtolower((string) $raw_code); if ($raw === '') { return 'unknown'; } if (strpos($raw, 'delivered') !== false) { return 'delivered'; } if (strpos($raw, 'out for delivery') !== false) { return 'out_for_delivery'; } if (strpos($raw, 'being sorted') !== false) { return 'in_transit'; } if (strpos($raw, 'en route') !== false) { return 'in_transit'; } if (strpos($raw, 'shipped') !== false) { return 'in_transit'; } if (strpos($raw, 'at customs') !== false) { return 'in_transit'; } if (strpos($raw, 'announced') !== false) { return 'created'; } if (strpos($raw, 'ready to send') !== false) { return 'created'; } if (strpos($raw, 'delivery attempt') !== false) { return 'attempted'; } if (strpos($raw, 'cancel') !== false) { return 'canceled'; } if (strpos($raw, 'return') !== false) { return 'returning'; } if (strpos($raw, 'error') !== false) { return 'on_hold'; } return 'unknown'; } public function track($voucher_no) { $auth = $this->authenticate(array()); if (empty($auth['ok'])) { return $auth; } $resp = $this->request('GET', '/parcels?tracking_number=' . rawurlencode((string) $voucher_no), null, $this->auth_headers()); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $parcel = $resp['parcels'][0] ?? array(); if (empty($parcel)) { return array('ok' => false, 'error' => __('Sendcloud does not recognise that tracking number.', 'ai-eshop-optimizer')); } $status = (string) ($parcel['status']['message'] ?? ''); $ts = isset($parcel['date_updated']) ? strtotime((string) $parcel['date_updated']) : false; return array( 'ok' => true, 'status_code' => $status, 'checkpoints' => $status === '' ? array() : array(array( 'code' => (string) ($parcel['status']['id'] ?? ''), 'description' => $status, 'location' => (string) ($parcel['carrier']['code'] ?? ''), 'checkpoint_at' => $ts ?: null, )), 'consignee' => null, 'delivered_at' => ('delivered' === $this->map_status($status) && $ts) ? $ts : null, ); } public function cancel($voucher_no) { $auth = $this->authenticate(array()); if (empty($auth['ok'])) { return $auth; } $id = ctype_digit((string) $voucher_no) ? (int) $voucher_no : 0; if ($id === 0) { $found = $this->request('GET', '/parcels?tracking_number=' . rawurlencode((string) $voucher_no), null, $this->auth_headers()); if (!is_wp_error($found) && !empty($found['parcels'][0]['id'])) { $id = (int) $found['parcels'][0]['id']; } } if ($id === 0) { return array('ok' => false, 'error' => __('Sendcloud does not recognise that parcel.', 'ai-eshop-optimizer')); } $resp = $this->request('POST', '/parcels/' . $id . '/cancel', null, $this->auth_headers()); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $status = strtolower((string) ($resp['status'] ?? '')); if ($status !== '' && 'cancelled' !== $status && 'queued' !== $status && 'deleted' !== $status) { return array('ok' => false, 'error' => (string) ($resp['message'] ?? __('Sendcloud declined to cancel this parcel.', 'ai-eshop-optimizer'))); } return array('ok' => true); } } add_filter('aieo_fulfillment_couriers', static function (array $drivers) { if (!isset($drivers['sendcloud']) && class_exists('AIEO_Courier_Driver_Sendcloud')) { $drivers['sendcloud'] = new AIEO_Courier_Driver_Sendcloud(); } return $drivers; });