GithubHelp home page GithubHelp logo

retailcrm / api-client-php Goto Github PK

View Code? Open in Web Editor NEW
60.0 16.0 56.0 2.05 MB

PHP client for RetailCRM API

Home Page: http://www.retailcrm.ru

License: MIT License

PHP 100.00%
retailcrm-api php packagist

api-client-php's Introduction

Build Status Coverage Latest stable PHP from Packagist

RetailCRM API PHP client

This is the PHP RetailCRM API client. This library allows using of the actual API version.
You can find more info in the documentation.

Table of contents

Requirements

  • PHP 7.3 and above
  • PHP's cURL support
  • PHP's JSON support
  • Any HTTP client compatible with PSR-18 (covered by the installation instructions).
  • Any HTTP factories implementation compatible with PSR-17 (covered by the installation instructions).
  • Any HTTP messages implementation compatible with PSR-7 (covered by the installation instructions).
  • Other dependencies listed in the composer.json (covered by the installation instructions)

Installation

Follow those steps to install the library:

  1. Download and install Composer package manager.
  2. Install the library from the Packagist by executing this command:
composer require retailcrm/api-client-php:"~6.0"

During the installation you will see this message. Press 'y' when you do:

civicrm/composer-compile-plugin contains a Composer plugin which is currently not in your allow-plugins config. See https://getcomposer.org/allow-plugins
Do you trust "civicrm/composer-compile-plugin" to execute code and wish to enable it now? (writes "allow-plugins" to composer.json) [y,n,d,?]

After that, you may see a message which will look like this:

The following packages have new compilation tasks:
 - retailcrm/api-client-php has 1 task

Allow these packages to compile? ([y]es, [a]lways, [n]o, [l]ist, [h]elp)

Choose [a]lways by typing a and pressing Enter.

Note: You should choose 'y' and [a]lways if your application is using CI/CD pipeline because the interactive terminal is not available in that environment which will result in failure during the dependencies installation.

If you chose something else during the installation and API client doesn't work properly - please follow these instructions to fix the problem.

  1. Include the autoloader if it's not included, or you didn't use Composer before.
require 'path/to/vendor/autoload.php';

Replace path/to/vendor/autoload.php with the correct path to Composer's autoload.php.

Note: API client uses php-http/curl-client and nyholm/psr7 as a PSR-18, PSR-17 and PSR-7 implementation. You can replace those implementations during installation by installing this library with the implementation of your choice, like this:

composer require symfony/http-client guzzlehttp/psr7 retailcrm/api-client-php:"~6.0"

More information about that can be found in the documentation.

Usage

Firstly, you should initialize the Client. The easiest way to do this is to use the SimpleClientFactory:

$client = \RetailCrm\Api\Factory\SimpleClientFactory::createClient('https://test.retailcrm.pro', 'apiKey');

The client is separated into several resource groups, all of which are accessible through the Client's public properties. You can call API methods from those groups like this:

$client->api->credentials();

For example, you can retrieve the customers list:

$client = \RetailCrm\Api\Factory\SimpleClientFactory::createClient('https://test.retailcrm.pro', 'apiKey');
$response = $client->customers->list();

Or the orders list:

$client = \RetailCrm\Api\Factory\SimpleClientFactory::createClient('https://test.retailcrm.pro', 'apiKey');
$response = $client->orders->list();

To handle errors you must use two types of exceptions:

  • RetailCrm\Api\Interfaces\ClientExceptionInterface for the network or other runtime errors.
  • RetailCrm\Api\Interfaces\ApiExceptionInterface for the errors from the API.

An example of error handling can be found in the next section of this document.

Each resource group is responsible for the corresponding API section. For example, costs resource group provide methods for costs manipulation and loyalty resource group allows interacting with loyalty programs, accounts, bonuses, etc.

Use annotations to determine which DTOs you need for sending the requests. If annotations are not provided by your IDE - you probably should configure them. It'll ease your work with this (and any other) library a lot.

More information about the usage including examples can be found in the documentation.

Examples

Listing orders:

<?php

use RetailCrm\Api\Interfaces\ClientExceptionInterface;
use RetailCrm\Api\Factory\SimpleClientFactory;
use RetailCrm\Api\Interfaces\ApiExceptionInterface;
use RetailCrm\Api\Model\Entity\CustomersCorporate\CustomerCorporate;

$client = SimpleClientFactory::createClient('https://test.retailcrm.pro', 'apiKey');

try {
    $response = $client->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;
}

Fetching a specific order by it's ID:

<?php

use RetailCrm\Api\Interfaces\ClientExceptionInterface;
use RetailCrm\Api\Interfaces\ApiExceptionInterface;
use RetailCrm\Api\Enum\ByIdentifier;
use RetailCrm\Api\Factory\SimpleClientFactory;
use RetailCrm\Api\Model\Request\BySiteRequest;

$client = SimpleClientFactory::createClient('https://test.retailcrm.pro', 'apiKey');

try {
    $response = $client->orders->get(1234, new BySiteRequest(ByIdentifier::ID, 'site'));
} catch (ApiExceptionInterface | ClientExceptionInterface $exception) {
    echo $exception; // Every ApiExceptionInterface instance should implement __toString() method.
    exit(-1);
}

echo 'Order: ' . print_r($response->order, true);

Creating a new customer:

<?php

use RetailCrm\Api\Interfaces\ClientExceptionInterface;
use RetailCrm\Api\Interfaces\ApiExceptionInterface;
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', 'apiKey');

$request = new CustomersCreateRequest();
$request->customer = new Customer();

$request->site = 'aliexpress';
$request->customer->email = '[email protected]';
$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;

Creating a task for the user with a specific email:

<?php

use RetailCrm\Api\Interfaces\ClientExceptionInterface;
use RetailCrm\Api\Interfaces\ApiExceptionInterface;
use RetailCrm\Api\Factory\SimpleClientFactory;
use RetailCrm\Api\Model\Entity\Tasks\Task;use RetailCrm\Api\Model\Filter\Users\ApiUserFilter;
use RetailCrm\Api\Model\Request\Tasks\TasksCreateRequest;
use RetailCrm\Api\Model\Request\Users\UsersRequest;

$client = SimpleClientFactory::createClient('https://test.retailcrm.pro', 'apiKey');

$usersRequest = new UsersRequest();
$usersRequest->filter = new ApiUserFilter();
$usersRequest->filter->email = '[email protected]';

try {
    $usersResponse = $client->users->list($usersRequest);
} catch (ApiExceptionInterface | ClientExceptionInterface $exception) {
    echo $exception; // Every ApiExceptionInterface instance should implement __toString() method.
    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; // Every ApiExceptionInterface instance should implement __toString() method.
    exit(-1);
}

echo 'Created task with ID: ' . $tasksResponse->id;

The error handling in the examples above is good enough for real production usage. You can safely assume that ApiExceptionInterface is an error from the API, and ClientExceptionInterface is a client error (e.g. network error or any runtime error, use HttpClientException to catch only PSR-18 client errors). However, you can implement more complex error handling if you want.

Also, both ApiExceptionInterface and ClientExceptionInterface implements __toString(). This means that you can just convert those exceptions to string and put the results into logs without any special treatment for the exception data.

More examples can be found in the documentation.

You can use a PSR-14 compatible event dispatcher to receive events from the client. See documentation for details.

Notes

This library uses HTTPlug abstractions. Visit official documentation to learn more about it.

api-client-php's People

Contributors

alexander-mart avatar andreymuriy avatar artem9-9 avatar azgalot avatar chazovs avatar chupocabra avatar curse89 avatar dendd1 avatar devalex86 avatar dmamontov avatar gulaandrij avatar gwinn avatar ilyavlasoff avatar iyzoer avatar kifril avatar linniksa avatar max-baranikov avatar moriony avatar muxx avatar neur0toxine avatar opheugene avatar oxy-coach avatar pomadchin avatar rencurs avatar ripulca avatar sergeykasyanov avatar soldierofheart avatar tikijian avatar uryvskiy-dima avatar vstaheev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

api-client-php's Issues

Uncaught Cannot deserialize body: Failed to JSON decode data. This is not supposed to happen

PHP Fatal error: Uncaught Cannot deserialize body: Failed to JSON decode data. This is not supposed to happen. (0)
#0 /data/projects/users_www/iosh/myProj/vendor/retailcrm/api-client-php/src/Handler/Response/UnmarshalResponseHandler.php(28): RetailCrm\Api\Handler\Response\AbstractResponseHandler->unmarshalBody()
#1 /data/projects/users_www/iosh/myProj/vendor/retailcrm/api-client-php/src/Handler/Response/AbstractResponseHandler.php(68): RetailCrm\Api\Handler\Response\UnmarshalResponseHandler->handleResponse()
#2 /data/projects/users_www/iosh/myProj/vendor/retailcrm/api-client-php/src/Handler/AbstractHandler.php(35): RetailCrm\Api\Handler\Response\AbstractResponseHandler->handle()
#3 /data/projects/users_www/iosh/myProj/vendor/retailcrm/api-client-php/src/Handler/Response/AbstractResponseHandler.php(84): RetailCrm\Api\Handler\AbstractHandler->handle()
#4 /data/projects/users_www/iosh/myProj/vendor/retailcrm/api-client-php/src/Handler/Response/FilesDownloadResponseHandler.php(30): RetailCrm\Api in /data/projects/users_www/iosh/myProj/vendor/retailcrm/api-client-php/src/Handler/Response/AbstractResponseHandler.php on line 99

filter[expired] не работает в положении 0

Не смотря на указанный фильтр expired=0, в получаемом списке заказов присутствуют просроченные. Однако, expired=1 работает.

$crm=new \RetailCrm\ApiClient($url,$apiKey);
$filter=array();
print_r($crm->ordersList($filter)->__get('pagination'));
/*
Array
(   
    [limit] => 20
    [totalCount] => 9961
    [currentPage] => 1
    [totalPageCount] => 499
)
*/
$filter['expired']=0;
print_r($crm->ordersList($filter)->__get('pagination'));
/*
Array
(   
    [limit] => 20
    [totalCount] => 9961
    [currentPage] => 1
    [totalPageCount] => 499
)
*/
$filter['expired']=1;
print_r($crm->ordersList($filter)->__get('pagination'));
/*
Array
(   
    [limit] => 20
    [totalCount] => 8583
    [currentPage] => 1
    [totalPageCount] => 430
)
*/

Фатальная ошибка при использовании библиотеки

Импортировал вашу библиотеку в папку с проектом. Пытаюсь вызвать для тестов метод получения информации о заказе. Получаю ошибку:
PHP Fatal error: Uncaught Error: Class 'RetailCrm\ApiClient' not found in public_html/test/test.php:2\nStack trace:\n#0 {main}\n thrown in public_html/test/test.php on line 2

Все файлы библиотеки лежат по пути public_html/test

Проблема с files upload

Добрый день, возникла проблема с загрузкой файла.

Версия библиотеки:
"retailcrm/api-client-php": "~6.0"

Код:

$fileData = $client->getStreamFactory()->createStream("TEST");
$response = $client->files->upload(new FilesUploadRequest($fileData));
$download = $client->files->download($response->file->id);

Ожидаю что $download->data->getContents() будет равен TEST,
но в реальности, метод возвращает file=TEST
так же и для бинарных файлов возвращает всегда file=...содержимое бинарника...

В CRM при попытке скачать файл тоже добавляется file= в начало.

Фильтр пользователей

Доброго дня! Вопрос ради интереса, почему в фильтре по пользователям нет возможности делать выборку по номеру телефона?

Спасибо за ответ!

/api/v5/custom-fields/dictionaries/create

This code from your library doesn't work:

    public function customDictionariesCreate($customDictionary)
    {
        if (!count($customDictionary) ||
            empty($customDictionary['code']) ||
            empty($customDictionary['elements'])
        ) {
            throw new \InvalidArgumentException(
                'Parameter `dictionary` must contain a data & fields `code` & `elemets` must be set'
            );
        }

        return $this->client->makeRequest(
            "/custom-fields/dictionaries/{$customDictionary['code']}/create",
            "POST",
            ['customDictionary' => json_encode($customDictionary)]
        );
    }

But this code is work:

    public function customDictionariesCreate($customDictionary)
    {
        if (!count($customDictionary) ||
            empty($customDictionary['code']) ||
            empty($customDictionary['elements'])
        ) {
            throw new \InvalidArgumentException(
                'Parameter `dictionary` must contain a data & fields `code` & `elemets` must be set'
            );
        }

        return $this->client->makeRequest(
            "/custom-fields/dictionaries/create",
            "POST",
            ['customDictionary' => json_encode($customDictionary)]
        );
    }

There is difference in first parameter of method makeRequest(). Is it error?

Wrong type of "success" param in response

Sometimes Response object has string values in bool parameters.

E.g. in good conditions when I try to get order list by URL like
https://demo.retailcrm.ru/api/v4/orders?apiKey=...
I see in JSON in response object success parameter with value true (type is bool):

{
...
    "success": true
...
}

But when something is wrong (just lost one symbol from account name)
https://dem.retailcrm.ru/api/v4/orders?apiKey=..
in JSON I see string value "false" of success parameter:

{
    "errorMsg": "Account does not exist.",
    "success": "false"
}

In bad way ApiResponse::getSuccess() works wrong.

Тип DateTime у поля birthday класса Customer

Добрый день,
Проверили, https://github.com/retailcrm/api-client-php/blob/master/src/Model/Entity/Customers/Customer.php#L310
Если все делать по правилам, т.е. день рождения указывать как 1937-07-05
(фактически нужно создать объект Customer и прописать birthday через new DateTime),
то апи клиент попытается передать дату в апи как "1937-07-05 00:00:00", что приведет к ответу апи: "Invalid datetime, expected format !Y-m-d."
В доке же указано https://docs.retailcrm.ru/Developers/API/APIVersions/APIv5#post--api-v5-customers-create DateTime у customer[birthday] и, скорее всего, в апи клиенте по этой же причине

New order method lose customer info

Hi. I wrote code that create customers before orders. So i know that ID.
When i try to send new order and fill customer property, that lose somewhere in request classes and come to crm empty, so crm think that this is new customer.

Using SerializedRelationCustomer class like in docs.

After many debugs im tryed to use default Customer class, and it`s work fine.

Oh and maybe it helps, i`m not use guzzle / psr7 cause it has problems with other my libraries ((, instead of this i use nyholm / psr7

Bug in customFields methods

There are customFieldsCreate(), customFieldsEdit and customFieldsGet() methods has buggy check:
if (empty($entity) || $entity != 'customer' || $entity != 'order')
They are always return true. It can be improve fore example by this code:
if (empty($entity) || !in_array($entity, ['customer', 'order']))

Некорректное удаление Расхода APIv5

В коде ошибка:
`

public function costsDeleteById($id) {
if (!empty($id)) { // мы никогда не удалим, так как параметр "не пустой"
throw new \InvalidArgumentException('Parameter id must contains a data');
}
/* @noinspection PhpUndefinedMethodInspection */
return $this->client->makeRequest(
sprintf('/costs/%s/delete', $id),
"POST"
);
}

`

public function costsDeleteById($id)

Order createdAt doesn't update via API

API v2.0

                        $orderData = [
                                'externalId' => trim($row['order_id']),
                                'createdAt' => date('Y-m-d H:i:s',trim($row['timestamp'])),
                        ];

                        try {
                                $crm->orderEdit($orderData);
                        }
                        catch (\IntaroCrm\Exception\CurlException $e) {
                                //$logger->addError('orderUpload: connection error');
                                die('orderUpload: connection error');
                        }
                        catch (\IntaroCrm\Exception\ApiException $e) {
                                //$logger->addError('orderUpload: ' . $e->getMessage());
                                die('orderUpload: ' . $e->getMessage());
                        }

Code run without errors, but I have "old" order date in IntaroCRM web interface and analytics. How can I fix order date?

account decoretto, $orderData:

Array
(
    [externalId] => 28568
    [createdAt] => 2011-04-22 09:07:36
)

Installation issue

Hello. I've tried to install api-client-php via "composer require retailcrm/api-client-php:"~6.0"" and got the error:
Problem 1
- retailcrm/api-client-php[v6.0.0, ..., v6.0.4] require liip/serializer ^2.0 -> satisfiable by liip/serializer[2.0.0, 2.0.1, 2.0.2, 2.0.3].
- liip/serializer[2.0.0, ..., 2.0.3] require php ^7.2 -> your php version (8.0.9) does not satisfy that requirement.
- Root composer.json requires retailcrm/api-client-php ~6.0 -> satisfiable by retailcrm/api-client-php[v6.0.0, ..., v6.0.4].
Same time if i try to use PHP v.7.2 i get issue with require"php": ">=7.3.0".

Проблема формата выгрузки платежа

Здравствуйте.
Столкнулись с проблемой на сервере разработки, что перестала выгружаться информация о платежах в ЦРМ.
Используем клиент версии 6.13.1 (но так же пробовали понизить до 6.12.5, результат такой же)

В логах ошибка выглядит так:

Errors in the entity format {"exception":"[object] (RetailCrm\\Api\\Exception\\Api\\ValidationException(code: 400): Errors in the entity format at /var/www/html/vendor/retailcrm/api-client-php/src/Factory/ApiExceptionFactory.php:62)
[stacktrace]
#0 /var/www/html/vendor/retailcrm/api-client-php/src/Handler/Response/ErrorResponseHandler.php(36): RetailCrm\\Api\\Factory\\ApiExceptionFactory->createException()
#1 /var/www/html/vendor/retailcrm/api-client-php/src/Handler/Response/AbstractResponseHandler.php(69): RetailCrm\\Api\\Handler\\Response\\ErrorResponseHandler->handleResponse()
#2 /var/www/html/vendor/retailcrm/api-client-php/src/Handler/AbstractHandler.php(35): RetailCrm\\Api\\Handler\\Response\\AbstractResponseHandler->handle()
#3 /var/www/html/vendor/retailcrm/api-client-php/src/Handler/Response/AbstractResponseHandler.php(85): RetailCrm\\Api\\Handler\\AbstractHandler->handle()
#4 /var/www/html/vendor/retailcrm/api-client-php/src/Handler/Response/AccountNotFoundHandler.php(56): RetailCrm\\Api\\Handler\\Response\\AbstractResponseHandler->next()
#5 /var/www/html/vendor/retailcrm/api-client-php/src/Handler/Response/AbstractResponseHandler.php(69): RetailCrm\\Api\\Handler\\Response\\AccountNotFoundHandler->handleResponse()
#6 /var/www/html/vendor/retailcrm/api-client-php/src/Component/Transformer/ResponseTransformer.php(63): RetailCrm\\Api\\Handler\\Response\\AbstractResponseHandler->handle()
#7 /var/www/html/vendor/retailcrm/api-client-php/src/ResourceGroup/AbstractApiResourceGroup.php(133): RetailCrm\\Api\\Component\\Transformer\\ResponseTransformer->createResponse()
#8 /var/www/html/vendor/retailcrm/api-client-php/src/ResourceGroup/Orders.php(675): RetailCrm\\Api\\ResourceGroup\\AbstractApiResourceGroup->sendRequest()

Сам объект, который должен выгрузиться выглядит так:

"RetailCrm\Api\Model\Entity\Orders\SerializedPayment":{
      "id":null,
      "status":"paid",
      "type":"stripe",
      "externalId":1891,
      "amount":"58.90",
      "paidAt":{
         "date":"2023-11-07 15:39:41.000000",
         "timezone_type":3,
         "timezone":"UTC"
      },
      "comment":null,
      "order":{
         "id":null,
         "externalId":"4261",
         "number":null,
         "applyRound":null
      }
   }

Для выгрузки используем класс RetailCrm\Api\Model\Request\Orders\OrdersPaymentsCreateRequest
и метод RetailCrm\Api\ResourceGroup\Orders::paymentsCreate

Пробовал убирать данные, оставляя только externalId и order.externalId. Результат не изменился и выглядит так же.

При этом всё то же самое (код, версия клиента, ключи и данные для выгрузки в ЦРМ) локально с моей машины работает корректно.

К сожалению, сообщение в ошибке не очень информативно.
Скажите пожалуйста, в чём проблема и как её исправить?

Civi\CompilePlugin\Util\ComposerPassthru

Install
PHP 8.0.9 windows x64
ComposerPassthru.php on line 62
PHP Fatal error: Uncaught TypeError: implode(): Argument #1 ($pieces) must be of type array, string given in

implode(' ', $this->options)
to
($this->options) ? implode(' ', $this->options) : null ,

Проблема с фильтрацией товаров в запросе $response = $client->store->products($request);

use RetailCrm\Api\Enum\NumericBoolean,
RetailCrm\Api\Factory\SimpleClientFactory,
RetailCrm\Api\Interfaces\ApiExceptionInterface,
RetailCrm\Api\Model\Filter\Store\ProductFilterType,
RetailCrm\Api\Model\Request\Store\ProductsRequest;

$client = SimpleClientFactory::createClient('сайт', 'ключ');

$request = new ProductsRequest();
$request->filter = new ProductFilterType();
$request->filter->active = NumericBoolean::TRUE;
$request->filter->externalId = '9460';
$request->page = 1;
$request->limit = 100;

try {
$response = $client->store->products($request);
} 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 'Products: ' . "

".print_r($response, true)."
";

Не работает фильтрация элементов. При любых значениях фильтра все равно выводится полный список товаров. В чем может быть причина?

Как работает загрузка файла к вам на сервер?

Здравствуйте.
Если открыть справку (http://help.retailcrm.ru/Developers/ApiVersion5#post--api-v5-files-upload) то там написано Для загрузки файла необходимо поместить его содержимое в тело запроса. Содержимое файла на php получается методом file_get_contents.
Но при просмотре функции апи-клиенте видим проверку входящей переменной как адреса файла: !file_exists($file) и filesize($file) == 0

public function fileUpload($file)
    {
        if (!file_exists($file)) {
            throw new \InvalidArgumentException("File doesn't exist");
        }

        if (filesize($file) == 0) {
            throw new \InvalidArgumentException("Empty file provided");
        }
        /* @noinspection PhpUndefinedMethodInspection */
        return $this->client->makeRequest(
            '/files/upload',
            "POST",
            ["file" => $file]
        );
    }

Так как всё таки будет правильно?
Первый раз я передавал именно путь к файлу и файлы открывались с црм. Но с недавнего времени там стали просто показывать этот путь к файлу. Пришел тогда к выводу что надо использовать file_get_contents, но тогда пришлось отключить эти две проверки. Но сам метод сработал и файлы загрузились.

New API v5 is not worked

Current version of library (v5.0.1) is not worked with API v5 methods (only API v4). Code for test - https://gist.github.com/XOlegator/2114ec1bd4d3cdbcfcf98f3b7e00073c
It give this result:

Версия = v4
RetailCrm\Response\ApiResponse Object
(
    [statusCode:protected] => 400
    [response:protected] => Array
        (
            [success] => 
            [errorMsg] => Order already exists.
        )

)
Версия = v5
RetailCrm\Response\ApiResponse Object
(
    [statusCode:protected] => 404
    [response:protected] => Array
        (
            [success] => 
            [errorMsg] => API method not found
        )

)

"API method not found" - this is for v5 only!

Пример из документации

Это вообще рабочая библиотека? Первый же пример из документации вызывает ошибку "Parameter 'site' is missing".

Не хватает метода добавления товара к заказу

В данный момент нет возможности добавить товар к закзазу.

Как я понял торговое предложение(offer), которое упоминается в документации это совсем иное, другая сущность нежели продукт
https://www.retailcrm.ru/docs/Developers/ApiVersion5#post--api-v5-orders-create.

Нельзя воспроизвести добавление товара через АПИ
image
Доступ к методу divide-discount, который добавляет, удаляет товары, закрыт

image

method not found

Hi, i got an error method getSitesAvailable not found, but few days ago all works normally, can you explain, may be you made some changes?
Thanks

Некорректно работает метод редактирования информации о файле.

Некорректно работает редактирование информации о файле.
fileEdit($file) он же /api/v5/files/{id}/edit

В ответе возвращается положительный результат, хотя файл не прикрепляется.

Информация подтверждена технической поддержкой RetailCRM.

Customer->nickName

order[customer][nickName] - This value should not be null

но у объекта кастомера нет соответствующего поля, чтобы передать название организации

Или не там смотрю?

Спасибо!

Нужна подсказка)

Есть более понятная инструкция для работы с библиотекой? Глобальная цель это оптимизировать скорость работы моей статистики(подгружаю много данных но делаю это через file_get_content и получается очень много запросов, а multi curl даже 2 запроса в секунду выдает ошибку типо много запросов делаю), работаю через file_get_content так как не смог разобраться с библиотекой(( В поддержку не пишу так как долго очень отвечают

php 8 support

Looks like dependencies don't support php8.

./composer.json has been updated
Running composer update symfony/http-client guzzlehttp/psr7 retailcrm/api-client-php
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
- retailcrm/api-client-php[dev-master, v6.0.0, ..., v6.0.2] require liip/serializer ^2.0 -> satisfiable by liip/serializer[2.0.0, ..., 2.x-dev (alias of dev-master)].
- liip/serializer 2.x-dev is an alias of liip/serializer dev-master and thus requires it to be installed too.
- liip/serializer[dev-master, 2.0.0, ..., 2.0.3] require php ^7.2 -> your php version (8.0.7) does not satisfy that requirement.
- retailcrm/api-client-php 6.x-dev is an alias of retailcrm/api-client-php dev-master and thus requires it to be installed too.
- Root composer.json requires retailcrm/api-client-php ~6.0 -> satisfiable by retailcrm/api-client-php[v6.0.0, v6.0.1, v6.0.2, 6.x-dev (alias of dev-master)].

Incompatibility with PHP8.1

PHP Parse error: syntax error, unexpected token "readonly" in .../vendor/retailcrm/api-client-php/src/Component/Serializer/Parser/JMSParser.php on line 333

Предлагаю создать метод getClient() в AbstractLoader

Как сейчас:
Есть класс AbstractLoader с закрытым свойством $client. Из этого, нельзя вызвать кастомный метод в АПИ. Например, сейчас не реализован метод /api/v5/store/products.
Сейчас приходится создавать свой класс, который расширяет класс \RetailCrm\Http\Client, чтобы вызвать вот такой код

class MyCustomClient extends \RetailCrm\Http\Client
.....................................
$client = new MyCustomClient();
$client->makeRequest('/store/products', 'GET', $params);

Как можно:
создать метод getClient() в \RetailCrm\Client\AbstractLoader, который возвращает $client
тогда можно сделать так

$response = $client->request->getClient()->makeRequest('/store/products', 'GET', $params);

Исчезнеть ошибка при вызове

$response = $client->request->client->makeRequest('/store/products', 'GET', $params);

Cannot access protected property RetailCrm\Client\ApiVersion5::$client

image

Каким образом получить список расходов?

Как получить список расходов? Пытаюсь вызвать метод costsList - ошибка с обработкой ответа.

require 'vendor/autoload.php';

$client = new \RetailCrm\ApiClient(
'domen',
'key',
\RetailCrm\ApiClient::V5
);

try {
$response = $client->request->costsList;
} catch (\RetailCrm\Exception\CurlException $e) {
echo "Connection error: " . $e->getMessage();
}

if ($response->isSuccessful()) {
echo $response;
} else {
echo sprintf(
"Error: [HTTP-code %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
);
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.