PHP code example of elastly / elastly-php

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

    

elastly / elastly-php example snippets




ig = Elastly\Configuration::getDefaultConfiguration()
    ->setAccessToken('elastly_live_...');

$prices = new Elastly\Api\PricesApi(null, $config);

$line = (new Elastly\Model\PricesRequestLinesInner())
    ->setProductSku('SKU-1042')
    ->setCustomerExternalId('CUST-88')
    ->setQuantity(25);

$request = (new Elastly\Model\PricesRequest())->setLines([$line]);

$response = $prices->getPrices(bin2hex(random_bytes(16)), $request);

foreach ($response->getLines() as $result) {
    if ($result->getOk()) {
        echo $result->getPriceCents() . ' ' . $result->getCurrency() . ': ' . $result->getReasonSummary() . PHP_EOL;
    } else {
        echo 'failed: ' . $result->getMessage() . PHP_EOL;
    }
}

use Elastly\Api\PricesApi;
use Elastly\Configuration;

$this->app->singleton(PricesApi::class, function () {
    $config = Configuration::getDefaultConfiguration()
        ->setAccessToken(config('services.elastly.key'));

    return new PricesApi(null, $config);
});

use Elastly\Configuration;
use Elastly\Model\PricesRequestLinesInner;
use Elastly\Serving\FailOpenPolicy;
use Elastly\Serving\FallbackPrice;
use Elastly\Serving\PricesNamespace;
use Elastly\Transport\ElastlyTransport;

$config = Configuration::getDefaultConfiguration()->setAccessToken('elastly_live_...');
$prices = new PricesNamespace(new ElastlyTransport($config));

$line = (new PricesRequestLinesInner())->setProductSku('SKU-1042')->setQuantity(25);

$result = $prices->get($line, FailOpenPolicy::staticFallback(
    fn ($line, $cause) => new FallbackPrice(priceCents: 1500),
));

if ($result->source() === 'elastly') {
    echo $result->priceCents . ' ' . $result->reasonSummary;
} elseif ($result->source() === 'fallback') {
    echo $result->priceCents . ' fallback because ' . $result->cause->reason;
} else {
    echo 'no price available: ' . $result->cause->reason;
}

use Elastly\Webhooks\SignatureVerificationError;
use Elastly\Webhooks\WebhooksNamespace;

$webhooks = new WebhooksNamespace();

try {
    $event = $webhooks->verify($rawBody, $signatureHeader, 'whsec_...');
} catch (SignatureVerificationError $error) {
    // reject with a 400
}

echo $event->event;
bash
composer