Git Product home page Git Product logo

allegro-api's Introduction

PHP Allegro API

Allegro API client library, written with PHP.

Requirements

  • PHP >= 5.6 || PHP >= 7.0
  • HTTP client

Features

  • REST and SOAP WebApi
  • Sandbox support
  • Auto-complete
  • PSR compatible

Installation

Via Composer:

composer require ircykk/allegro-api

Library is build on top of HTTPlug, we need to install HTTP client.

composer require php-http/guzzle6-adapter "^1.1"

Developer Documentation

https://developer.allegro.pl/documentation/

Usage of client

Authentication with OAuth

<?php

// Composer autoload
require_once __DIR__.'/vendor/autoload.php';

$credentials = ...

$client = new \Ircykk\AllegroApi\Client($credentials);

// Redirect to allegro for authenticate and get back with code
if (!isset($_GET['code'])) {
    header('Location: '.$client->getAuthUrl());
} else {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);

    // Store access token...
}

We have $token->access_token for authenticate all our future requests.

See example.

Client credentials flow

In order to access to public available resources such as categories or offers use client credentials flow:

$token = $client->fetchAccessTokenWithClientCredentials();

Device flow

To use browserless device flow use getAuthUserCode() method to get user_code and verification uri:

$code = $client->getAuthUserCode();

and then after user authenticate device you can fetch acces_token:

$code = ...

$token = $client->fetchAccessTokenWithDeviceCode($code->device_code);

Making Requests

<?php

// Composer autoload
require_once __DIR__.'/vendor/autoload.php';

$credentials = ...
$token = ...

$client = new \Ircykk\AllegroApi\Client($credentials);
$client->authenticate($token);

$categories = $client->sale()->categories()->all();

Making SOAP Requests

$credentials = ...

// WebApi SOAP client
$soapClient = new \Ircykk\AllegroApi\WebapiClient($credentials);

$categories = $soapClient->webApi()->getCatsDataLimit(0, 10);

Sandbox

In order to use Sandbox environment just set Credentials property $sandbox to true.

$credentials = new \Ircykk\AllegroApi\Credentials(
    ...
    true // Sandbox
);

Cache usage

Use any PSR-6 compatible library to cache requests.

In this example we use Symfony Cache, to install just run:

$ composer require symfony/cache
$credentials = ...
$client = new Client($credentials);

$cache = new FilesystemAdapter();
$client->addCache($cache, ['default_ttl' => 3600]);

See example.

Logger

Use any PSR-3 logger library for example Monolog, to install just run:

$ composer require monolog/monolog
$credentials = ...
$client = new Client($credentials);

$logger = new Logger('api');
$logger->pushHandler(
    new StreamHandler(__DIR__.'/api.log', Logger::DEBUG)
);
$loggerPlugin = new LoggerPlugin($logger);
$client->addPlugin($loggerPlugin);

See example.

Customization

Thanks to HTTPlug library can be customized easily, for example to set language use HeaderDefaultsPlugin plugin:

...
$headerDefaultsPlugin = new HeaderDefaultsPlugin([
    'Accept-Language' => 'en-US'
]);
$client->addPlugin($headerDefaultsPlugin);

See full list of available HTTPlug plugins.

TO-DO

  • Tests
  • Documentation

Contributing

Feel free to contribute.

Credits

API client build on top of HTTPlug and inspired by KnpLabs GitHub client.

Soap types generated by wsdl2phpgenerator library.

allegro-api's People

Contributors

ircykk avatar patrykmakowski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

allegro-api's Issues

Zmiana ceny Kup Teraz przez Rest Api

Hej

Dzięki za świetna robotę. Nie mogę jednak poradzić sobie ze zmianą ceny KT poprzez Rest API.
Poniższy program nie działa:

$credentials = new\Ircykk\AllegroApi\Credentials(
    CLIENT_ID,
    CLIENT_SECRET,
    REDIRECT_URI
);

$client = new \Ircykk\AllegroApi\Client($credentials);
$client->authenticate($access_token));

$params = [
            "buyNowPrice" => [
                "amount" => "100",
                "currency" => "PLN"
            ]
        ];

$response = $client->sale()->commands()->changePrice("704xxxxx",$params);
print_r($response);

otrzymuję:

stdClass Object
(
    [errors] => Array
        (
            [0] => stdClass Object
                (
                    [code] => ConstraintViolationException.NotNull
                    [message] => may not be null
                    [details] => Invalid value: null, Annotation: @javax.validation.constraints.NotNull(message={javax.validation.constraints.NotNull.message}, groups=[], payload=[])
                    [path] => arg4.input
                    [userMessage] => may not be null
                )

        )
)

Może jakaś podpowiedź co robię źle?
Dzięki za pomoc.

 

Body do edycji aukcji

Na wstępie gratuluję bardzo fajnej biblioteki do obsługi allegro. Generalnie działa bardzo dobrze mam jednak problem z edycją istniejących aukcji.

Jaki format powinna posiadać zmienna przesyłana jako PUT w przypadku poniżej $response?

$makeupdate = $client->sale()->offers()->update('7713858513', $offer);

Kopię się z tym od wczoraj z dokumentacji wynika, że trzeba wysłać pełną treść zapytania pobranego jako GET. Z API wynika, że musi to być tablica. Kombinuję na różne sposoby np.
$offer = array('offer' => $updatee);

i cały czas odpowiedź

Receive response: "422 Unprocessable Entity 1.1" for request: "PUT https://api.allegro.pl/sale/offers/7713858513 1.1" {"request":"[object] (GuzzleHttp\Psr7\Request: {})","response":"[object] (GuzzleHttp\Psr7\Response: {})"} []

Np tutaj np zmiana kod ean

$response = $client->sale()->offers()->show('7713858513'); $response2 = json_decode(json_encode($response), True); $response2["ean"] = '4021457607945'; $updatee = json_encode($response2); $offer = array('offer' => $updatee); $makeupdate = $client->sale()->offers()->update('7713858513', $offer);
W przypadku wysłania takiego samego requestu jaki otrzymałem od allegro cały czas to samo :(.

Z góry dziękuję za odpowiedź.

Puli Factory is not available

Hello, thanks for your project. Today I installed the project according to the installation guide, but I met a problem when I tried to run my program. I always get the error

throw new PuliUnavailableException('Puli Factory is not available');
So could you please tell me how to fix the problem?
Thanks in advance.

AbstractRestBetaResource::post()

Warning: Declaration of Ircykk\AllegroApi\Rest\AbstractRestBetaResource::post($path, array $params = Array, array $requestHeaders = Array) should be compatible with
Ircykk\AllegroApi\Rest\AbstractRestResource::post($path, $data, array $requestHeaders = Array) in /home/rebel/admin/vendor/ircykk/allegro-api/src/Rest/AbstractRestBetaResource.php on line 60

GET sale/offer-events

Hej

Straciłem dzisiaj dobre kilka godzin i nie udało mi się dobić do zasobu jak w temacie za pomocą klasy.
Program wygląda mniej więcej tak:
$client = new \Ircykk\AllegroApi\Client($credentials);
$client->authenticate($dbase->getVar("access_token"));
$response = $client->get("/sale/offer-events");

W odpowiedzi dostaję:
stdClass Object
  | (
  | [errors] => Array
  | (
  | [0] => stdClass Object
  | (
  | [code] => NotAcceptableException
  | [message] => Not acceptable representation requested. Please check 'Accept' request header
  | [details] =>
  | [path] =>
  | [userMessage] => The request contains incorrect data. Contact the author of the application.
  | )
  |  
  | )
  |  
  | )

Próba dodania wcześniej:
$headerDefaultsPlugin = new \Http\Client\Common\Plugin\HeaderDefaultsPlugin([
"Accept-Charset" => "utf-8",
"Content-Type:" => "application/vnd.allegro.public.v1+json"
]);
$client->addPlugin($headerDefaultsPlugin);

i wielu innych kombinacji nagłówków nic nie dają.

Kiedy testuję wywołania na aplikacji Advanced REST Client i puszczam coś takiego:
GET /sale/offer-events HTTP/1.1
Accept-Charset: utf-8
Authorization: Bearer XXXXXXXXXXX
Content-Type: application/vnd.allegro.public.v1+json

wszystko działa bez najmniejszego problemu, działa nawet coś takiego:

GET /sale/offer-events HTTP/1.1
Authorization: Bearer XXXXXXXXXXX

czyli przekazanie samego tokena bez Content-Type i Charset.

Ja coś robię nie tak, czy gdzieś w klasie jest błąd?
Dzięki za zainteresowanie.

Timeout połączenia z REST

Czy da się jakoś ustawić timeout dla połączeń REST? Opiszę swój problem.
Mam skrypt, który pobiera przez get /offers/listing wszystkie aukcje z danej kategorii. W większości to działa, ale czasami się zdarza, że uruchomiony skrypt nie może z niewiadomych mi powodów połączyć się z Allegro i program się kończy po 60 sekundach zwracając błąd.
Owy skrypt uruchamiam na serwerze z innego skryptu nadrzędnego co pewien czas jako CGI.
Skrypt nadrzędny kończy się, podrzędny, czyli ten o którym mowa, ma problem z połączeniem i w ten sposób zostaje jako proces zombie na serwerze. Po kilku godzinach mam kilkadziesiąt takich procesów zombi i nie wiem jak sobie z tym poradzić.
Czy da się jakoś ustawić timeout dla połączeń REST, tak bay np. po 10 s. niemożności połączenia się dłużej nie próbował? SOAP od wielu lat działa bez problemu, ale z REST są jakieś przeboje, nie wiem jak sobie z tym poradzić. Dzięki za wskazówki.

cURL errors

Cześć,

bardzo często dostaję takie błędy:

  • Uncaught GuzzleHttp\Exception\ConnectException: cURL error 52: Empty reply from server
  • Uncaught GuzzleHttp\Exception\ConnectException: cURL error 28: Operation timed out after 150000 milliseconds with 0 out of 0 bytes received
  • Uncaught GuzzleHttp\Exception\ConnectException: cURL error 6: Could not resolve host: allegro.pl

można to jakoś obsłużyć?

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.