PHP code example of rewloy / rewloy-php

1. Go to this page and download the library: Download rewloy/rewloy-php 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/ */

    

rewloy / rewloy-php example snippets


use Rewloy\Client;

$rewloy = new Client(apiKey: (string) getenv('REWLOY_API_KEY'));

$kart = $rewloy->getPass(['params' => ['serial' => 'ABCD-EFGH-JKLM']]);
// "Şimdi ne yapılabilir?" için `actions[].ready` okunur; `rewardReady` yalnız damga ve puanda "ödül hazır"dır.
$odul = array_filter($kart['actions'], static fn (array $a): bool => in_array($a['action'], ['redeem-stamps', 'redeem-reward'], true) && $a['ready']);
echo $kart['type'], ' ', $kart['balance'] ?? '-', $odul !== [] ? ' (ödül hazır)' : '', "\n";

$giris = (new Client())->login(['body' => ['email' => $eposta, 'password' => $sifre]]);
$ekip = new Client(staffSession: $giris['token'], merchant: $isletmeId);
if ($giris['mfaRequired']) {
    $ekip->proveMfa(['body' => ['code' => '123456']]);
}

$rewloy = new Client(
    apiKey: (string) getenv('REWLOY_API_KEY'),
    baseUrl: 'https://rewloy-staging.ornek.com',   // sonuna /v1 yazsanız da olur
);

$kart = $rewloy->issuePass([
    'body' => ['programId' => $programId, 'email' => '[email protected]', 'firstName' => 'Ayşe', 'kvkkConsent' => true],
]);

$sonuc = $rewloy->passAction([
    'params' => ['serial' => $kart['serial']],
    'body' => ['action' => 'earn-stamps', 'locationId' => $subeId, 'count' => 1],
    'idempotencyKey' => 'kasa3-z0187-fis' . $fisNo,   // aşağıya bakın
]);
if ($sonuc['duplicate']) {
    echo "Bu işlem zaten yazılmış\n";
}

$kart = $rewloy->getPass(['params' => ['serial' => $seri]]);
// Kartın türüne özgü alanlar; `balance` yerine bunları okuyun.
if (isset($kart['stamps'])) {
    echo $kart['stamps']['count'], ' / ', $kart['stamps']['max'], " damga\n";
}
if (isset($kart['points'])) {
    echo $kart['points'], " puan\n";
}
if (isset($kart['money'])) {
    echo $kart['money']['amountMinor'] / 100, ' ', $kart['money']['currency'], "\n";
}
echo $kart['programName'], ' ', $kart['customer']['name'] ?? '', "\n";   // customer: yalnız customers.read yetkisiyle

// Fiş numarası anahtar olamaz: kasa + Z no + fiş no, ya da satışla saklanan bir UUID.
$anahtar = 'kasa3-z0187-fis' . $fisNo;
$satis = $rewloy->recordSale([
    'params' => ['serial' => $seri],
    'body' => [
        'locationId' => $subeId,
        'amountMinor' => 4550,            // 45,50: kartın para biriminde ($kart['currency']), kuruş
        'currency' => $kart['currency'],  // isteğe bağlı güvence: uyuşmazsa 422 CURRENCY_MISMATCH
        'reference' => 'fis-' . $fisNo,   // fiş numarası buraya yazılır
    ],
    'idempotencyKey' => $anahtar,
]);
if ($satis['applied'] === 'none') {
    echo 'Yazılan bir şey yok: ', $satis['reason'] ?? '', "\n";
} else {
    echo $satis['credited'], ' ', $satis['applied'], ' yazıldı, bakiye ', $satis['balance'], "\n";
}
// Fişi çizmek için ayrıca okumanız gerekmez: yazımdan sonraki kart `$satis['card']`'dadır (yetki yoksa null).
foreach ($satis['card']['actions'] ?? [] as $a) {
    if (in_array($a['action'], ['redeem-stamps', 'redeem-reward'], true) && $a['ready']) {
        echo "Ödül hazır\n";
    }
}

$geri = $rewloy->reverseSale([
    'params' => ['serial' => $seri],
    'body' => ['saleKey' => $anahtar, 'locationId' => $subeId],
]);
echo $geri['reversed'], ' ', $geri['applied'], ' geri alındı, bakiye ', $geri['balance'], "\n";

$rewloy->recordSale([
    'params' => ['serial' => $seri],
    'body' => ['locationId' => $subeId, 'amountMinor' => 4550, 'reference' => 'fis-' . $fisNo, 'occurredAt' => '2026-10-05T14:32:10+03:00'],
    'idempotencyKey' => $anahtar,
]);

$rewloy->passAction([
    'params' => ['serial' => $seri],
    'body' => ['action' => 'spend', 'locationId' => $subeId, 'amountMinor' => 2500],
    'idempotencyKey' => 'kasa3-z0187-iptal' . $fisNo,
]);
$iptal = $rewloy->reverseAction([
    'params' => ['serial' => $seri],
    'body' => ['actionKey' => 'kasa3-z0187-iptal' . $fisNo, 'locationId' => $subeId],   // ya da ['reference' => 'fis-' . $fisNo]
]);
echo $iptal['undone'], ' ', $iptal['restored'], ' geri verildi, bakiye ', $iptal['balance'], "\n";

foreach ($rewloy->paginate('listPassOperations', ['params' => ['serial' => $seri]]) as $islem) {
    if (!$islem['reversible']) {
        continue;
    }
    if ($islem['undoWith'] === 'sale/reverse') {
        $rewloy->reverseSale(['params' => ['serial' => $seri], 'body' => ['saleKey' => $islem['saleKey']]]);
    } else {
        $rewloy->reverseAction(['params' => ['serial' => $seri], 'body' => ['actionKey' => $islem['actionKey']]]);
    }
}

$satirlar = [
    ['lineId' => 'l1', 'name' => 'Latte', 'category' => ['Kahve', 'Sıcak'], 'quantity' => 2, 'unitPriceMinor' => 9000, 'totalMinor' => 18000],
    ['lineId' => 'l2', 'name' => 'Su', 'category' => 'Su', 'quantity' => 1, 'unitPriceMinor' => 2000, 'totalMinor' => 2000],
];

// Yazmadan dene: kartı ve defteri değiştirmez, Idempotency-Key istemez.
$onizleme = $rewloy->previewSale(['params' => ['serial' => $seri], 'body' => ['amountMinor' => 20000, 'lines' => $satirlar]]);
// Kart olmadan da sorulabilir (bir taslak kural kümesiyle): previewEarn.
$rewloy->previewEarn(['params' => ['id' => $programId], 'body' => ['amountMinor' => 20000, 'lines' => $satirlar]]);

$satis = $rewloy->recordSale([
    'params' => ['serial' => $seri],
    'body' => ['locationId' => $subeId, 'amountMinor' => 20000, 'lines' => $satirlar],
    'idempotencyKey' => $anahtar,
]);
foreach ($satis['earn']['lines'] ?? [] as $satir) {
    echo $satir['lineId'], ': ', $satir['status'], ' ', $satir['earned'], "\n";
}

// Tek bir satırın iadesi: satış bu satırsız yeniden yargılanır, yalnız fark geri alınır.
$iade = $rewloy->reverseSale([
    'params' => ['serial' => $seri],
    'body' => ['saleKey' => $anahtar, 'lines' => [['lineId' => 'l1', 'quantity' => 1]]],
    'idempotencyKey' => $anahtar . '-iade1',
]);
echo $iade['balance'], ' ', json_encode($iade['linesLeft'] ?? []), "\n";

$sube = $rewloy->getLocation(['params' => ['id' => $subeId]]);
$sayfa = $rewloy->publicBranch(['params' => ['code' => $sube['qr']['code']]]);
echo $sayfa['branch']['state'], ' ', count($sayfa['items']), " kart\n";

file_put_contents('sube-qr.png', $rewloy->locationQrPng(['params' => ['id' => $subeId], 'query' => ['size' => 1024]]));
file_put_contents('afis-a4.pdf', $rewloy->locationQrSheetPdf(['params' => ['id' => $subeId], 'query' => ['form' => 'a4']]));

foreach ($rewloy->paginate('listCustomers', ['query' => ['consent' => 'yes', 'limit' => 200]]) as $musteri) {
    echo $musteri['displayName'], ': ', $musteri['passCount'], " kart\n";
}

['data' => $musteriler, 'meta' => $meta] = $rewloy->listCustomers(['query' => ['page' => 2]]);

foreach ($rewloy->liveFeed() as $olay) {
    if ($olay->event === 'event') {
        $hareket = $olay->json();   // at, kind, location, program, delta, unit, name, currency
        echo $hareket['kind'], ' ', $hareket['location'], "\n";
    }
}

$yeni = $rewloy->createWebhook([
    'body' => ['url' => 'https://ornek.com/rewloy/webhook', 'events' => ['pass.activity', 'pass.voided']],
]);
$sir = $yeni['secret'];
$rewloy->testWebhook(['params' => ['id' => $yeni['webhook']['id']]]);   // webhook.test olayı gönderir

$r = $rewloy->rotateWebhookSecret(['params' => ['id' => $webhookId]]);
// yeni sırrı alıcınıza ekleyin, 24 saat sonra eskisini bırakın
$olay = Rewloy\Webhook::verify($hamGovde, $imzaBasligi, [$r['secret'], $eskiSir]);

use Rewloy\Exception\WebhookSignatureException;
use Rewloy\Webhook;

$govde = (string) file_get_contents('php://input');
try {
    $olay = Webhook::verify($govde, $_SERVER['HTTP_REWLOY_SIGNATURE'] ?? null, (string) getenv('REWLOY_WEBHOOK_SECRET'));
} catch (WebhookSignatureException) {
    http_response_code(400);
    exit;
}
// Rewloy-Delivery bir teslimin her denemesinde aynıdır: işlediyseniz atlayın.
if (dahaOnceIslendi($_SERVER['HTTP_REWLOY_DELIVERY'] ?? '')) {
    exit;
}
if ($olay['type'] === 'pass.activity') {
    $veri = $olay['data'];   // kind, card, program_id, location_id, customer_id, unit, delta…
}

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
use Rewloy\Exception\WebhookSignatureException;
use Rewloy\Webhook;

Route::post('/rewloy/webhook', function (Request $request) {
    try {
        $olay = Webhook::verify(
            $request->getContent(),
            $request->headers->get('Rewloy-Signature'),
            config('services.rewloy.webhook_secret'),
        );
    } catch (WebhookSignatureException) {
        return response()->noContent(400);
    }
    // Aynı teslim yeniden gelirse atlayın.
    if (! Cache::add('rewloy:' . $request->headers->get('Rewloy-Delivery'), true, now()->addDays(3))) {
        return response()->noContent();
    }
    // … $olay['type'], $olay['data']
    return response()->noContent();
});

use Rewloy\Exception\WebhookSignatureException;
use Rewloy\Webhook;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class RewloyWebhookController
{
    public function __construct(
        #[Autowire(env: 'REWLOY_WEBHOOK_SECRET')] private string $secret,
    ) {
    }

    #[Route('/rewloy/webhook', methods: ['POST'])]
    public function __invoke(Request $request): Response
    {
        try {
            $olay = Webhook::verify($request->getContent(), $request->headers->get('Rewloy-Signature'), $this->secret);
        } catch (WebhookSignatureException) {
            return new Response(status: 400);
        }
        // … $request->headers->get('Rewloy-Delivery') ile tekrarları ayıklayın.
        return new Response(status: 200);
    }
}

foreach ($rewloy->listWebhooks() as $w) {
    if ($w['pausedUntil'] !== null) echo "{$w['url']}: {$w['pausedUntil']} anına kadar bekletiliyor\n";
    if ($w['resumableUntil'] !== null) echo "{$w['url']}: {$w['resumableUntil']} öncesinde açın, kaldığı yerden sürer\n";
}

use Rewloy\Exception\RateLimitException;
use Rewloy\Exception\RewloyException;
use Rewloy\Generated\ErrorCode;

try {
    $rewloy->passAction([
        'params' => ['serial' => $seri],
        'body' => ['action' => 'spend', 'locationId' => $subeId, 'amountMinor' => 5000],
        'idempotencyKey' => 'kasa3-z0187-fis' . $fisNo,
    ]);
} catch (RateLimitException $e) {
    echo $e->retryAfter, " saniye sonra yeniden deneyin\n";
} catch (RewloyException $e) {
    if ($e->errorCode !== ErrorCode::INSUFFICIENT_BALANCE) {
        throw $e;
    }
    echo $e->detail, "\n";
}

$yanit = $rewloy->request('sendCampaign', [
    'body' => ['body' => 'Bu hafta kahveler 2 damga!'],
    'idempotencyKey' => 'kampanya-2026-10-03',
]);
$yanit->status;      // 201
$yanit->replayed;    // true: aynı anahtarın ilk yanıtı yeniden döndü (Idempotent-Replayed)
$yanit->requestId;   // x-request-id
$yanit->rateLimit(); // RateLimit-* başlıkları: limit, remaining, reset (yoksa null)
$yanit->mode;        // Rewloy-Mode
$yanit->data;        // kampanya

$rewloy = new Client(apiKey: (string) getenv('REWLOY_TEST_KEY'));   // rwk_test_…
$yanit = $rewloy->request('getPass', ['params' => ['serial' => $seri]]);
$yanit->mode;   // 'test'

use Rewloy\Http\CurlTransport;

$rewloy = new Client(
    apiKey: (string) getenv('REWLOY_API_KEY'),
    transport: new CurlTransport([CURLOPT_PROXY => 'http://vekil:3128', CURLOPT_CAINFO => '/etc/ssl/ca.pem']),
);

use Rewloy\Client;

$rewloy = new Client(apiKey: (string) getenv('REWLOY_API_KEY'));   // or staffSession: + merchant:, or holderSession:

$card = $rewloy->issuePass(['body' => ['programId' => $programId, 'email' => $email, 'kvkkConsent' => true]]);
$sale = $rewloy->recordSale([
    'params' => ['serial' => $card['serial']],
    'body' => ['locationId' => $locationId, 'amountMinor' => 4550, 'reference' => 'receipt-' . $receiptNo],  // amount in the card's currency, minor units
    'idempotencyKey' => 'till3-z0187-r' . $receiptNo,
]);

// A gift-card spend rung up by mistake? Void it by the key it was sent with:
$rewloy->passAction([
    'params' => ['serial' => $card['serial']],
    'body' => ['action' => 'spend', 'locationId' => $locationId, 'amountMinor' => 2500],
    'idempotencyKey' => 'till3-z0187-s' . $receiptNo,
]);
$voided = $rewloy->reverseAction([
    'params' => ['serial' => $card['serial']],
    'body' => ['actionKey' => 'till3-z0187-s' . $receiptNo],
]);
echo $voided['undone'], ' ', $voided['restored'], ' ', $voided['balance'], "\n";   // spend 2500 and the balance again

$event = Rewloy\Webhook::verify($rawBody, $signatureHeader, $secret);

  $lines = [
      ['lineId' => 'l1', 'name' => 'Latte', 'category' => ['Coffee', 'Hot'], 'quantity' => 2, 'unitPriceMinor' => 9000, 'totalMinor' => 18000],
      ['lineId' => 'l2', 'name' => 'Water', 'category' => 'Water', 'quantity' => 1, 'unitPriceMinor' => 2000, 'totalMinor' => 2000],
  ];
  $try = $rewloy->previewSale(['params' => ['serial' => $serial], 'body' => ['amountMinor' => 20000, 'lines' => $lines]]);
  $sale = $rewloy->recordSale([
      'params' => ['serial' => $serial],
      'body' => ['locationId' => $locationId, 'amountMinor' => 20000, 'lines' => $lines],
      'idempotencyKey' => $key,
  ]);
  foreach ($sale['earn']['lines'] ?? [] as $line) {
      echo $line['lineId'], ': ', $line['status'], ' ', $line['earned'], "\n";
  }
  // One line comes back: the sale is judged again without it and only the difference is taken back.
  $refund = $rewloy->reverseSale([
      'params' => ['serial' => $serial],
      'body' => ['saleKey' => $key, 'lines' => [['lineId' => 'l1', 'quantity' => 1]]],
      'idempotencyKey' => $key . '-refund1',
  ]);