PHP code example of pzelant / expert-sender-api

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

    

pzelant / expert-sender-api example snippets


// ...

use GuzzleHttp\Client;
use Pzelant\ExpertSenderApi\RequestSender;
use Pzelant\ExpertSenderApi\ExpertSenderApi;
use Pzelant\ExpertSenderApi\Model\SubscribersRequest\SubscriberInfo;
use Pzelant\ExpertSenderApi\Model\SubscribersRequest\Options;
use Pzelant\ExpertSenderApi\Model\SubscribersPostRequest\Identifier;
use Pzelant\ExpertSenderApi\Enum\SubscribersPostRequest\Mode;

// ...

$httpClient = new Client(['base_uri' => 'https://api.esv2.com/']);
$requestSender = new RequestSender($httpClient, 'api-key');
$api = new ExpertSenderApi($requestSender);

$email = '[email protected]';
$listId = 25;
$subscriberData = new SubscriberInfo(Identifier::createEmail($email), $listId);
$subscriberInfo->setFirstName('John');
$subscriberInfo->setLastName('Doe');
$subscriberInfo->setVendor('vendor');
$subscriberInfo->setTrackingCode('tracking code');
// another sets

$addResult = $api->subscribers()->addOrEdit([$subscriberData]);
if ($addResult->isOk()) {
    // ... make some stuff
} else {
    $errorMessages = $addResult->getErrorMessages();
    $errorCode = $addResult->getErrorCode();
}

// ...

use GuzzleHttp\Client;
use Pzelant\ExpertSenderApi\RequestSender;
use Pzelant\ExpertSenderApi\ExpertSenderApi;

// ...

// api endpoint always the same
$apiEndpoint = 'https://api.esv2.com/';

// http client must implements Guzzle's ClientInterface
$httpClient = new Client(['base_uri' => $apiEndpoint]);

// request sender object must implements RequestSenderInterface
$requestSender = new RequestSender($httpClient, 'api-key');

// now we have api object and can access to all methods of api
$api = new ExpertSenderApi($requestSender);

$response = $api->getServerTime();
if ($response->isOk()) {
    $dateTime = $response->getServerTime();
    echo $dateTime->format('Y-m-d H:i:s');
} else {
    // handle errors
}

// ...

use Pzelant\ExpertSenderApi\Model\TransactionalPostRequest\Receiver;
use Pzelant\ExpertSenderApi\Model\TransactionalPostRequest\Snippet;
use Pzelant\ExpertSenderApi\Model\TransactionalPostRequest\Attachment;

// ...

// message id is  Receiver::createById(862547);

// snippets are optional
$snippets = [];
$snippets[] = new Snippet('name1', 'value1');
$snippets[] = new Snippet('name2', 'value2');

// attachments are optional
$attachments = [];
$attachments[] = new Attachment('filename.jpeg', base64_encode('content'), 'image/jpeg');

// should response has guid of sent message
$returnGuid = true;

$response = $api->messages()->sendTransactionalMessage($messageId, $receiverById, $snippets, $attachments, $returnGuid);

if ($response->isOk()) {
    // guid available, only if returnGuid=true in request
    $guid = $response->getGuid();
} else {
    // handle errors
}

// ...

use Pzelant\ExpertSenderApi\Model\TransactionalPostRequest\Receiver;
use Pzelant\ExpertSenderApi\Model\TransactionalPostRequest\Snippet;
use Pzelant\ExpertSenderApi\Model\TransactionalPostRequest\Attachment;

// ...

// message id is  Receiver::createById(862547);

// snippets are optional
$snippets = [];
$snippets[] = new Snippet('name1', 'value1');
$snippets[] = new Snippet('name2', 'value2');

// attachments are optional
$attachments = [];
$attachments[] = new Attachment('filename.jpeg', base64_encode('content'), 'image/jpeg');

// should response has guid of sent message
$returnGuid = true;

$response = $api->messages()->sendSystemTransactionalMessage($messageId, $receiverById, $snippets, $attachments, $returnGuid);

if ($response->isOk()) {
    // guid available, only if returnGuid=true in request
    $guid = $response->getGuid();
} else {
    // handle errors
}

// ...

use Pzelant\ExpertSenderApi\Model\TriggersPostRequest\Receiver;

// ...

$triggerMessageId = 25;
$response = $api->messages()->sendTriggerMessage(
    $triggerMessageId,
    [
        Receiver::createFromEmail('[email protected]'),
        Receiver::createFromId(384636),
    ]        
);

if ($response->isOk()) {
    // do some stuff
} else {
    // handle errors
}

$subscriberEmail = '[email protected]';

// get short info about subscriber
$shortInfoResponse = $api->subscribers()->getShort($subscriberEmail);

// get long info about subscriber
$longInfoResponse = $api->subscribers()->getLong($subscriberEmail);

// get full info about subscriber
$fullInfoResponse = $api->subscribers()->getFull($subscriberEmail);

// get events history
$eventsHistoryResponse = $api->subscribers()->getEventsHistory($subscriberEmail);

// ...

use Pzelant\ExpertSenderApi\Model\SubscribersPostRequest\Options;
use Pzelant\ExpertSenderApi\Model\SubscribersPostRequest\Identifier;
use Pzelant\ExpertSenderApi\Enum\SubscribersPostRequest\Mode;

// ...

$listId = 25;

// to add new subscriber you can use one of identifiers email or phone (but not others, read documentation 
// for more information). You can use phone identifier, if sms channel is turned on, otherwise api 
// return 400 response.
$emailIdentifier = Identifier::createEmail('[email protected]');
$phoneIdentifier = Identifier::createPhone('89159109933');

// if you want to edit subscriber you can use more identifiers
$emailMd5Indentifier = Identifier::createEmailMd5('md5');
$customSubscriberIdentifier = Identifier::createCustomSubscriberId('cuscom-subscriber-id');
$idIdentifier = Identifier::createId(100);

$identifierToUse = $emailIdentifier;
$subscriberData = new SubscriberInfo($identifierToUse, $listId);
$subscriberData->setFirsname('firstname');
// another sets...

// if you want to get additonal data on response, or verbose errors, you can create object 
// with type Options. It's optional
$returnAdditionalDataOnResponse = true;
$useVerboseErrors = true;
$options = new Options($returnAdditionalDataOnResponse, $useVerboseErrors);

// if you want use another adding mode, create it. It's optional too and by default "AddAndUpdate" 
$mode = Mode::ADD_AND_UPDATE();

// you can add more than one subscriber to request
$addOrEditResponse = $api->subscribers()->addOrEdit([$subscriberData], $options, $mode);

if ($addOrEditResponse->isOk()) {
    // do something if everything is ok
} else {
    // handle errors
}

    $identifier = Identifier::createId(45603);
    $subscriberData = new SubscriberData($identifier, $listId);
    $subscriberData->setEmail('[email protected]');
    $api->subscribers()->addOrEdit([$subscriberData]); 
    

    $identifier = Identifier::createEmailMd5('md5');
    $subscriberData = new SubscriberData($identifier, $listId);
    $subscriberData->setPhone('9153452412');
    $api->subscribers()->addOrEdit([$subscriberData]); 
    

    $identifier = Identifier::createId(230584);
    $subscriberData = new SubscriberData($identifier, $listId);
    $subscriberData->setPhone('9153452412');
    $subscriberData->setEmail('[email protected]');
    $api->subscribers()->addOrEdit([$subscriberData]); 
    

$listId = 25;
$subscriberId = 5839274;
$subscriberEmail = '[email protected]';

// delete by subscriber's ID from list
$api->subscribers()->deleteById($subscriberId, $listId);

// delete by subscriber's email from every list
$api->subscribers()->deleteByEmail($subscriberEmail);

// ...

use Pzelant\ExpertSenderApi\Enum\RemovedSubscribersGetRequest\RemoveType;
use Pzelant\ExpertSenderApi\Enum\RemovedSubscribersGetRequest\Option;

// ...

// you can choose list ids
$listIds = [1, 2, 3];

// and/or you can choose remove types (reasons)
$removeTypes = [RemoveType::OPT_OUT_LINK(), RemoveType::USER_UNKNOWN()];

// and/or start date
$startDate = new \DateTime('2015-01-01');

// and/or end date
$endDate = new \DateTime('2016-01-01');

// and/or option. If specified, additional subscriber information will be returned
$option = Option::CUSTOMS();

$response = $api->subscribers()->getRemovedSubscribers($listIds, $removeTypes, $startDate, $endDate, $option);

foreach ($response->getRemovedSubscribers() as $removedSubscriber) {
    $email = $removedSubscriber->getEmail();
    // subscriber data present, only if Customs option specified
    $subscriberData = $removedSubscriber->getSubscriberData();
    $id = $subscriberData->getId();
    $properties = $subscriberData->getProperties();
}

// every parameter is optional
$listIds = [1,2,3];
$startDate = new \DateTime('2017-01-01');
$endDate = new \DateTime('2017-02-02');
$response = $api->subscribers()->getSnoozedSubscribers($listIds, $startDate, $endDate);
if ($response->isOk()) {
    foreach ($response->getSnoozedSubscribers() as $snoozedSubscriber) {
        echo $snoozedSubscriber->getEmail();
        echo $snoozedSubscriber->getListId();
        echo $snoozedSubscriber->getSnoozedUntil(); 
    }
} else {
    // handle errors
}

// Unique subscriber identifier
$subscriberId = 12;
// Number of weeks the subscription will be snoozed for
$snoozeWeeks = 20;
// List ID
$listId = 23;

// Snooze subscriber with id #12 for 20 weeks in List #23
$snoozedByIdResponse = $api->subscribers()->snoozeSubscriberById($subscriberId, $snoozeWeeks, $listId);
if ($snoozedByIdResponse->isOk()) {
    // ok
} else {
    // handle errors
}

// subscriber's email
$subscriberEmail = '[email protected]';
// Number of weeks the subscription will be snoozed for
$snoozeWeeks = 10;

// Snooze subscriber with email '[email protected]' for 20 weeks in all lists
$snoozedByEmailResponse = $api->subscribers()->snoozeSubscriberByEmail($subscriberEmail, $snoozeWeeks);
if ($snoozedByEmailResponse->isOk()) {
    // ok
} else {
    // handle errors
}

// ...
$returnGuidInResponse = true;
$returnTitleInResponse = true;
$subscriptions = $api->subscribers()->getSubscriberActivity()->getSubscriptions(new \DateTime('2017-02-02'))
    ->getSubscriptions();

$confirmations = $api->subscribers()->getSubscriberActivity()->getConfirmations(new \DateTime('2017-02-02'))
    ->getConfirmations();

$sends = $api->subscribers()->getSubscriberActivity()->getSends(
    new \DateTime('2017-06-24'), 
    ReturnColumnsSet::STANDARD(),
    $returnGuidInResponse
)->getSends();

$opens = $api->subscribers()->getSubscriberActivity()->getOpens(
    new \DateTime('2017-06-24'), 
    ReturnColumnsSet::STANDARD(),
    $returnGuidInResponse
)->getOpens();

$clicks = $api->subscribers()->getSubscriberActivity()->getClicks(
    new \DateTime('2017-06-24'), 
    ReturnColumnsSet::STANDARD(),
    $returnTitleInResponse,
    $returnGuidInResponse
)->getClicks();

$complaints = $api->subscribers()->getSubscriberActivity()->getComplaints(
    new \DateTime('2017-06-24'), 
    ReturnColumnsSet::STANDARD(),
    $returnGuidInResponse
)->getComplaints();

$removals = $api->subscribers()->getSubscriberActivity()->getRemovals(
    new \DateTime('2017-06-24'), 
    ReturnColumnsSet::STANDARD(),
    $returnGuidInResponse
)->getRemovals();

$bounces = $api->subscribers()->getSubscriberActivity()->getBounces(
    new \DateTime('2017-06-24'), 
    ReturnColumnsSet::STANDARD(),
    $returnGuidInResponse
)->getBounces();

$goals = $api->subscribers()->getSubscriberActivity()->getGoals(
    new \DateTime('2017-06-24'), 
    ReturnColumnsSet::STANDARD(),
    $returnGuidInResponse
)->getGoals();

$response = $api->subscribers()->getSubscriberSegments();
if ($response->isOk()) {
    foreach($response->getSegments() as $segment) {
        echo $segment->getId();
        echo $segment->getName();
    }
} else {
    // handle errors
}

$segmentId = 25;
$response = $api->subscribers()->getSegmentSize($segmentId);
if ($response->isOk()) {
    echo $response->getSize();
    echo $response->getCountDate()->format('Y-m-d H:i:s);
} else {
    // handle errors
}

// ...
use Pzelant\ExpertSenderApi\Enum\BouncesGetRequest\BounceType;
// ...
$startDate = new \DateTime('2015-01-01');
$endDate = new \DateTime('2016-01-01');
// bounce type is optional, null by defalt
$bounceType = BounceType::MAILBOX_FULL();

$response = $api->getBouncesList($startDate, $endDate, $bounceType);

foreach ($response->getBounces() as $bounce) {
    $date = $bounce->getDate();
    $email = $bounce->getEmail();
    // etc
}

$response = $api->dataTables()->getTablesList();
if ($response->isOk()) {
   foreach ($response->getTables() as $table)) {
        echo $table->getId();
        echo $table->getName();
        echo $table->getColumnsCount();
        echo $table->getRelationshipsCount();
        echo $table->getRelationshipsDestinationCount();
        echo $table->getRowsCount();
        echo $table->getSize();
   }   
} else {
    // handle errors
} 

$response = $api->dataTables()->getTableDetails('table-name');
if ($response->isOk()) {
    $tableDetails = $response->getTableDetails();
    echo $tableDetails->getId();
    echo $tableDetails->getName();
    echo $tableDetails->getColumnsCount();
    echo $tableDetails->getRelationshipsCount();
    echo $tableDetails->getRelationshipsDestinationCount();
    echo $tableDetails->getRowsCount();
    echo $tableDetails->getDescription();
    foreach ($tableDetails->getColumns() as $column) {
        echo $column->getName();
        echo $column->getColumnType();
        echo $column->getLength();
        echo $column->getDefaultValue() ?: 'No default value';
        echo $column->isPrimaryKey() ? 'true' : 'false';
        echo $column->isRequired() ? 'true' : 'false';
    }
} else {
    // handle errors
}

// ...
use Pzelant\ExpertSenderApi\Enum\DataTablesGetDataPostRequest\Direction;
use Pzelant\ExpertSenderApi\Enum\DataTablesGetDataPostRequest\Operator;
use Pzelant\ExpertSenderApi\Model\WhereCondition;
use Pzelant\ExpertSenderApi\Model\DataTablesGetDataPostRequest\OrderByRule;
// ...
// limit is optional, and null by default
$limit = 30;
$response = $api->dataTables()->getRows(
    // table name to get data from
    'table-name',
    // array of column names to get from table
    ['ColumnName1', 'ColumnName2'],
    // where conditions to filter data
    [
        new WhereCondition('ColumnName1', Operator::EQUAL(), 'value'),
        new WhereCondition('ColumnName2', Operator::LIKE(), 'string'),
        new WhereCondition('ColumnName3', Operator::GREATER(), 24),
        new WhereCondition('ColumnName4', Operator::LOWER(), 10.54),
    ],
    // sorting rules
    [
        new OrderByRule('ColumnName1', Direction::ASCENDING()),
        new OrderByRule('ColumnName1', Direction::DESCENDING()),
    ],
    // and limit
    $limit
);

if ($response->isOk()) {
    // if everything is okay, you can get csv reader and fetch data
    $csvReader = $response->getCsvReader();
    foreach ($csvReader->fetchAll() as $row) {
        // fetched data will have column names in keys and values ... will be values
        echo $row['ColumnName1'];
        echo $row['ColumnName2'];
    }
} else {
    // handle errors
}

// ...
use Pzelant\ExpertSenderApi\Enum\DataTablesGetDataPostRequest\Operator;
use Pzelant\ExpertSenderApi\Model\WhereCondition;
// ...
$response = $api->dataTables()->getRowsCount(
    'table-name',
    [
        new WhereCondition('Column1', Operator::EQUAL(), 12),
        new WhereCondition('Column2', Operator::GREATER(), 12.53),
        new WhereCondition('Column3', Operator::LOWER(), -0.56),
        new WhereCondition('Column5', Operator::LIKE(), 'string'),
    ]
);

if ($response->isOk()) {
    $count = $response->getCount();
} else {
    // handle errors
}

$response = $api->dataTables()->clearTable('table-name');
if ($response->isOk()) {
    // table has been cleared
} else {
    // handle errors
}

// ...
use Pzelant\ExpertSenderApi\Model\Column;
use Pzelant\ExpertSenderApi\Model\DataTablesAddMultipleRowsPostRequest\Row;
// ...
$response = $api->dataTables()->addRows(
    // table name to insert rows
    'table-name',
    // rows to insert
    [
        new Row(
            [
                // fields to set 
                new Column('ColumnName1', 10),
                new Column('ColumnName2', 10.5),
                new Column('ColumnName3', 'string'),
            ]
        ),
        new Row(
            [
                new Column('ColumnName1', 25),
                new Column('ColumnName2', 0.45),
                new Column('ColumnName3', 'value'),
            ]
        ),
    ]
);

if ($response->isOk()) {
    // make some stuff
} else {
    // handle errors
    echo $response->getErrorCode();
    foreach ($response->getErrorMessages() as $errorMessage) {
        echo $errorMessage->getMessage();
    }
}

// ...
use Pzelant\ExpertSenderApi\Model\Column;
// ...
$response = $api->dataTables()->updateRow(
    // table name 
    'table-name',
    // primary keys to find row
    [
        new Column('ColumnName1', 12),
        new Column('ColumnName2', 'value'),
    ],
    // fields to change
    [
        new Column('ColumnName3', 25),
        new Column('ColumnName4', 'string'),
        new Column('ColumnName5', 25.4)
    ]
);

if ($response->isOk()) {
    // make some stuff
} else {
    // handle errors
    echo $response->getErrorCode();
    foreach ($response->getErrorMessages() as $errorMessage) {
        echo $errorMessage->getMessage();
    }
}

// ...
use Pzelant\ExpertSenderApi\Model\Column;
// ...
$response = $api->dataTables()->deleteOneRow(
    // table name to update rows
    'table-name',
    // primary keys to find row
    [
        new Column('ColumnName1', 12),
        new Column('ColumnName2', 'value'),
    ]
);

if ($response->isOk()) {
    // make some stuff
} else {
    // handle errors
    echo $response->getErrorCode();
    foreach ($response->getErrorMessages() as $errorMessage) {
        echo $errorMessage->getMessage();
    }
}

// ...
use Pzelant\ExpertSenderApi\Model\DataTablesDeleteRowsPostRequest\Filter;
use Pzelant\ExpertSenderApi\Enum\DataTablesDeleteRowsPostRequest\FilterOperator;
// ...
$response = $api->dataTables()->deleteRows(
    'table-name',
    [
        new Filter('Column1', FilterOperator::EQ(), 12),
        new Filter('Column2', FilterOperator::GE(), 56.7),
        new Filter('Column3', FilterOperator::EQ(), 'string'),
        new Filter('Column4', FilterOperator::GT(), 89.234),
        new Filter('Column5', FilterOperator::LT(), 87.3),
        new Filter('Column6', FilterOperator::LE(), 98),
    ]
);

if ($response->isOk()) {
    $count = $response->getCount();
} else {
    // handle errors
}