### Plugin Installation and Requirements Source: https://context7.com/cdek-it/wordpress/llms.txt Instructions for installing the CDEKDelivery plugin via WP-CLI or manually. Includes checks for minimum server requirements and initial configuration steps in WooCommerce. ```bash # Install via WP-CLI wp plugin install cdekdelivery --activate # Or upload manually via WordPress admin: # Plugins → Add New → search "CDEKDelivery" → Install → Activate # Minimum server requirements check: php -r "echo PHP_VERSION;" # must be >= 7.4 php -m | grep openssl # must be present # After activation, configure at: # WooCommerce → Settings → Shipping → CDEKDelivery # Required fields: # - Identifier (client_id from lk.cdek.ru/integration) # - Secret key (client_secret from lk.cdek.ru/integration) # - Yandex Maps API key # - Sender city (select from autocomplete dropdown) # - Sender address # Enable test mode to use sandbox credentials automatically: # test_mode = yes → uses https://api.edu.cdek.ru/v2/ with built-in test keys # Add the CDEK shipping method to a shipping zone: # WooCommerce → Settings → Shipping → [Zone] → Add shipping method → CDEK Shipping ``` -------------------------------- ### Calculate CDEK Shipping Rates Source: https://context7.com/cdek-it/wordpress/llms.txt This example shows how to use `CalculateDeliveryAction` to compute shipping rates for a WooCommerce cart. It requires defining package details and the destination, then handles potential API errors. ```php use Cdek\Actions\CalculateDeliveryAction; use Cdek\ShippingMethod; $method = ShippingMethod::factory(); $package = [ 'destination' => [ 'city' => 'Москва', 'postcode' => '101000', 'country' => 'RU', ], 'contents' => WC()->cart->get_cart_contents(), // standard WC cart contents 'contents_cost' => WC()->cart->get_displayed_subtotal(), ]; try { $rates = CalculateDeliveryAction::new()($package, $method); // $rates is an array of rate arrays, e.g.: // [ // 136 => [ // 'id' => 'official_cdek:136', // 'label' => 'Посылка склад-склад, (2-4 days)', // 'cost' => 380, // 'meta_data' => [ // '_official_cdek_tariff_code' => 136, // '_official_cdek_tariff_mode' => 4, // '_official_cdek_weight' => 1500, // grams // '_official_cdek_office_code' => null, // ], // ], // ] foreach ($rates as $rate) { echo $rate['label'] . ' — ' . $rate['cost'] . ' RUB' . PHP_EOL; } } catch (\Cdek\Exceptions\External\ApiException $e) { error_log('CDEK rate calculation failed: ' . $e->getMessage()); } ``` -------------------------------- ### Generate CDEK Waybill via AJAX (Admin) Source: https://context7.com/cdek-it/wordpress/llms.txt This JavaScript code fetches a CDEK waybill PDF as a base64-encoded string. It makes a GET request to the 'official_cdek-waybill' AJAX action and handles the response to display or download the PDF. ```javascript const url = new URL(ajaxurl); url.searchParams.set('action', 'official_cdek-waybill'); url.searchParams.set('_wpnonce', cdekdelivery_params.nonce); url.searchParams.set('id', '1042'); // WooCommerce order ID fetch(url) .then(r => r.json()) .then(data => { if (data.success) { // data.data is base64-encoded PDF const pdfBytes = atob(data.data); // open or download the PDF const blob = new Blob( [Uint8Array.from(pdfBytes, c => c.charCodeAt(0))], { type: 'application/pdf' } ); window.open(URL.createObjectURL(blob)); } else { console.error('Waybill error:', data.data); } }); ``` ```php $result = \Cdek\Actions\GenerateWaybillAction::new()($cdekNumber); if ($result['success']) { $pdfContent = base64_decode($result['data']); file_put_contents('/tmp/waybill.pdf', $pdfContent); } ``` -------------------------------- ### IntakeCreateAction Source: https://context7.com/cdek-it/wordpress/llms.txt Schedules a CDEK courier pickup (intake request) from the store. It supports both door-pickup and office-pickup tariffs, storing the resulting intake details in order meta. ```APIDOC ## IntakeCreateAction — Schedule a CDEK Courier Pickup `IntakeCreateAction` creates a courier intake request in CDEK (a scheduled courier pickup from the store). It handles both door-pickup tariffs (linked by CDEK order number) and office-pickup tariffs (supplying sender address, cargo description, and weight). The resulting intake UUID and number are stored in order meta. ```php use Cdek\Actions\IntakeCreateAction; use Cdek\Model\Order; $order = new \Cdek\Model\Order(1042); // WooCommerce order ID $intakeData = [ 'call' => 'true', // request a call before arrival 'date' => '2025-06-15', // pickup date (Y-m-d) 'from' => '10:00', // pickup window start (HH:MM, 09:00–19:00) 'to' => '14:00', // pickup window end (HH:MM, 12:00–22:00) 'comment' => 'Ring the bell', // optional comment for courier // For office-pickup tariffs, also required: // 'weight' => 2500, // total weight in grams // 'desc' => 'Electronics', // cargo description ]; try { $result = IntakeCreateAction::new()($order, $intakeData); if ($result->state) { echo 'Courier intake scheduled successfully'; // Intake UUID and number saved to order meta // Order note added: "Intake has been created: Number: X | Uuid: Y" } else { echo 'Intake error: ' . $result->message; } } catch (\Cdek\Exceptions\ShippingNotFoundException $e) { echo 'No CDEK shipping on this order'; } ``` ``` -------------------------------- ### Plugin Configuration Constants Source: https://context7.com/cdek-it/wordpress/llms.txt Centralizes environment constants like API URLs, hook names, and developer keys. Use these constants to access configuration values within the plugin. ```php use Cdek\Config; // API endpoint constants Config::API_URL // 'https://api.cdek.ru/v2/' Config::TEST_API_URL // 'https://api.edu.cdek.ru/v2/' Config::API_CORE_URL // 'https://api.cdek.ru/' // Shipping method ID (used as WooCommerce shipping method identifier) Config::DELIVERY_NAME // 'official_cdek' // WordPress action scheduler hook names Config::ORDER_AUTOMATION_HOOK_NAME // 'cdekdelivery_automation' Config::UPGRADE_HOOK_NAME // 'cdekdelivery_upgrade' Config::TASK_MANAGER_HOOK_NAME // 'cdekdelivery_task_manager' // Test/sandbox credentials (built-in for test mode) Config::TEST_CLIENT_ID // 'wqGwiQx0gg8mLtiEKsUinjVSICCjtTEP' Config::TEST_CLIENT_SECRET // 'RmAmgvSgSl1yirlz9QupbzOJVqhCxcP5' // Documentation URLs Config::DOCS_URL // 'https://cdek-it.github.io/wordpress/' Config::FAQ_URL // 'https://cdek-it.github.io/wordpress/faq' // Enable debug mode by appending ?cdeksik to any admin URL // Config::MAGIC_KEY = 'cdeksik' ``` -------------------------------- ### Access and Update ShippingMethod Settings Source: https://context7.com/cdek-it/wordpress/llms.txt Demonstrates how to retrieve an instance of the active `ShippingMethod` and access or programmatically update its settings. Settings are stored as WooCommerce shipping method options. ```php // Retrieve the active ShippingMethod instance anywhere in your code $method = \Cdek\ShippingMethod::factory(); // Read settings $clientId = $method->client_id; // CDEK API OAuth2 client ID $testMode = $method->test_mode; // bool – use sandbox API $tariffList = $method->tariff_list; // array of enabled tariff codes e.g. ['136', '137'] $cityCode = $method->city_code; // CDEK city code for the sender location $automate = $method->automate_orders; // bool – auto-create CDEK waybills on checkout // Write a setting programmatically $method->update_option('extra_day', '2'); // add 2 extra days to all delivery estimates ``` -------------------------------- ### Create CDEK Order via AJAX (Admin) Source: https://context7.com/cdek-it/wordpress/llms.txt Use this JavaScript snippet on the admin order page to send package definitions to create a CDEK order. It requires a nonce for authentication and sends data via a URL-encoded POST request. ```javascript const nonce = cdekdelivery_params.nonce; // localized in admin scripts fetch(ajaxurl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ action: 'official_cdek-create', _wpnonce: nonce, id: '1042', // WooCommerce order ID }), // POST body (raw JSON) contains packages: }).then(() => {/* AdminOrderBox HTML is returned and injected */}); ``` ```javascript const packagesJson = JSON.stringify([ { length: 30, width: 20, height: 15 }, // single-seat { length: 20, width: 10, height: 10, // multi-seat with item mapping items: [{ id: 101, qty: 1 }, { id: 202, qty: 2 }] } ]); ``` -------------------------------- ### City Autocomplete (Admin AJAX) Source: https://context7.com/cdek-it/wordpress/llms.txt This AJAX action queries the CDEK city suggestion API to provide autocomplete suggestions for city names in the plugin's admin settings. It requires `action`, `_wpnonce`, and a query parameter `q`. ```javascript // GET request – used by the admin settings page address field autocomplete const url = new URL(ajaxurl); url.searchParams.set('action', 'official_cdek-cities'); url.searchParams.set('_wpnonce', cdekdelivery_params.nonce); url.searchParams.set('q', 'Екатер'); // partial city name fetch(url) .then(r => r.json()) .then(data => { if (data.success) { // data.data is array of CDEK city objects: // [{ "code": 270, "city": "Екатеринбург", "region": "Свердловская обл." }, ...] data.data.forEach(city => { console.log(city.code, city.city); }); } }); ``` -------------------------------- ### Schedule CDEK Courier Pickup Source: https://context7.com/cdek-it/wordpress/llms.txt Use IntakeCreateAction to schedule a CDEK courier pickup from your store. It handles both door-pickup and office-pickup tariffs, storing the intake UUID and number in order meta. ```php use Cdek\Actions\IntakeCreateAction; use Cdek\Model\Order; $order = new \Cdek\Model\Order(1042); // WooCommerce order ID $intakeData = [ 'call' => 'true', // request a call before arrival 'date' => '2025-06-15', // pickup date (Y-m-d) 'from' => '10:00', // pickup window start (HH:MM, 09:00–19:00) 'to' => '14:00', // pickup window end (HH:MM, 12:00–22:00) 'comment' => 'Ring the bell', // optional comment for courier // For office-pickup tariffs, also required: // 'weight' => 2500, // total weight in grams // 'desc' => 'Electronics', // cargo description ]; try { $result = IntakeCreateAction::new()($order, $intakeData); if ($result->state) { echo 'Courier intake scheduled successfully'; // Intake UUID and number saved to order meta // Order note added: "Intake has been created: Number: X | Uuid: Y" } else { echo 'Intake error: ' . $result->message; } } catch (\Cdek\Exceptions\ShippingNotFoundException $e) { echo 'No CDEK shipping on this order'; } ``` -------------------------------- ### OrderCreateAction Source: https://context7.com/cdek-it/wordpress/llms.txt Creates a CDEK shipment from a WooCommerce order ID. It constructs the CDEK order payload, posts it to the CDEK API, and polls for the tracking number. On success, it saves the tracking number to order meta and adds a note. Failed attempts can be retried. ```APIDOC ## OrderCreateAction — Create CDEK Shipment from WooCommerce Order `OrderCreateAction` takes a WooCommerce order ID, constructs the full CDEK order payload (sender, recipient, tariff, packages with item details, services, COD settings), posts it to `POST /v2/orders/`, and polls for the resulting CDEK tracking number. On success the tracking number is saved to order meta and a note is added. Failed attempts can be automatically retried up to 5 times via WooCommerce Action Scheduler. ```php use Cdek\Actions\OrderCreateAction; use Cdek\Exceptions\External\InvalidRequestException; use Cdek\Exceptions\ShippingNotFoundException; $orderId = 1042; // WooCommerce order ID with CDEK shipping selected try { $result = OrderCreateAction::new()($orderId, 0, [ // Optional: explicit package dimensions (multi-seat mode) // If omitted, dimensions come from shipping item meta [ 'length' => 30, // cm 'width' => 20, // cm 'height' => 15, // cm 'items' => [ ['id' => 101, 'qty' => 2], ['id' => 205, 'qty' => 1], ], ], ]); if ($result->state) { echo 'CDEK order created successfully'; // Tracking number is now stored in order meta and an order note was added } else { echo 'Order creation failed: ' . $result->message; } } catch (InvalidRequestException $e) { foreach ($e->getData()['errors'] as $err) { echo 'Validation error: ' . $err['message'] . PHP_EOL; } } catch (ShippingNotFoundException $e) { echo 'Order has no CDEK shipping method selected'; } ``` ``` -------------------------------- ### CDEK REST API Callback Endpoint (Webhooks) Source: https://context7.com/cdek-it/wordpress/llms.txt This endpoint receives inbound webhooks from CDEK for events like token refreshes and task triggers. Requests must be authenticated with a PASETO token. Returns 202 Accepted on success or 400 Bad Request for unknown commands. ```bash // Endpoint: POST /wp-json/official_cdek/cb // Auth: PASETO token in Authorization header (validated server-side by Tokens::checkIncomingRequest) // Command: tokens.refresh — triggered by CDEK to rotate API tokens // Body: { "command": "tokens.refresh", ...token payload... } // Command: tasks — triggered by CDEK to execute pending tasks (e.g. order sync) // Body: { "command": "tasks" } // curl example (tokens.refresh): curl -X POST "https://yourstore.com/wp-json/official_cdek/cb" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{"command": "tokens.refresh", "token": "...", "endpoint": "https://..."}' // curl example (task execution trigger): curl -X POST "https://yourstore.com/wp-json/official_cdek/cb" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{"command": "tasks"}' // Returns 202 Accepted on success, 400 Bad Request for unknown commands ``` -------------------------------- ### Log Warnings with Exceptions Source: https://context7.com/cdek-it/wordpress/llms.txt Log warning messages, including exception details, to aid in diagnosing API call failures or other runtime errors. ```php use Cdek\Helpers\Logger; // Log a warning with an exception try { // ... API call ... } catch (\Throwable $e) { Logger::warning('CDEK API call failed', $e); // Logs: message + exception class, message, file, line, and trace } ``` -------------------------------- ### Schedule Courier Intake (Admin AJAX) Source: https://context7.com/cdek-it/wordpress/llms.txt Use these AJAX actions to request or cancel CDEK courier pickups from the WordPress order admin page. Requires `action`, `_wpnonce`, and `id` parameters. ```javascript // Create intake fetch(ajaxurl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ action: 'official_cdek-intake_create', _wpnonce: nonce, id: '1042', }), // Raw JSON body: // { "date": "2025-06-15", "from": "10:00", "to": "14:00", "call": true, "comment": "Ring bell" } // For office tariffs also add: "weight": 2500, "desc": "Electronics" }); // Delete intake fetch(ajaxurl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ action: 'official_cdek-intake_delete', _wpnonce: nonce, id: '1042', }), }); ``` -------------------------------- ### DispatchOrderAutomationAction Source: https://context7.com/cdek-it/wordpress/llms.txt Automatically triggers CDEK order creation based on WooCommerce order status transitions and checkout events. It checks for automatic order creation settings and payment gateway confirmations before scheduling the creation via Action Scheduler. ```APIDOC ## DispatchOrderAutomationAction — Automatic Order Creation Trigger `DispatchOrderAutomationAction` is hooked into WooCommerce order status transitions and the checkout process. When triggered, it checks whether automatic order creation is enabled for the shipping method and, if required, waits for specific payment gateways to confirm payment before scheduling the CDEK order creation via Action Scheduler. ```php // This action is automatically registered on plugin load: // add_action('woocommerce_order_status_changed', new DispatchOrderAutomationAction); // add_action('woocommerce_checkout_order_processed', new DispatchOrderAutomationAction, 10, 3); // add_action('woocommerce_store_api_checkout_order_processed', new DispatchOrderAutomationAction); // To trigger it programmatically (e.g. after manual payment confirmation): $action = new \Cdek\Actions\DispatchOrderAutomationAction(); $action($orderId); // will schedule via Action Scheduler if automate_orders = true // Configuration in ShippingMethod settings: // automate_orders = true — enable automatic waybill creation // automate_wait_gateways = ['bacs'] — wait for bank transfer payment before creating // The scheduled hook fires: cdekdelivery_automation($orderId, $attempt) // and calls OrderCreateAction::new()($orderId, $attempt) // It retries up to 5 times with a 5-minute delay on transient failures ``` ``` -------------------------------- ### Flush Token Cache (Admin AJAX) Source: https://context7.com/cdek-it/wordpress/llms.txt Use this AJAX action to clear the cached CDEK OAuth2 access token, forcing a new token to be fetched on the next API call. This is useful after changing API credentials. It requires `action` and `_wpnonce` parameters. ```javascript fetch(ajaxurl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ action: 'official_cdek-cache', _wpnonce: cdekdelivery_params.nonce, }), }).then(r => r.json()).then(data => { if (data.success) { console.log('CDEK token cache cleared — new token will be fetched on next API call'); } }); // PHP equivalent: \Cdek\Actions\FlushTokenCacheAction::new()(); ``` -------------------------------- ### City Autocomplete (Admin Settings AJAX) Source: https://context7.com/cdek-it/wordpress/llms.txt Provides city suggestions for the address input autocomplete in the plugin settings page by querying the CDEK city suggestion API. ```APIDOC ## AJAX Action: City Autocomplete (Admin Settings) Registered as `wp_ajax_official_cdek-cities`. ### Method GET ### Endpoint `/wp-admin/admin-ajax.php` ### Parameters #### Query Parameters - **action** (string) - Required - Must be `official_cdek-cities`. - **_wpnonce** (string) - Required - WordPress nonce for security. - **q** (string) - Required - Partial city name for searching. ### Request Example ```javascript const url = new URL(ajaxurl); url.searchParams.set('action', 'official_cdek-cities'); url.searchParams.set('_wpnonce', cdekdelivery_params.nonce); url.searchParams.set('q', 'Екатер'); // partial city name fetch(url) .then(r => r.json()) .then(data => { if (data.success) { // data.data is array of CDEK city objects: // [{ "code": 270, "city": "Екатеринбург", "region": "Свердловская обл." }, ...] data.data.forEach(city => { console.log(city.code, city.city); }); } }); ``` ### Response On success, returns a JSON object with `success: true` and a `data` field containing an array of city objects. Each city object includes `code`, `city`, and `region`. ``` -------------------------------- ### Automatic CDEK Order Creation Trigger Source: https://context7.com/cdek-it/wordpress/llms.txt DispatchOrderAutomationAction hooks into order status transitions and checkout to automatically create CDEK shipments. It can wait for specific payment gateways before scheduling the creation via Action Scheduler. ```php // This action is automatically registered on plugin load: // add_action('woocommerce_order_status_changed', new DispatchOrderAutomationAction); // add_action('woocommerce_checkout_order_processed', new DispatchOrderAutomationAction, 10, 3); // add_action('woocommerce_store_api_checkout_order_processed', new DispatchOrderAutomationAction); // To trigger it programmatically (e.g. after manual payment confirmation): $action = new \Cdek\Actions\DispatchOrderAutomationAction(); $action($orderId); // will schedule via Action Scheduler if automate_orders = true // Configuration in ShippingMethod settings: // automate_orders = true — enable automatic waybill creation // automate_wait_gateways = ['bacs'] — wait for bank transfer payment before creating // The scheduled hook fires: cdekdelivery_automation($orderId, $attempt) // and calls OrderCreateAction::new()($orderId, $attempt) // It retries up to 5 times with a 5-minute delay on transient failures ``` -------------------------------- ### Read Order Shipping Item Meta Source: https://context7.com/cdek-it/wordpress/llms.txt Retrieve CDEK-specific metadata from an order's shipping item using the MetaKeys constants. This allows access to details like tariff code, office code, and package dimensions. ```php use Cdek\MetaKeys; // Reading meta from an order's shipping item: $order = wc_get_order(1042); foreach ($order->get_items('shipping') as $item) { $tariffCode = $item->get_meta(MetaKeys::TARIFF_CODE); // e.g. "136" $officeCode = $item->get_meta(MetaKeys::OFFICE_CODE); // e.g. "MSK10" or null $weight = $item->get_meta(MetaKeys::WEIGHT); // e.g. "1500" } ``` -------------------------------- ### Schedule Courier Intake (Admin AJAX) Source: https://context7.com/cdek-it/wordpress/llms.txt Allows admin users to request or cancel CDEK courier pickups directly from the order admin page using AJAX. ```APIDOC ## AJAX Action: Schedule Courier Intake (Admin) Registers `wp_ajax_official_cdek-intake_create` and `wp_ajax_official_cdek-intake_delete`. ### Method POST ### Endpoint `/wp-admin/admin-ajax.php` ### Parameters #### Query Parameters - **action** (string) - Required - Either `official_cdek-intake_create` or `official_cdek-intake_delete`. - **_wpnonce** (string) - Required - WordPress nonce for security. - **id** (string) - Required - The ID of the order or intake. ### Request Example (Create Intake) ```javascript fetch(ajaxurl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ action: 'official_cdek-intake_create', _wpnonce: nonce, id: '1042', }), }); ``` ### Request Example (Delete Intake) ```javascript fetch(ajaxurl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ action: 'official_cdek-intake_delete', _wpnonce: nonce, id: '1042', }), }); ``` ### Notes - The commented-out JSON body in the create intake example shows optional parameters like `date`, `from`, `to`, `call`, `comment`, `weight`, and `desc` that can be included for more specific scheduling. ``` -------------------------------- ### Log Debug Messages with Context Source: https://context7.com/cdek-it/wordpress/llms.txt Log debug messages with contextual data using the Logger class. This is useful for tracking calculations and debugging issues. ```php use Cdek\Helpers\Logger; // Log a debug message with context array Logger::debug('Calculating delivery', [ 'tariff_code' => 136, 'from_city' => 270, 'weight_g' => 1500, ]); ``` -------------------------------- ### Define CDEK Order Meta Keys Source: https://context7.com/cdek-it/wordpress/llms.txt The MetaKeys class provides constants for all CDEK-specific meta keys used in WooCommerce orders and shipping items. These are crucial for persisting and retrieving CDEK data. ```php use Cdek\MetaKeys; // Meta keys stored on the WooCommerce shipping line item: // MetaKeys::TARIFF_CODE = '_official_cdek_tariff_code' — selected tariff (e.g. 136) // MetaKeys::TARIFF_MODE = '_official_cdek_tariff_mode' — delivery mode constant // MetaKeys::OFFICE_CODE = '_official_cdek_office_code' — selected PVZ/office code // MetaKeys::WEIGHT = '_official_cdek_weight' — package weight in grams // MetaKeys::LENGTH = '_official_cdek_length' — package length in cm // MetaKeys::WIDTH = '_official_cdek_width' — package width in cm // MetaKeys::HEIGHT = '_official_cdek_height' — package height in cm // MetaKeys::POSTAL = '_official_cdek_postal' — destination postal code // MetaKeys::CITY = '_official_cdek_city' — destination city name // MetaKeys::ADDRESS_HASH = '_official_cdek_address_hash' — hash of destination address // MetaKeys::JEWEL_UIN = '_official_cdek_jewel_uin' — UIN for gold/jewelry items ``` -------------------------------- ### Create CDEK Shipment from WooCommerce Order Source: https://context7.com/cdek-it/wordpress/llms.txt Use OrderCreateAction to create a CDEK shipment from a WooCommerce order. It constructs the CDEK payload, posts it to the API, and polls for the tracking number. Failed attempts can be retried. ```php use Cdek\Actions\OrderCreateAction; use Cdek\Exceptions\External\InvalidRequestException; use Cdek\Exceptions\ShippingNotFoundException; $orderId = 1042; // WooCommerce order ID with CDEK shipping selected try { $result = OrderCreateAction::new()($orderId, 0, [ // Optional: explicit package dimensions (multi-seat mode) // If omitted, dimensions come from shipping item meta [ 'length' => 30, // cm 'width' => 20, // cm 'height' => 15, // cm 'items' => [ ['id' => 101, 'qty' => 2], ['id' => 205, 'qty' => 1], ], ], ]); if ($result->state) { echo 'CDEK order created successfully'; // Tracking number is now stored in order meta and an order note was added } else { echo 'Order creation failed: ' . $result->message; } } catch (InvalidRequestException $e) { foreach ($e->getData()['errors'] as $err) { echo 'Validation error: ' . $err['message'] . PHP_EOL; } } catch (ShippingNotFoundException $e) { echo 'Order has no CDEK shipping method selected'; } ``` -------------------------------- ### Register CDEKDelivery Shipping Method Source: https://context7.com/cdek-it/wordpress/llms.txt This code snippet shows how to register the CDEKDelivery shipping method with WooCommerce. It's typically done automatically by the plugin. ```php add_filter( 'woocommerce_shipping_methods', fn(array $methods) => array_merge($methods, ['official_cdek' => \Cdek\ShippingMethod::class]) ); ``` -------------------------------- ### Classify CDEK Tariff Delivery Modes Source: https://context7.com/cdek-it/wordpress/llms.txt Use the Tariff class to determine delivery modes (to/from office/door) and check availability for shop orders. It also provides tariff display names and types for API requests. ```php use Cdek\Model\Tariff; // Check delivery mode for tariff 136 (Посылка склад-склад) Tariff::isToOffice(136); // true — delivery to CDEK office/PVZ Tariff::isFromOffice(136); // true — pickup from CDEK office Tariff::isFromDoor(139); // true — tariff 139 = Посылка дверь-дверь // Get tariff display name (respects custom names from settings) echo Tariff::getName(136, 'Посылка склад-склад'); // "CDEK: Посылка склад-склад" // or custom name if configured as "136-My Custom Name" in settings: echo Tariff::getName(136, ''); // "My Custom Name" // Get delivery type (SHOP_TYPE=1 or DELIVERY_TYPE=2) for API request $type = Tariff::getType(136); // 1 (SHOP_TYPE) $type = Tariff::getType(748); // 2 (DELIVERY_TYPE) — Сборный груз // List all available tariffs for display in settings multiselect $all = Tariff::list(); // [136 => 'Посылка склад-склад (136)', 137 => 'Посылка склад-дверь (137)', ...] // Check if tariff supports parcel lockers (postamats) Tariff::isToPickup(366); // true — Посылка дверь-постамат Tariff::isToPickup(136); // false ``` -------------------------------- ### Generate CDEK Barcode via AJAX (Admin) Source: https://context7.com/cdek-it/wordpress/llms.txt This JavaScript snippet generates a CDEK barcode image and displays it. It sends a request to the 'official_cdek-barcode' AJAX action and expects a base64-encoded image string in the response. ```javascript const url = new URL(ajaxurl); url.searchParams.set('action', 'official_cdek-barcode'); url.searchParams.set('_wpnonce', cdekdelivery_params.nonce); url.searchParams.set('id', '1042'); fetch(url) .then(r => r.json()) .then(data => { if (data.success) { // data.data is base64-encoded barcode image (PDF or PNG depending on format setting) document.getElementById('barcode-img').src = 'data:application/pdf;base64,' + data.data; } else { alert('Barcode generation failed: ' + data.data?.message); } }); ``` -------------------------------- ### Flush Token Cache (Admin Settings AJAX) Source: https://context7.com/cdek-it/wordpress/llms.txt Clears the cached CDEK OAuth2 access token, forcing a fresh token fetch on the next API call. Useful when API credentials are changed. ```APIDOC ## AJAX Action: Flush Token Cache (Admin Settings) Registered as `wp_ajax_official_cdek-cache`. ### Method POST ### Endpoint `/wp-admin/admin-ajax.php` ### Parameters #### Query Parameters - **action** (string) - Required - Must be `official_cdek-cache`. - **_wpnonce** (string) - Required - WordPress nonce for security. ### Request Example ```javascript fetch(ajaxurl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ action: 'official_cdek-cache', _wpnonce: cdekdelivery_params.nonce, }), }).then(r => r.json()).then(data => { if (data.success) { console.log('CDEK token cache cleared — new token will be fetched on next API call'); } }); ``` ### PHP Equivalent ```php \Cdek\Actions\FlushTokenCacheAction::new()(); ``` ``` -------------------------------- ### Log Other PSR-3 Levels Source: https://context7.com/cdek-it/wordpress/llms.txt Utilize the full PSR-3 log level hierarchy (info, error, critical) for comprehensive logging of application events and errors. ```php use Cdek\Helpers\Logger; // Other log levels: Logger::info('Order sent to CDEK', ['order_id' => 1042]); Logger::error('Authentication failed', ['client_id' => 'abc123']); Logger::critical('CDEK plugin fatal error', $exception); // Logs are viewable at: // WooCommerce > Status > Logs > cdekdelivery-YYYY-MM-DD-*.log // Or via WP-CLI: wp wc log list ``` -------------------------------- ### CDEK Webhook Callback Endpoint Source: https://context7.com/cdek-it/wordpress/llms.txt This REST API endpoint receives inbound webhooks from CDEK's backend for events like token refreshes and task triggers. ```APIDOC ## REST API Callback Endpoint — Inbound Webhooks from CDEK Registers `POST /wp-json/official_cdek/cb`. ### Method POST ### Endpoint `/wp-json/official_cdek/cb` ### Authentication PASETO token in the `Authorization` header. ### Request Body Requests are JSON formatted and contain a `command` field. #### Commands - **tokens.refresh**: Triggered by CDEK to rotate API tokens. Expected body includes `command`, `token`, and `endpoint`. - **tasks**: Triggered by CDEK to execute pending tasks, such as order synchronization. ### Request Example (tokens.refresh) ```bash curl -X POST "https://yourstore.com/wp-json/official_cdek/cb" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{"command": "tokens.refresh", "token": "...", "endpoint": "https://..."}' ``` ### Request Example (tasks) ```bash curl -X POST "https://yourstore.com/wp-json/official_cdek/cb" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{"command": "tasks"}' ``` ### Response - **202 Accepted**: On successful command processing. - **400 Bad Request**: For unknown commands. ``` -------------------------------- ### Read CDEK Tracking Number from Order Meta Source: https://context7.com/cdek-it/wordpress/llms.txt Access the CDEK tracking number, which is stored as order meta with the key '_official_cdek_number'. This is typically set when an order is created or processed. ```php // Reading CDEK tracking number stored on the order: // Stored via \Cdek\Model\Order::$number (WooCommerce order meta '_official_cdek_number') $cdekNumber = $order->get_meta('_official_cdek_number'); // e.g. "1234567890" ``` -------------------------------- ### Delete CDEK Order via AJAX (Admin) Source: https://context7.com/cdek-it/wordpress/llms.txt Use this JavaScript to delete a CDEK order via AJAX. It sends a POST request to the 'official_cdek-delete' action, which removes the order from CDEK and updates the WooCommerce order meta. ```javascript fetch(ajaxurl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ action: 'official_cdek-delete', _wpnonce: nonce, id: '1042', }), }).then(r => { // AdminOrderBox HTML fragment returned; re-render the meta box }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.