PHPackages                             notifica-dev/sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Mail &amp; Notifications](/categories/mail)
4. /
5. notifica-dev/sdk

ActiveLibrary[Mail &amp; Notifications](/categories/mail)

notifica-dev/sdk
================

Official PHP SDK for notifica.dev

v0.2.3(1w ago)033↓64.3%MITPHPPHP ^8.1

Since Jun 9Pushed 1w agoCompare

[ Source](https://github.com/GC-Tec/notifica-php)[ Packagist](https://packagist.org/packages/notifica-dev/sdk)[ RSS](/packages/notifica-dev-sdk/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (3)Versions (6)Used By (0)

notifica-dev/sdk
================

[](#notifica-devsdk)

SDK PHP oficial do [notifica.dev](https://notifica.dev) — envio de notificações push, e-mail e web a partir do seu backend PHP.

Requisitos
----------

[](#requisitos)

- PHP 8.1 ou superior
- [Composer](https://getcomposer.org)

Instalação
----------

[](#instalação)

```
composer require notifica-dev/sdk
```

Configuração
------------

[](#configuração)

Instancie o `NotificaClient` com o seu access token e a URL base da API:

```
use Notifica\NotificaClient;

$notifica = new NotificaClient(
    accessToken: env('NOTIFICA_ACCESS_TOKEN'),
    baseUrl: env('NOTIFICA_API_URL'),
);
```

> O `baseUrl` é opcional. Se omitido, aponta para `https://api.notifica.dev`.

---

Notificações
------------

[](#notificações)

O SDK usa uma abordagem baseada em classes para envio de notificações. Cada evento do seu sistema vira uma classe que declara os canais e o conteúdo da mensagem.

### Criando uma notificação

[](#criando-uma-notificação)

```
use Notifica\Notification;
use Notifica\Target;
use Notifica\Messages\PushMessage;
use Notifica\Messages\EmailMessage;
use Notifica\Messages\WebMessage;

class PedidoEnviadoNotification extends Notification
{
    public function __construct(private Pedido $pedido) {}

    // Canais que serão utilizados
    public function via(): array
    {
        return ['push', 'email'];
    }

    // Destinatários (opcional — pode ser sobrescrito no send())
    public function targets(): array
    {
        return [
            Target::customer("users:{$this->pedido->userId}"),
        ];
    }

    // Agendamento (opcional)
    public function scheduledAt(): ?\DateTimeInterface
    {
        return null; // envio imediato
    }

    // Chave de idempotência (opcional)
    // O SDK sufixará o canal automaticamente: "pedido-123-push", "pedido-123-email"
    public function code(): ?string
    {
        return "pedido-enviado-{$this->pedido->id}";
    }

    public function toPush(): PushMessage
    {
        return PushMessage::make()
            ->title('Seu pedido foi enviado!')
            ->body("Pedido #{$this->pedido->id} está a caminho.");
    }

    public function toEmail(): EmailMessage
    {
        return EmailMessage::make()
            ->subject("Pedido #{$this->pedido->id} enviado!")
            ->body('Seu pedido está a caminho. Acompanhe a entrega pelo link abaixo.')
            ->to($this->pedido->emailCliente)
            ->from('pedidos@minhaapp.com.br', 'Minha App');
    }

    public function toWeb(): WebMessage
    {
        return WebMessage::make()
            ->title('Pedido enviado!')
            ->body("Pedido #{$this->pedido->id} está a caminho.")
            ->data(['pedido_id' => $this->pedido->id]);
    }
}
```

### Enviando

[](#enviando)

```
// Destinatários definidos na própria classe
$notifica->send(new PedidoEnviadoNotification($pedido));

// Destinatários sobrescritos na chamada
$notifica->send(
    new PedidoEnviadoNotification($pedido),
    Target::customer("users:{$user->id}"),
);
```

O método `send()` retorna um array com a resposta da API para cada canal:

```
$resultados = $notifica->send(new PedidoEnviadoNotification($pedido));

$resultados['push']['id'];  // ID do intent de push
$resultados['email']['id']; // ID do intent de e-mail
```

---

Destinatários (Target)
----------------------

[](#destinatários-target)

Use a classe `Target` para definir para quem a notificação será enviada:

```
use Notifica\Target;

Target::customer('users:123')          // cliente pelo ID externo
Target::allDevices()                   // todos os dispositivos do app
Target::device('installation-id')      // dispositivo específico
Target::emailAddress('user@email.com') // endereço de e-mail direto
Target::code('usuarios-premium')       // dispositivos com este código
Target::tag('premium', 'beta')         // dispositivos com estas tags
```

---

Dispositivos
------------

[](#dispositivos)

### Registrar instalação web

[](#registrar-instalação-web)

```
$notifica->devices->registerWeb(
    installationKey: $installationKey,
    customerExternalId: "users:{$user->id}",
    name: $user->name,
    email: $user->email,
);
```

> Idempotente — conflitos 409 são ignorados silenciosamente.

### Registrar instalação mobile (iOS / Android)

[](#registrar-instalação-mobile-ios--android)

```
$notifica->devices->registerMobile(
    platform: 'android',         // 'android' ou 'ios'
    pushProvider: 'expo',
    pushToken: $expoPushToken,
    customerExternalId: "users:{$user->id}",
    customerName: $user->name,
    tags: ['premium'],
);
```

---

Token de sessão do cliente
--------------------------

[](#token-de-sessão-do-cliente)

Necessário para autenticar conexões WebSocket e requisições de inbox no frontend.

```
$token = $notifica->customerTokens->mint("users:{$user->id}");

$token->token;     // string — token de sessão
$token->expiresAt; // DateTimeImmutable — data de expiração
```

### Iniciar uma sessão web em uma chamada

[](#iniciar-uma-sessão-web-em-uma-chamada)

Registra a instalação web e gera o token de uma vez — ideal para o endpoint de sessão consumido pelo frontend:

```
$token = $notifica->startWebSession(
    installationKey: $installationKey,
    customerExternalId: "users:{$user->id}",
    name: $user->name,
    email: $user->email,
);
```

Os objetos de resposta implementam `JsonSerializable` (emitindo `snake_case`), então podem ser retornados diretamente de um controller:

```
return response()->json($token); // { "token": "...", "expires_at": "..." }
```

---

Inbox
-----

[](#inbox)

### Listar notificações

[](#listar-notificações)

`list()` retorna um `Notifica\Responses\InboxPage` (também serializável para JSON):

```
$inbox = $notifica->inbox->list(
    customerExternalId: "users:{$user->id}",
    page: 1,
    perPage: 20,
    readStatus: 'unread', // 'all', 'read' ou 'unread'
);

$inbox->total;
$inbox->unreadTotal; // total de notificações não lidas do cliente
$inbox->hasNextPage;

foreach ($inbox->items as $notification) {
    $notification->id;
    $notification->title;     // ?string
    $notification->body;
    $notification->data;      // payload definido pela aplicação (o SDK não interpreta)
    $notification->createdAt; // DateTimeImmutable
    $notification->isRead();
}

return response()->json($inbox); // { "data": [...], "meta": {...} }
```

### Marcar como lida / não lida

[](#marcar-como-lida--não-lida)

Retornam o `Notifica\Responses\CustomerNotification` atualizado:

```
$notification = $notifica->inbox->markAsRead($notificationId, "users:{$user->id}");
$notification = $notifica->inbox->markAsUnread($notificationId, "users:{$user->id}");
```

---

Tempo real (inbox)
------------------

[](#tempo-real-inbox)

O contrato do canal de tempo real é exposto em `Notifica\Realtime` para evitar strings mágicas no frontend:

```
use Notifica\Realtime;

Realtime::NAMESPACE;            // "/customer-events" — namespace Socket.IO
Realtime::EVENT_INBOX_UPDATED;  // "inbox.updated" — recarregue a inbox ao receber este evento
```

Conecte um cliente Socket.IO a `{baseUrl}` + `Realtime::NAMESPACE`, autenticado com o token de sessão, e recarregue a inbox quando `Realtime::EVENT_INBOX_UPDATED` for emitido.

---

Tratamento de erros
-------------------

[](#tratamento-de-erros)

Todas as chamadas à API lançam `Notifica\Exceptions\NotificaException` em caso de erro HTTP:

```
use Notifica\Exceptions\NotificaException;

try {
    $notifica->send(new PedidoEnviadoNotification($pedido));
} catch (NotificaException $e) {
    $e->statusCode; // código HTTP (ex: 422, 503)
    $e->response;   // corpo da resposta como array
    $e->getMessage();
}
```

---

Licença
-------

[](#licença)

MIT

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance98

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity36

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~9 days

Total

5

Last Release

9d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/115515311?v=4)[Pedro](/maintainers/pedrodevelops)[@pedrodevelops](https://github.com/pedrodevelops)

---

Top Contributors

[![pedrogadelha-gc](https://avatars.githubusercontent.com/u/180218714?v=4)](https://github.com/pedrogadelha-gc "pedrogadelha-gc (11 commits)")

### Embed Badge

![Health badge](/badges/notifica-dev-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/notifica-dev-sdk/health.svg)](https://phpackages.com/packages/notifica-dev-sdk)
```

###  Alternatives

[aws/aws-sdk-php

AWS SDK for PHP - Use Amazon Web Services in your PHP project

6.2k543.5M2.7k](/packages/aws-aws-sdk-php)[neuron-core/neuron-ai

The PHP Agentic Framework.

2.0k656.1k46](/packages/neuron-core-neuron-ai)[tencentcloud/tencentcloud-sdk-php

TencentCloudApi php sdk

3661.3M47](/packages/tencentcloud-tencentcloud-sdk-php)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

293.1k](/packages/eslazarev-wildberries-sdk)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k16](/packages/tempest-framework)[lion/bundle

Lion-framework configuration and initialization package

122.4k4](/packages/lion-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
