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 Issues

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 ,

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

Как получить список расходов? Пытаюсь вызвать метод 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()
);
}

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

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

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

Здравствуйте.
Столкнулись с проблемой на сервере разработки, что перестала выгружаться информация о платежах в ЦРМ.
Используем клиент версии 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. Результат не изменился и выглядит так же.

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

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

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

Customer->nickName

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

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

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

Спасибо!

Предлагаю создать метод 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

Некорректное удаление Расхода 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)

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

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

Импортировал вашу библиотеку в папку с проектом. Пытаюсь вызвать для тестов метод получения информации о заказе. Получаю ошибку:
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= в начало.

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.

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
)
*/

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

Здравствуйте.
Если открыть справку (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, но тогда пришлось отключить эти две проверки. Но сам метод сработал и файлы загрузились.

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

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

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

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

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

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

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

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

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)].

/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?

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

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

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

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

image

Проблема с фильтрацией товаров в запросе $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)."
";

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

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!

Тип 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] и, скорее всего, в апи клиенте по этой же причине

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".

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']))

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
)

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

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

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

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.