PHP code example of thinwrap / notifications

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

    

thinwrap / notifications example snippets


use Thinwrap\Notifications\Email;
use Thinwrap\Notifications\Enum\NotificationProviderId;
use Thinwrap\Notifications\Providers\Sendgrid\SendgridConfig;
use Thinwrap\Notifications\DTO\Email\EmailSendInput;
use Thinwrap\Notifications\Exception\ConnectorError;

$email = new Email(
    NotificationProviderId::Sendgrid,
    new SendgridConfig(apiKey: getenv('SG_KEY')),
);

try {
    $result = $email->send(new EmailSendInput(
        to:      '[email protected]',
        from:    '[email protected]',
        subject: 'Hello from Thinwrap',
        text:    'A short plain-text body.',
    ));
    echo $result->success;            // bool
    echo $result->providerMessageId;  // vendor message id, if returned
} catch (ConnectorError $e) {
    error_log($e->providerCode->value . ': ' . ($e->providerMessage ?? ''));
}

use Thinwrap\Notifications\Sms;
use Thinwrap\Notifications\Providers\Twilio\TwilioConfig;
use Thinwrap\Notifications\Providers\Vonage\VonageConfig;
use Thinwrap\Notifications\DTO\Sms\SmsSendInput;

$twilio = new Sms(NotificationProviderId::Twilio, new TwilioConfig(
    accountSid: getenv('TWILIO_SID'),
    authToken:  getenv('TWILIO_TOKEN'),
));
$vonage = new Sms(NotificationProviderId::Vonage, new VonageConfig(
    apiKey:    getenv('VONAGE_KEY'),
    apiSecret: getenv('VONAGE_SECRET'),
));

$sameInput = new SmsSendInput(to: '+14155550100', from: '+14155550199', body: 'Hello');
$twilio->send($sameInput);
$vonage->send($sameInput);

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

$tracingClient = new class(new Client()) implements ClientInterface {
    public function __construct(private Client $inner) {}
    public function sendRequest(RequestInterface $req): ResponseInterface
    {
        error_log('→ ' . $req->getMethod() . ' ' . (string) $req->getUri());
        return $this->inner->sendRequest($req);
    }
};

$email = new Email(
    NotificationProviderId::Sendgrid,
    new SendgridConfig(apiKey: getenv('SG_KEY'), from: '[email protected]'),
    $tracingClient,                // ?ClientInterface — third constructor arg
);

use Thinwrap\Notifications\Exception\ConnectorError;
use Thinwrap\Notifications\Enum\ProviderCode;

try {
    $email->send($input);
} catch (ConnectorError $e) {
    match ($e->providerCode) {
        ProviderCode::RateLimited         => /* respect Retry-After in $e->cause['retryAfter'] */ null,
        ProviderCode::AuthFailed          => /* rotate credentials                              */ null,
        ProviderCode::InvalidRequest      => /* fix payload                                     */ null,
        ProviderCode::InvalidRecipient    => /* bad destination address                         */ null,
        ProviderCode::ProviderUnavailable => /* transient 5xx — your retry strategy             */ null,
        ProviderCode::Unknown             => /* fallback                                        */ null,
    };
}

[
    'raw'               => mixed,            // the parsed vendor error body (or transport-failure detail), null when absent
    'retryAfter'        => string|int|null,  // the RAW Retry-After value (header string, or body int for Telegram/Discord) — never normalized
    'retryAfterSeconds' => int|null,         // the PARSED Retry-After in seconds (null when no Retry-After present)
]

$email->send(new EmailSendInput(
    to:      '[email protected]',
    from:    '[email protected]',
    subject: 'Hi',
    text:    'Hello',
    _passthrough: [
        'body' => [
            // SendGrid-specific — forwarded into v3/mail/send body verbatim
            'dynamic_template_data' => ['firstName' => 'Alice'],
            'mail_settings'         => ['sandbox_mode' => ['enable' => true]],
        ],
    ],
));

use Thinwrap\Notifications\Push;
use Thinwrap\Notifications\Contract\PushConnectorInterface;
use Thinwrap\Notifications\DTO\Push\PushSendInput;
use Thinwrap\Notifications\DTO\Push\PushSendResult;
use Thinwrap\Notifications\DTO\Push\PushStatus;

final class NtfyPushConnector implements PushConnectorInterface
{
    public function __construct(private \Psr\Http\Client\ClientInterface $client) {}

    public function send(PushSendInput $input): PushSendResult
    {
        // your wire call — e.g. POST https://ntfy.sh/{$input->to}
        $response = $this->client->sendRequest(/* ... */);

        return new PushSendResult(
            success:           true,
            status:            PushStatus::Sent,
            providerMessageId: null,
            raw:               (string) $response->getBody(),
        );
    }
}

$push = Push::fromConnector(new NtfyPushConnector($client));
$push->send(new PushSendInput(to: 'deploys', title: 'Deploy', body: 'v1.0 is live'));

// Before — twilio/sdk
$twilio = new \Twilio\Rest\Client($sid, $token);
$twilio->messages->create('+14155550100', ['from' => '+14155550199', 'body' => 'Hi']);

// After
use Thinwrap\Notifications\Sms;
use Thinwrap\Notifications\Providers\Twilio\TwilioConfig;
use Thinwrap\Notifications\DTO\Sms\SmsSendInput;

$sms = new Sms(NotificationProviderId::Twilio, new TwilioConfig(accountSid: $sid, authToken: $token));
$sms->send(new SmsSendInput(to: '+14155550100', from: '+14155550199', body: 'Hi'));

// Before — sendgrid/sendgrid-php
$sg = new \SendGrid(getenv('SG_KEY'));
$mail = new \SendGrid\Mail\Mail();
$mail->setFrom('[email protected]');
$mail->addTo('[email protected]');
$mail->setSubject('Hi');
$mail->addContent('text/plain', 'Hello');
$sg->send($mail);

// After
$email = new Email(NotificationProviderId::Sendgrid, new SendgridConfig(apiKey: getenv('SG_KEY')));
$email->send(new EmailSendInput(to: '[email protected]', from: '[email protected]', subject: 'Hi', text: 'Hello'));