PHP code example of retjet / returns-api-php-client

1. Go to this page and download the library: Download retjet/returns-api-php-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

retjet / returns-api-php-client example snippets


use RetJetApi\Returns\Client;

$client = Client::create('YOUR_API_KEY');

$rma = $client->rmaRequests()->get(1234);

echo $rma->identifier;        // RMA-2024-001234
echo $rma->state?->label;     // in_progress
echo $rma->customer?->email;  // [email protected]

use RetJetApi\Returns\Client;

$client = Client::builder()
    ->withApiKey($key)                          // gger)                    // optional - otherwise no logging
    ->withRetry(maxRetries: 5)                  // optional - default: 3
    ->withTimeout(30)                           // optional - default: 10 s
    ->withUserAgent('my-app/2.0')               // optional
    ->build();

// Let the SDK build the client, and it will honour the timeout.
$client = Client::builder()->withApiKey($key)->withTimeout(30)->build();

// Bring your own client, and the timeout is yours to configure on it.
$client = Client::builder()
    ->withApiKey($key)
    ->withHttpClient(new GuzzleHttp\Client(['timeout' => 30]))
    ->build();

// One page. Use it when the page number comes from outside - a paginated UI, a job argument.
$page = $client->rmaRequests()->list(page: 2);

$page->totalItems();   // size of the whole result set
count($page);          // size of this page - not the same number
$page->hasNextPage();
$page->nextPage();     // the server's next-page URL, or null on the last page

foreach ($page as $rma) {
    // ...
}

// Every page, lazily. Nothing is fetched until the iteration starts, and page N+1 is only
// requested once page N has been consumed - so this is safe for result sets larger than memory.
foreach ($client->rmaRequests()->iterate() as $rma) {
    // ...
}

$followers = $client->rmaRequests()->followers(1234);          // one page
$timeline  = $client->rmaRequests()->timeline(1234);           // one page

foreach ($client->rmaRequests()->iterateFollowers(1234) as $follower) {
    // ...
}

foreach ($client->rmaRequests()->iterateTimeline(1234) as $entry) {
    // ...
}

$rma = $client->rmaRequests()->get(1234);

foreach ($rma->items ?? [] as $item) {
    echo $item->requestedQty;
    echo $item->orderedProduct?->name;
}

echo $rma->saleChannel?->label;

use RetJetApi\Returns\Request\CreateRmaRequest;
use RetJetApi\Returns\Request\CreateRmaRequestCustomer;
use RetJetApi\Returns\Request\CreateRmaRequestItem;
use RetJetApi\Returns\Request\UpdateProduct;

$rma = $client->rmaRequests()->create(new CreateRmaRequest(
    saleChannelId: 7,
    customer: new CreateRmaRequestCustomer(
        email: '[email protected]',
        firstName: 'John',
        lastName: 'Doe',
        country: 'PL',
        city: 'Warszawa',
        address1: 'Prosta 1',
    ),
    items: [new CreateRmaRequestItem(
        orderId: 'ORDER-123',
        productId: 'SKU-9',
        quantity: 1,
        reasonId: 3,
        conditionId: 4,
    )],
));

echo $rma->id;   // assigned by the server

$client->rmaRequests()->changeStatus($rma->id, 'in_progress');
$client->rmaRequests()->assignOwner($rma->id, 42);
$client->rmaRequests()->addMessage($rma->id, 'We have received your return.', public: true);
$client->rmaRequests()->setApprovedAmount($rma->id, 99.99, 'PLN');
$client->rmaRequests()->updateProduct($rma->id, 42, new UpdateProduct(confirmedQty: 1));

new CreateRmaRequest(
    saleChannelId: 7,
    customer: new CreateRmaRequestCustomer(/* ... */),
    items: [/* ... */],
    extra: ['fieldAddedByTheApiLater' => 'value'],
);

$client->rmaRequests()->changeStatus(1234, 'in_progress');

$updated = $client->rmaRequests()->get(1234);   // the only way to observe the new state

echo $updated->state?->label;

$client->rmaRequests()->bulkChangeStatus([1, 2, 3], 'closed');
// Returns void. If ID 2 did not exist, nothing here will say so.

$client->rmaRequests()->removeFollower(1234);   // unfollows the authenticated user

use RetJetApi\Returns\Exception\NotFoundException;
use RetJetApi\Returns\Exception\RetJetException;
use RetJetApi\Returns\Exception\ValidationException;

try {
    $client->rmaRequests()->create($payload);
} catch (ValidationException $e) {
    foreach ($e->violations() as $propertyPath => $messages) {
        // ['saleChannelId' => ['This value should not be blank.']]
    }
} catch (NotFoundException $e) {
    // ...
} catch (RetJetException $e) {
    // anything else the SDK can throw
}

$e->status();                // HTTP status, authoritative
$e->problem()->title();
$e->problem()->detail();
$e->problem()->type();
$e->problem()->instance();
$e->method();                 // "GET"
$e->path();                   // "/v1/rma-requests/1234/follower"
$e->getMessage();             // "HTTP 404: Not Found (GET /v1/rma-requests/1234/follower)"

use RetJetApi\Returns\Exception\AuthenticationException;

try {
    $client->rmaRequests()->list();
} catch (AuthenticationException $e) {
    $e->status();             // 401
    $e->problem()->detail();  // null - the server sent no problem document
}

use RetJetApi\Returns\Exception\ServerException;

try {
    $client->rmaRequests()->list();
} catch (ServerException $e) {
    if ($e->problem()->detail() === 'Unable to exchange token') {
        // The key is wrong, revoked, or the exchange service is down.
    }
}

use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

final class FakeHttpClient implements ClientInterface
{
    public function __construct(private readonly ResponseInterface $response)
    {
    }

    public function sendRequest(RequestInterface $request): ResponseInterface
    {
        return $this->response;
    }
}

$factory = new Nyholm\Psr7\Factory\Psr17Factory();
$response = $factory->createResponse(200)
    ->withHeader('Content-Type', 'application/ld+json')
    ->withBody($factory->createStream(json_encode(['member' => []])));

$client = Client::create('test-key', new FakeHttpClient($response));
$page = $client->saleChannels()->list();