### Install Dependencies and Run Example Source: https://github.com/retailcrm/api-client-php/blob/master/doc/customization/examples/custom-api-methods-with-dto/README.md Install project dependencies using Composer and execute the main application file to see the custom API method in action. This verifies the setup and custom serializer integration. ```sh composer install php app.php ``` -------------------------------- ### Complete composer.json Configuration for Manual Setup Source: https://github.com/retailcrm/api-client-php/blob/master/doc/compilation_prompt.md This is an example of a complete composer.json file with manual configuration to enable code generation and disable compilation prompts. ```json { "name": "author/some-project", "description": "Description of the project.", "type": "project", "license": "MIT", "require": { "php": ">=7.3.0", "symfony/http-client": "^5.2", "nyholm/psr7": "^1.4", "retailcrm/api-client-php": "~6.0" }, "config": { "allow-plugins": { "civicrm/composer-compile-plugin": true } }, "extra": { "compile-mode": "whitelist", "compile-whitelist": ["retailcrm/api-client-php"] } } ``` -------------------------------- ### ClientFactory Basic Setup Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/instantiation.md Demonstrates the basic setup of ClientFactory, including setting a cache directory and an event dispatcher. This factory is stateful and intended for integration with dependency injection containers. ```php use RetailCrm\Api\Factory\ClientFactory; use League\Event\EventDispatcher; $eventDispatcher = new EventDispatcher(); $factory = new ClientFactory(); $factory ->setCacheDir('/tmp/retailcrm_cache') ->setEventDispatcher($eventDispatcher); $client = $factory->createClient('https://test.retailcrm.pro', 'key'); ``` -------------------------------- ### Install RetailCRM API PHP Client with Composer Source: https://github.com/retailcrm/api-client-php/blob/master/README.md Use this Composer command to install the RetailCRM API PHP client library with version constraint '~6.0'. ```bash composer require retailcrm/api-client-php:"~6.0" ``` -------------------------------- ### Creating a Customer Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/sending_a_request.md Example of creating a new customer with email and site information. ```APIDOC ## Creating a Customer ### Description This request will create a new customer. ### Method ```php $client->customers->create($request) ``` ### Request Body Example ```php use RetailCrm\Api\Factory\SimpleClientFactory; use RetailCrm\Api\Model\Entity\Customers\Customer; use RetailCrm\Api\Model\Request\Customers\CustomersCreateRequest; $client = SimpleClientFactory::createClient('https://test.retailcrm.pro', 'key'); $request = new CustomersCreateRequest(); $request->customer = new Customer(); $request->customer->email = 'test@example.com'; $request->site = 'site'; $response = $client->customers->create($request); ``` ### Response Example (Response structure depends on the API, typically an ID or status) ``` -------------------------------- ### Configuring ClientFactory with league/container Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/instantiation.md This example shows how to configure the league/container to instantiate ClientFactory once and inject it into other services. It sets up cache and event dispatchers. ```php use RetailCrm\Api\Factory\ClientFactory; use RetailCrm\Api\Interfaces\ClientFactoryInterface; use League\Container\Container; use League\Event\EventDispatcher; use Psr\Cache\CacheItemPoolInterface; use Psr\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use App\Services\ClientFactoryDependentService; use App\Controller\HealthCheckController; $container = new Container(); $container->add(CacheItemPoolInterface::class, new FilesystemAdapter('test_app')); $container->add(EventDispatcherInterface::class, EventDispatcher::class); $container->add(ClientFactoryInterface::class, ClientFactory::class) ->addMethodCalls([ 'setCache' => [CacheItemPoolInterface::class], 'setEventDispatcher' => [EventDispatcherInterface::class], ]); $container->add(ClientFactoryDependentService::class)->addArgument(ClientFactoryInterface::class); $container->add(HealthCheckController::class)->addArgument(ClientFactoryDependentService::class); ``` -------------------------------- ### Example Output Source: https://github.com/retailcrm/api-client-php/blob/master/doc/customization/examples/custom-api-methods-with-dto/README.md This output indicates that the custom API method successfully created a customer using the configured DTOs and custom serializer. ```sh Created customer using custom methods. ID: 5633 ``` -------------------------------- ### Configuring ClientFactory with PSR dependencies Source: https://github.com/retailcrm/api-client-php/blob/master/doc/customization/different_psr_implementations.md Example of configuring the ClientFactory with a custom HTTP client and PSR-17 factories. ```php $psr17Factory = new \Nyholm\Psr7\Factory\Psr17Factory(); $factory = new \RetailCrm\Api\Factory\ClientFactory(); $factory->setHttpClient(new \Http\Client\Curl\Client()) ->setRequestFactory($psr17Factory) ->setStreamFactory($psr17Factory) ->setUriFactory($psr17Factory); $client = $factory->createClient('https://test.retailcrm.pro', 'apiKey'); ``` -------------------------------- ### Install with Custom PSR Implementations Source: https://github.com/retailcrm/api-client-php/blob/master/README.md Install the API client along with specific PSR-18, PSR-17, and PSR-7 implementations like Symfony HTTP client and Guzzle PSR7. ```bash composer require symfony/http-client guzzlehttp/psr7 retailcrm/api-client-php:"~6.0" ``` -------------------------------- ### Install PSR-17, PSR-7, and PSR-18 Implementations Source: https://github.com/retailcrm/api-client-php/blob/master/doc/troubleshooting.md Install recommended packages like nyholm/psr7 and symfony/http-client to fix 'DiscoveryFailedException' or 'Could not find resource' errors. ```sh composer require nyholm/psr7 symfony/http-client ``` -------------------------------- ### Getting a Customer by ID Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/sending_a_request.md Example of fetching a specific customer using their ID and site. ```APIDOC ## Getting a Customer by ID ### Description This one will fetch specific customer from the API by the ID and site. ### Method ```php $client->customers->get($identifier, new BySiteRequest($identifierType, $site)) ``` ### Request Body Example ```php use RetailCrm\Api\Enum\ByIdentifier; use RetailCrm\Api\Factory\SimpleClientFactory; use RetailCrm\Api\Model\Request\BySiteRequest; $client = SimpleClientFactory::createClient('https://test.retailcrm.pro', 'key'); $response = $client->customers->get(1, new BySiteRequest(ByIdentifier::ID, 'site')); echo $response->customer->email; ``` ### Response Example (Response structure depends on the API, typically contains customer details) ``` -------------------------------- ### Configuring ClientBuilder with PSR dependencies Source: https://github.com/retailcrm/api-client-php/blob/master/doc/customization/different_psr_implementations.md Example of configuring the ClientBuilder with a custom HTTP client and PSR-17 factories. ```php $psr17Factory = new \Nyholm\Psr7\Factory\Psr17Factory(); $builder = new \RetailCrm\Api\Builder\ClientBuilder(); $client = $builder ->setApiUrl('https://test.retailcrm.pro') ->setAuthenticatorHandler(new \RetailCrm\Api\Handler\Request\HeaderAuthenticatorHandler('apiKey')) ->setHttpClient(new \Http\Client\Curl\Client()) ->setRequestFactory($psr17Factory) ->setStreamFactory($psr17Factory) ->setUriFactory($psr17Factory) ->build(); ``` -------------------------------- ### Register and Call a Custom API Method (GET) Source: https://github.com/retailcrm/api-client-php/blob/master/doc/customization/implementing_custom_api_methods.md Register a custom GET method for fetching dialogs and then call it. This demonstrates the basic usage of `CustomApiMethod` for implementing unoffical API endpoints. ```php use RetailCrm\Api\Component\CustomApiMethod; use RetailCrm\Api\Enum\RequestMethod; use RetailCrm\Api\Factory\SimpleClientFactory; use RetailCrm\Api\Interfaces\ApiExceptionInterface; $client = SimpleClientFactory::createClient('https://test.simla.io', 'key'); $client->customMethods->register('dialogs', new CustomApiMethod(RequestMethod::GET, 'dialogs')); try { $dialogs = $client->customMethods->call('dialogs'); } catch (ApiExceptionInterface $exception) { echo sprintf( 'Error from RetailCRM API (status code: %d): %s', $exception->getStatusCode(), $exception->getMessage() ); if (count($exception->getErrorResponse()->errors) > 0) { echo PHP_EOL . 'Errors: ' . implode(', ', $exception->getErrorResponse()->errors); } return; } echo 'Dialogs: ' . print_r($dialogs['dialogs'], true); ``` -------------------------------- ### Install Nyholm PSR7 for Supported Factories Source: https://github.com/retailcrm/api-client-php/blob/master/doc/troubleshooting.md Install the nyholm/psr7 package to resolve 'No Message Factories' errors by providing a supported PSR-17 implementation. ```sh composer require nyholm/psr7 ``` -------------------------------- ### Catching API and Client Exceptions Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/error_handling.md This example demonstrates how to catch both API-specific exceptions (implementing `ApiExceptionInterface`) and client-specific exceptions (implementing `ClientExceptionInterface`) using a combined catch block. It shows basic client initialization and an API call that might fail. ```php use RetailCrm\Api\Factory\SimpleClientFactory; use RetailCrm\Api\Interfaces\ApiExceptionInterface; use RetailCrm\Api\Interfaces\ClientExceptionInterface; $client = SimpleClientFactory::createClient('https://test.retailcrm.pro', 'apiKey'); try { $apiVersions = $client->api->apiVersions(); } catch (ApiExceptionInterface | ClientExceptionInterface $exception) { echo $exception; return; } echo 'Available API versions: ' . implode(', ', $apiVersions->versions); ``` -------------------------------- ### Automated CLI Utility to Enable Code Generation Source: https://github.com/retailcrm/api-client-php/blob/master/doc/compilation_prompt.md Run this command in your project's root directory after API client installation to automatically configure composer.json and enable code generation. ```sh ./vendor/bin/retailcrm-client compiler:prompt ``` -------------------------------- ### Editing a Customer Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/sending_a_request.md Example of editing an existing customer's details using their ID and site. ```APIDOC ## Editing a Customer ### Description And this one will edit specific customer: ### Method ```php $client->customers->edit($identifier, $request) ``` ### Request Body Example ```php use RetailCrm\Api\Enum\ByIdentifier; use RetailCrm\Api\Factory\SimpleClientFactory; use RetailCrm\Api\Model\Entity\Customers\Customer; use RetailCrm\Api\Model\Request\Customers\CustomersEditRequest; $client = SimpleClientFactory::createClient('https://test.retailcrm.pro', 'key'); $request = new CustomersEditRequest(); $request->customer = new Customer(); $request->customer->email = 'test@example.com'; $request->site = 'site'; $request->by = ByIdentifier::ID; $response = $client->customers->edit(1, $request); echo "Edited customer ID: " . $response->id; ``` ### Response Example (Response structure depends on the API, typically returns the ID of the edited customer) ``` -------------------------------- ### PHP API Client with Complete Error Handling Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/examples/complete_error_handling_example.md This example demonstrates how to fetch filtered orders data using the RetailCRM API client and handle a wide range of potential exceptions. It includes specific catches for handler, HTTP client, network, request, various API errors (like invalid credentials, access denied, account not found, missing parameters, validation errors), and general throwable errors. It is not recommended for production due to potential code clutter. ```php filter = new OrderFilter(); $request->filter->ids = [7141]; try { $response = $client->orders->list($request); } catch (HandlerException $exception) { echo 'Error while trying to prepare request: ' . $exception->getMessage(); exit(-1); } catch (HttpClientException $exception) { $prefix = 'Unknown error'; if ($exception->getPrevious() instanceof NetworkExceptionInterface) { $prefix = 'Network error'; } if ($exception->getPrevious() instanceof RequestExceptionInterface) { $prefix = 'Invalid request'; } if ($exception->getPrevious() instanceof PsrClientExceptionInterface) { $prefix = 'HTTP client exception'; } echo $prefix . ': ' . $exception->getMessage(); exit(-1); } catch ( InvalidCredentialsException | AccessDeniedException | AccountDoesNotExistException | MissingCredentialsException | MissingParameterException $exception ) { echo $exception->getMessage(); exit(-1); } catch (ValidationException $exception) { echo 'Errors in fields:' . PHP_EOL; foreach ($exception->getErrorResponse()->errors as $field => $error) { printf(" - %s: %s\n", $field, $error); } exit(-1); } catch (ApiExceptionInterface | ClientExceptionInterface $exception) { echo $exception; // Every ApiException and ClientException implements __toString() method exit(-1); } catch (Throwable $throwable) { echo 'Unknown runtime exception: ' . $throwable->getMessage() . PHP_EOL; echo $throwable->getTraceAsString(); exit(-1); } foreach ($response->orders as $order) { printf("Order ID: %d\n", $order->id); printf("First name: %s\n", $order->firstName); printf("Last name: %s\n", $order->lastName); printf("Patronymic: %s\n", $order->patronymic); printf("Phone #1: %s\n", $order->phone); printf("Phone #2: %s\n", $order->additionalPhone); printf("E-Mail: %s\n", $order->email); if ($order->customer instanceof CustomerCorporate) { echo "Customer type: corporate\n"; } else { echo "Customer type: individual\n"; } foreach ($order->items as $item) { echo PHP_EOL; printf("Product name: %s\n", $item->productName); printf("Quantity: %d\n", $item->quantity); printf("Initial price: %f\n", $item->initialPrice); } echo PHP_EOL; printf("Discount: %f\n", $order->discountManualAmount); printf("Total: %f\n", $order->totalSumm); echo PHP_EOL; } ``` -------------------------------- ### Controller Using Client Factory Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/event_handing.md A Symfony controller that utilizes the `ClientFactoryInterface` to create an API client and fetch credentials. This example demonstrates a typical usage pattern where API calls are made without explicit try-catch blocks, relying on event listeners for error handling. ```php createClient('https://test3487687.retailcrm.pro', 'key'); $credentials = $client->api->credentials(); // Will print out empty model because https://test3487687.retailcrm.pro account does not exist. return $this->json($credentials); } } ``` -------------------------------- ### Include Composer Autoloader in PHP Source: https://github.com/retailcrm/api-client-php/blob/master/README.md Include the Composer autoloader file in your PHP script to enable the use of installed libraries. Replace 'path/to/vendor/autoload.php' with the actual path. ```php require 'path/to/vendor/autoload.php'; ``` -------------------------------- ### Customize Request Pipeline with CallbackRequestHandler Source: https://github.com/retailcrm/api-client-php/blob/master/doc/customization/pipelines/using_a_predefined_handler.md Add custom logic to the request pipeline by using a CallbackRequestHandler. This example demonstrates adding a custom header to outgoing requests. ```php use RetailCrm\Api\Builder\ClientBuilder; use RetailCrm\Api\Builder\FormEncoderBuilder; use RetailCrm\Api\Component\Transformer\RequestTransformer; use RetailCrm\Api\Factory\RequestPipelineFactory; use RetailCrm\Api\Handler\Request\CallbackRequestHandler; use RetailCrm\Api\Model\RequestData; $requestHandler = new CallbackRequestHandler( static function ( RequestData $requestData, RequestFactoryInterface $requestFactory, StreamFactoryInterface $streamFactory, UriFactoryInterface $uriFactory ) { if (null !== $requestData->request) { $requestData->request = $requestData->request->withHeader('X-Rlimit-Token', 'example_token'); } } ); $builder = new ClientBuilder(); $formEncoder = (new FormEncoderBuilder())->setCacheDir('cache')->build(); $client = $builder->setApiUrl('https://test.retailcrm.pro') ->setAuthenticatorHandler(new HeaderAuthenticatorHandler('apiKey')) ->setRequestTransformer(new RequestTransformer( RequestPipelineFactory::createDefaultPipeline( $formEncoder, null, // PSR factories will be found by the service discovery. null, null, $requestHandler ) )) ->setResponseTransformer(new ResponseTransformer( ResponsePipelineFactory::createDefaultPipeline( $formEncoder->getSerializer(), new ApiExceptionFactory(), null, // No EventDispatcherInterface was provided $responseHandler ) ))->build(); ``` -------------------------------- ### Customize Response Pipeline with CallbackResponseHandler Source: https://github.com/retailcrm/api-client-php/blob/master/doc/customization/pipelines/using_a_predefined_handler.md Implement custom response validation or modification using a CallbackResponseHandler. This example checks for missing parameters in the response model and throws an exception. ```php use RetailCrm\Api\Exception\Api\MissingParameterException; use RetailCrm\Api\Factory\ApiExceptionFactory; use RetailCrm\Api\Factory\ResponsePipelineFactory; use RetailCrm\Api\Handler\Response\CallbackResponseHandler; use RetailCrm\Api\Model\Response\Api\Credentials; use RetailCrm\Api\Model\Response\ErrorResponse; use RetailCrm\Api\Model\ResponseData; $responseHandler = new CallbackResponseHandler( static function ( ResponseData $data, SerializerInterface $serializer, EventDispatcherInterface $eventDispatcher, ApiExceptionFactory $apiExceptionFactory ) { if ( $data->responseModel instanceof Credentials && !in_array('/api/customers/create', $data->responseModel->credentials) ) { $data->responseModel = new ErrorResponse(); $data->responseModel->errorMsg = 'Parameter "/api/customers/create" is missing'; throw new MissingParameterException($data->responseModel, 400); } } ); $builder = new ClientBuilder(); $formEncoder = (new FormEncoderBuilder())->setCacheDir('cache')->build(); $client = $builder->setApiUrl('https://test.retailcrm.pro') ->setAuthenticatorHandler(new HeaderAuthenticatorHandler('apiKey')) ->setRequestTransformer(new RequestTransformer( RequestPipelineFactory::createDefaultPipeline( $formEncoder, null, // PSR factories will be found by the service discovery. null, null, $requestHandler ) )) ->setResponseTransformer(new ResponseTransformer( ResponsePipelineFactory::createDefaultPipeline( $formEncoder->getSerializer(), new ApiExceptionFactory(), null, // No EventDispatcherInterface was provided $responseHandler ) ))->build(); ``` -------------------------------- ### Fetch Orders List in PHP Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/examples/fetch_orders.md Use this snippet to retrieve a list of orders from the RetailCRM API. It includes basic error handling for API exceptions and iterates through the orders to display key information such as customer details and items. Ensure you have the RetailCRM API client library installed. ```php orders->list(); } catch (ApiExceptionInterface | ClientExceptionInterface $exception) { echo $exception; // Every ApiExceptionInterface instance should implement __toString() method. exit(-1); } foreach ($response->orders as $order) { printf("Order ID: %d\n", $order->id); printf("First name: %s\n", $order->firstName); printf("Last name: %s\n", $order->lastName); printf("Patronymic: %s\n", $order->patronymic); printf("Phone #1: %s\n", $order->phone); printf("Phone #2: %s\n", $order->additionalPhone); printf("E-Mail: %s\n", $order->email); if ($order->customer instanceof CustomerCorporate) { echo "Customer type: corporate\n"; } else { echo "Customer type: individual\n"; } foreach ($order->items as $item) { echo PHP_EOL; printf("Product name: %s\n", $item->productName); printf("Quantity: %d\n", $item->quantity); printf("Initial price: %f\n", $item->initialPrice); } echo PHP_EOL; printf("Discount: %f\n", $order->discountManualAmount); printf("Total: %f\n", $order->totalSumm); echo PHP_EOL; } ``` -------------------------------- ### Configure Event Dispatcher in Symfony Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/event_handing.md Define the `ClientFactory` in `services.yml` to use a specific event dispatcher. This setup ensures that events dispatched by the client are routed to the configured dispatcher. ```yaml services: # ClientFactory definition. RetailCrm\Api\Interfaces\ClientFactoryInterface: class: 'RetailCrm\Api\Factory\ClientFactory' calls: - setCacheDir: ['%kernel.cache_dir%'] - setEventDispatcher: ['@event_dispatcher'] ``` -------------------------------- ### Create a Simple Client Instance and Call API Methods Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/sending_a_request.md Instantiate a simple client and call API methods that do not require parameters, such as apiVersions and credentials. ```php use RetailCrm\Api\Factory\SimpleClientFactory; $client = SimpleClientFactory::createClient('https://test.retailcrm.pro', 'key'); $client->api->apiVersions(); $client->api->credentials(); ``` -------------------------------- ### Initialize RetailCRM API Client Source: https://github.com/retailcrm/api-client-php/blob/master/README.md Use SimpleClientFactory to create a client instance. Provide the API endpoint URL and your API key. ```php $client = \RetailCrm\Api\Factory\SimpleClientFactory::createClient('https://test.retailcrm.pro', 'apiKey'); ``` -------------------------------- ### Fetch Orders List Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/examples/fetch_orders.md This snippet shows how to initialize the client and fetch a list of orders. It includes basic error handling and iterates through the orders to display key information. ```APIDOC ## Fetch Orders List ### Description This operation fetches a list of orders from the CRM. ### Method This is an SDK method call, not an HTTP request. ### Endpoint Not applicable (SDK method). ### Parameters This method does not take any explicit parameters in this example, but the client must be initialized with a base URL and API key. ### Request Example ```php orders->list(); // Process the response foreach ($response->orders as $order) { printf("Order ID: %d\n", $order->id); printf("First name: %s\n", $order->firstName); // ... other order details ... } } catch (ApiExceptionInterface | ClientExceptionInterface $exception) { echo $exception; exit(-1); } ``` ### Response #### Success Response The response contains a list of `Order` objects. - **orders** (array) - An array of order objects. #### Response Example ```json { "orders": [ { "id": 123, "firstName": "John", "lastName": "Doe", "patronymic": "", "phone": "+1234567890", "additionalPhone": null, "email": "john.doe@example.com", "customer": { "type": "individual", "id": 456 }, "items": [ { "productName": "Example Product", "quantity": 1, "initialPrice": 100.00 } ], "discountManualAmount": 0.00, "totalSumm": 100.00 } ], "pagination": { "limit": 50, "offset": 0, "totalCount": 1 } } ``` ``` -------------------------------- ### Simple Client Instantiation Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/instantiation.md Use SimpleClientFactory::createClient for the easiest way to instantiate an API client without complex configuration. This is suitable for basic usage where advanced integration is not required. ```php use RetailCrm\Api\Factory\SimpleClientFactory; $client = SimpleClientFactory::createClient('https://test.retailcrm.pro', 'key'); ``` -------------------------------- ### Create New Customer with RetailCRM API Client (PHP) Source: https://github.com/retailcrm/api-client-php/blob/master/README.md Demonstrates creating a new customer in RetailCRM. Sets customer details like email, first name, and last name. Requires the client to be initialized and includes error handling. ```php customer = new Customer(); $request->site = 'aliexpress'; $request->customer->email = 'john.doe@example.com'; $request->customer->firstName = 'John'; $request->customer->lastName = 'Doe'; try { $response = $client->customers->create($request); } catch (ApiExceptionInterface | ClientExceptionInterface $exception) { echo $exception; // Every ApiExceptionInterface instance should implement __toString() method. exit(-1); } echo 'Customer ID: ' . $response->id; ``` -------------------------------- ### Create a New Customer Request Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/sending_a_request.md This snippet demonstrates how to create a new customer by initializing a CustomersCreateRequest, setting customer details, and specifying the site. ```php use RetailCrm\Api\Factory\SimpleClientFactory; use RetailCrm\Api\Model\Entity\Customers\Customer; use RetailCrm\Api\Model\Request\Customers\CustomersCreateRequest; $client = SimpleClientFactory::createClient('https://test.retailcrm.pro', 'key'); $request = new CustomersCreateRequest(); $request->customer = new Customer(); $request->customer->email = 'test@example.com'; $request->site = 'site'; $response = $client->customers->create($request); ``` -------------------------------- ### Creating a New Customer Source: https://github.com/retailcrm/api-client-php/blob/master/README.md Demonstrates how to create a new customer in RetailCRM. ```APIDOC ## Creating a New Customer ### Description Creates a new customer record in the RetailCRM system. ### Method `POST` (Implicitly through client method) ### Endpoint `/customers` (Implicitly through client method) ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body - **customer** (object) - Required - The customer data object. - **email** (string) - Optional - The customer's email address. - **firstName** (string) - Optional - The customer's first name. - **lastName** (string) - Optional - The customer's last name. - **site** (string) - Required - The site the customer belongs to. ### Request Example ```php customer = new Customer(); $request->site = 'aliexpress'; $request->customer->email = 'john.doe@example.com'; $request->customer->firstName = 'John'; $request->customer->lastName = 'Doe'; try { $response = $client->customers->create($request); } catch (ApiExceptionInterface | ClientExceptionInterface $exception) { echo $exception; exit(-1); } echo 'Customer ID: ' . $response->id; ``` ### Response #### Success Response (200) - **id** (integer) - The ID of the newly created customer. #### Response Example ```json { "id": 12345 } ``` ``` -------------------------------- ### Retrieve Customers List Source: https://github.com/retailcrm/api-client-php/blob/master/README.md Initialize the client and then call the list method on the customers resource group to fetch a list of customers. ```php $client = \RetailCrm\Api\Factory\SimpleClientFactory::createClient('https://test.retailcrm.pro', 'apiKey'); $response = $client->customers->list(); ``` -------------------------------- ### Initialize Client with CallbackResponseHandler via ClientBuilder Source: https://github.com/retailcrm/api-client-php/blob/master/doc/customization/pipelines/using_a_predefined_handler.md Initializes the client using ClientBuilder and appends a `CallbackResponseHandler` to handle specific API responses and exceptions. ```php use RetailCrm\Api\Builder\ClientBuilder; use RetailCrm\Api\Builder\FormEncoderBuilder; use RetailCrm\Api\Exception\Api\MissingParameterException; use RetailCrm\Api\Factory\ApiExceptionFactory; use RetailCrm\Api\Handler\Request\HeaderAuthenticatorHandler; use RetailCrm\Api\Handler\Response\CallbackResponseHandler; use RetailCrm\Api\Model\Response\Api\Credentials; use RetailCrm\Api\Model\Response\ErrorResponse; use RetailCrm\Api\Model\ResponseData; use Liip\Serializer\SerializerInterface; use Psr\EventDispatcher\EventDispatcherInterface; $handler = new CallbackResponseHandler( static function ( ResponseData $data, SerializerInterface $serializer, EventDispatcherInterface $eventDispatcher, ApiExceptionFactory $apiExceptionFactory ) { if ( $data->responseModel instanceof Credentials && !in_array('/api/customers/create', $data->responseModel->credentials) ) { $data->responseModel = new ErrorResponse(); $data->responseModel->errorMsg = 'Parameter "/api/customers/create" is missing'; throw new MissingParameterException($data->responseModel, 400); } } ); $formEncoder = (new FormEncoderBuilder())->setCacheDir('cache')->build(); $builder = new ClientBuilder(); $client = $builder->setApiUrl('https://test.retailcrm.pro') ->setAuthenticatorHandler(new HeaderAuthenticatorHandler('apiKey')) ->setFormEncoder($formEncoder) ->appendRequestHandler($handler) ->build(); ``` -------------------------------- ### Initialize Client with CallbackRequestHandler via ClientFactory Source: https://github.com/retailcrm/api-client-php/blob/master/doc/customization/pipelines/using_a_predefined_handler.md Initializes the client using ClientFactory and appends a `CallbackRequestHandler` to modify request headers. ```php use RetailCrm\Api\Factory\ClientFactory; use RetailCrm\Api\Handler\Request\CallbackRequestHandler; use RetailCrm\Api\Model\RequestData; use Psr\Http\Message\RequestFactoryInterface; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\UriFactoryInterface; $handler = new CallbackRequestHandler( static function ( RequestData $requestData, RequestFactoryInterface $requestFactory, StreamFactoryInterface $streamFactory, UriFactoryInterface $uriFactory ) { if (null !== $requestData->request) { $requestData->request = $requestData->request->withHeader('X-Rlimit-Token', 'example_token'); } } ); $factory = new ClientFactory(); $client = $factory->appendRequestHandler($handler)->createClient('https://test.retailcrm.pro', 'apiKey'); ``` -------------------------------- ### Instantiate Client with ClientBuilder Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/instantiation.md Use `ClientBuilder` for advanced client instantiation, allowing customization of dependencies like HTTP clients, transformers, and authenticator handlers. This method is powerful but complex. ```php use Http\Client\Curl\Client as CurlClient; use League\Event\EventDispatcher; use Nyholm\Psr7\Factory\Psr17Factory; use RetailCrm\Api\Builder\ClientBuilder; use RetailCrm\Api\Builder\FormEncoderBuilder; use RetailCrm\Api\Component\Transformer\RequestTransformer; use RetailCrm\Api\Component\Transformer\ResponseTransformer; use RetailCrm\Api\Factory\ApiExceptionFactory; use RetailCrm\Api\Factory\RequestPipelineFactory; use RetailCrm\Api\Factory\ResponsePipelineFactory; use RetailCrm\Api\Handler\Request\HeaderAuthenticatorHandler; $eventDispatcher = new EventDispatcher(); $psr17Factory = new Psr17Factory(); $httpClient = new CurlClient(); $builder = new ClientBuilder(); $formEncoder = (new FormEncoderBuilder())->setCacheDir('cache')->build(); $client = $builder->setApiUrl('https://test.retailcrm.pro') ->setAuthenticatorHandler(new HeaderAuthenticatorHandler('apiKey')) ->setFormEncoder($formEncoder) ->setHttpClient($httpClient) ->setRequestTransformer(new RequestTransformer( RequestPipelineFactory::createDefaultPipeline( $formEncoder, $psr17Factory, // PSR-17 UriFactoryInterface $psr17Factory, // PSR-17 RequestFactoryInterface $psr17Factory // PSR-17 StreamFactoryInterface ) )) ->setResponseTransformer(new ResponseTransformer( ResponsePipelineFactory::createDefaultPipeline( $formEncoder->getSerializer(), new ApiExceptionFactory(), $eventDispatcher ) ))->build(); ``` -------------------------------- ### Retrieve Orders List Source: https://github.com/retailcrm/api-client-php/blob/master/README.md Initialize the client and then call the list method on the orders resource group to fetch a list of orders. ```php $client = \RetailCrm\Api\Factory\SimpleClientFactory::createClient('https://test.retailcrm.pro', 'apiKey'); $response = $client->orders->list(); ``` -------------------------------- ### Listing Orders Source: https://github.com/retailcrm/api-client-php/blob/master/README.md Demonstrates how to fetch a list of orders from RetailCRM. ```APIDOC ## Listing Orders ### Description Fetches a list of orders from the RetailCRM system. ### Method `GET` (Implicitly through client method) ### Endpoint `/orders` (Implicitly through client method) ### Parameters None explicitly shown for the `list()` method itself, but the client is initialized with a base URL and API key. ### Request Example ```php orders->list(); } catch (ApiExceptionInterface | ClientExceptionInterface $exception) { echo $exception; exit(-1); } foreach ($response->orders as $order) { printf("Order ID: %d\n", $order->id); printf("First name: %s\n", $order->firstName); printf("Last name: %s\n", $order->lastName); printf("Patronymic: %s\n", $order->patronymic); printf("Phone #1: %s\n", $order->phone); printf("Phone #2: %s\n", $order->additionalPhone); printf("E-Mail: %s\n", $order->email); if ($order->customer instanceof \RetailCrm\Api\Model\Entity\CustomersCorporate\CustomerCorporate) { echo "Customer type: corporate\n"; } else { echo "Customer type: individual\n"; } foreach ($order->items as $item) { echo PHP_EOL; printf("Product name: %s\n", $item->productName); printf("Quantity: %d\n", $item->quantity); printf("Initial price: %f\n", $item->initialPrice); } echo PHP_EOL; printf("Discount: %f\n", $order->discountManualAmount); printf("Total: %f\n", $order->totalSumm); echo PHP_EOL; } ``` ### Response #### Success Response (200) - **orders** (array) - An array of order objects. - **pagination** (object) - Pagination details. #### Response Example (Response structure depends on the order data, see code for iteration details) ``` -------------------------------- ### Fetch a Customer by ID and Site Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/sending_a_request.md Retrieve a specific customer using their ID and site. Ensure to import necessary enums and request models. ```php use RetailCrm\Api\Enum\ByIdentifier; use RetailCrm\Api\Factory\SimpleClientFactory; use RetailCrm\Api\Model\Request\BySiteRequest; $client = SimpleClientFactory::createClient('https://test.retailcrm.pro', 'key'); $response = $client->customers->get(1, new BySiteRequest(ByIdentifier::ID, 'site')); echo $response->customer->email; ``` -------------------------------- ### List Orders with RetailCRM API Client (PHP) Source: https://github.com/retailcrm/api-client-php/blob/master/README.md Fetches a list of orders from RetailCRM. Includes basic error handling for API and client exceptions. Assumes the client is already initialized. ```php orders->list(); } catch (ApiExceptionInterface | ClientExceptionInterface $exception) { echo $exception; // Every ApiExceptionInterface and ClientExceptionInterface instance implements __toString() method. exit(-1); } foreach ($response->orders as $order) { printf("Order ID: %d\n", $order->id); printf("First name: %s\n", $order->firstName); printf("Last name: %s\n", $order->lastName); printf("Patronymic: %s\n", $order->patronymic); printf("Phone #1: %s\n", $order->phone); printf("Phone #2: %s\n", $order->additionalPhone); printf("E-Mail: %s\n", $order->email); if ($order->customer instanceof CustomerCorporate) { echo "Customer type: corporate\n"; } else { echo "Customer type: individual\n"; } foreach ($order->items as $item) { echo PHP_EOL; printf("Product name: %s\n", $item->productName); printf("Quantity: %d\n", $item->quantity); printf("Initial price: %f\n", $item->initialPrice); } echo PHP_EOL; printf("Discount: %f\n", $order->discountManualAmount); printf("Total: %f\n", $order->totalSumm); echo PHP_EOL; } ``` -------------------------------- ### Manual Code Generation Command Source: https://github.com/retailcrm/api-client-php/blob/master/doc/compilation_prompt.md This command can be used to manually run code generation once. Ensure 'retailcrm-client' is in your binary directory. ```sh composer compile --all ``` -------------------------------- ### Creating a Task for a User Source: https://github.com/retailcrm/api-client-php/blob/master/README.md Demonstrates how to create a task for a user identified by their email. ```APIDOC ## Creating a Task for a User ### Description Creates a new task in RetailCRM and assigns it to a user found by their email address. ### Method `POST` (Implicitly through client methods) ### Endpoint `/users` and `/tasks` (Implicitly through client methods) ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body **For User Search:** - **filter** (object) - Filter criteria for users. - **email** (string) - Required - The email address of the user to find. **For Task Creation:** - **task** (object) - Required - The task data object. - **performerId** (integer) - Required - The ID of the user who will perform the task. - **text** (string) - Required - The description of the task. - **site** (string) - Required - The site the task belongs to. ### Request Example ```php filter = new ApiUserFilter(); $usersRequest->filter->email = 'john.doe@example.com'; try { $usersResponse = $client->users->list($usersRequest); } catch (ApiExceptionInterface | ClientExceptionInterface $exception) { echo $exception; exit(-1); } if (0 === count($usersResponse->users)) { echo 'User is not found.'; exit(-1); } $tasksRequest = new TasksCreateRequest(); $tasksRequest->task = new Task(); $tasksRequest->task->performerId = $usersResponse->users[0]->id; $tasksRequest->task->text = 'Do something!'; $tasksRequest->site = 'site'; try { $tasksResponse = $client->tasks->create($tasksRequest); } catch (ApiExceptionInterface | ClientExceptionInterface $exception) { echo $exception; exit(-1); } echo 'Created task with ID: ' . $tasksResponse->id; ``` ### Response #### Success Response (200) - **id** (integer) - The ID of the newly created task. #### Response Example ```json { "id": 54321 } ``` ``` -------------------------------- ### Create a New Order with RetailCRM API Client (PHP) Source: https://github.com/retailcrm/api-client-php/blob/master/doc/usage/examples/create_order.md Use this snippet to create a new order. It includes setting up payment, delivery, items, customer information, and custom fields. Ensure all required fields are populated before sending the request. ```php type = 'bank-card'; $payment->status = 'paid'; $payment->amount = 1000; $payment->paidAt = new DateTime(); $deliveryAddress->index = '344001'; $deliveryAddress->countryIso = CountryCodeIso3166::RUSSIAN_FEDERATION; $deliveryAddress->region = 'Region'; $deliveryAddress->city = 'City'; $deliveryAddress->street = 'Street'; $deliveryAddress->building = '10'; $delivery->address = $deliveryAddress; $delivery->cost = 0; $delivery->netCost = 0; $offer->name = 'Offer №1445123'; $offer->displayName = 'Offer №1445123'; $offer->xmlId = 'tGunLo27jlPGmbA8BrHxY2'; $offer->article = '14451445-14451445'; $offer->unit = new Unit('796', 'Piece', 'pcs'); $item->offer = $offer; $item->priceType = new PriceType('base'); $item->quantity = 1; $item->purchasePrice = 60; $order->delivery = $delivery; $order->items = [$item]; $order->payments = [$payment]; $order->orderType = 'test'; $order->orderMethod = 'phone'; $order->countryIso = CountryCodeIso3166::RUSSIAN_FEDERATION; $order->firstName = 'Test'; $order->lastName = 'User'; $order->patronymic = 'Patronymic'; $order->phone = '89003005069'; $order->email = 'testuser12345678901@example.com'; $order->managerId = 28; $order->customer = SerializedRelationCustomer::withIdAndType( 4924, CustomerType::CUSTOMER ); $order->status = 'assembling'; $order->statusComment = 'Assembling order'; $order->weight = 1000; $order->shipmentStore = 'main12'; $order->shipmentDate = (new DateTime())->add(new DateInterval('P7D')); $order->shipped = false; $order->customFields = [ "galka" => false, "test_number" => 0, "otpravit_dozakaz" => false, ]; $request->order = $order; $request->site = 'moysklad'; try { $response = $client->orders->create($request); } catch (ApiExceptionInterface | ClientExceptionInterface $exception) { echo $exception; // Every ApiExceptionInterface instance should implement __toString() method. exit(-1); } printf( 'Created order id = %d with the following data: %s', $response->id, print_r($response->order, true) ); ```