Saltar al contenido principal
Documentation

SDK PHP

Packagist: coffeemail/coffeemail-php v0.1.0

Referencia completa del paquete oficial coffeemail/coffeemail-php para PHP moderno (8.2+). Tipado estricto, retorno seguro data, error, soporte para tuplas y validación criptográfica de webhooks.

¿Buscas la documentación para Node.js o TypeScript? Consulta la referencia oficial del paquete @coffeemail/node.

SDK Node.js
terminal
composer require coffeemail/coffeemail-php

Inicialización del Cliente

Laravel • Symfony • WordPress • Vanilla PHP

La clave de API se resuelve automáticamente de la variable de entorno COFFEEMAIL_API_KEY si se omite en el constructor.

$client = new CoffeeMail(?string $apiKey = null, string $locale = 'pt-BR', int $timeoutSeconds = 10);
send_email.php
use CoffeeMail\CoffeeMail; // Carrega automaticamente COFFEEMAIL_API_KEY do ambiente ou do construtor:$client = new CoffeeMail(); [$data, $error] = $client->emails->send([    'from' => 'contato@seudominio.com.br',    'to' => 'cliente@gmail.com',    'subject' => 'Bem-vindo ao CoffeeMail!',    'html' => '<h1>Olá!</h1><p>Sua conta está ativa.</p>',]); if ($error !== null) {    echo "Erro ao enviar [{$error->code}]: {$error->message}\n";    exit(1);} echo "E-mail enfileirado com sucesso: {$data['id']}\n";

Desempaquetado de Tuplas y Retorno Seguro

Patrón Seguro { data, error }

Las operaciones retornan una instancia de CoffeeMailResponse permitiendo desempaquetar [$data, $error] directamente o invocar ->unwrap() para lanzar excepciones tipadas.

error_handling.php
use CoffeeMail\CoffeeMail;use CoffeeMail\Exceptions\RateLimitError; $client = new CoffeeMail(); [$data, $error] = $client->emails->send([    'from' => 'contato@seudominio.com.br',    'to' => 'cliente@gmail.com',    'subject' => 'Aviso',    'html' => '<p>Mensagem</p>',]); if ($error instanceof RateLimitError) {    echo "Aguarde {$error->retryAfterSeconds} segundos antes de tentar novamente.\n";    exit(1);} if ($error !== null) {    echo "Falha de envio: {$error->message}\n";    exit(1);} echo "ID: {$data['id']}\n";

Validación Criptográfica de Webhooks

HMAC SHA-256 (hash_equals)

El método Webhooks::verifySignature valida la firma HMAC SHA-256 en el encabezado x-coffeemail-signature usando comparación en tiempo constante contra ataques de temporización.

webhook_controller.php
use CoffeeMail\Resources\Webhooks; // No endpoint de webhook do seu app PHP:$payload = file_get_contents('php://input');$signature = $_SERVER['HTTP_X_COFFEEMAIL_SIGNATURE'] ?? '';$secret = getenv('COFFEEMAIL_WEBHOOK_SECRET'); if (! Webhooks::verifySignature($payload, $signature, $secret)) {    http_response_code(401);    echo "Assinatura inválida";    exit;} $event = json_decode($payload, true);echo "Evento processado com segurança: " . $event['event'];

Catálogo de Métodos

Referencia de operaciones disponibles en el cliente oficial para PHP.

Emails

.send()— Enviar correo transaccional
$client->emails->send(array $payload): CoffeeMailResponse
send.php
use CoffeeMail\CoffeeMail; $client = new CoffeeMail(); [$data, $error] = $client->emails->send([    'from' => 'noreply@seudominio.com.br',    'to' => 'cliente@example.com',    'subject' => 'Confirmação do pedido #123',    'html' => '<h1>Obrigado!</h1><p>Seu pedido está em processamento.</p>',]); if ($error !== null) {    echo "Erro ao enviar [{$error->code}]: {$error->message}\n";    exit(1);} echo "E-mail enfileirado com sucesso: {$data['id']}\n";
.sendBatch()— Enviar correos en lote
$client->emails->sendBatch(array $items): CoffeeMailResponse
sendBatch.php
use CoffeeMail\CoffeeMail; $client = new CoffeeMail(); [$data, $error] = $client->emails->sendBatch([    [        'from' => 'noreply@seudominio.com.br',        'to' => 'cliente1@example.com',        'subject' => 'Notificação 1',        'html' => '<p>Mensagem 1</p>',    ],    [        'from' => 'noreply@seudominio.com.br',        'to' => 'cliente2@example.com',        'subject' => 'Notificação 2',        'html' => '<p>Mensagem 2</p>',    ],]); if ($error !== null) {    throw $error;}
.get()— Consultar estado del correo
$client->emails->get(string $id): CoffeeMailResponse
get.php
use CoffeeMail\CoffeeMail; $client = new CoffeeMail(); [$data, $error] = $client->emails->get('eml_8f92b7c4'); if ($data !== null) {    echo "Status: {$data['status']}\n";}
.list()— Listar historial de envíos con filtros
$client->emails->list(array $query = []): CoffeeMailResponse
list.php
use CoffeeMail\CoffeeMail; $client = new CoffeeMail(); [$data, $error] = $client->emails->list([    'limit' => 20,    'status' => 'delivered',]);

Dominios

.create()— Registrar dominio remitente
$client->domains->create(array $payload): CoffeeMailResponse
create.php
use CoffeeMail\CoffeeMail; $client = new CoffeeMail(); [$data, $error] = $client->domains->create([    'name' => 'meudominio.com.br',]);
.verify()— Verificar registros DNS del dominio
$client->domains->verify(string $id): CoffeeMailResponse
verify.php
use CoffeeMail\CoffeeMail; $client = new CoffeeMail(); [$data, $error] = $client->domains->verify('dom_123');

Plantillas

.preview()— Previsualizar plantilla con variables
$client->templates->preview(string $id, array $variables = []): CoffeeMailResponse
preview.php
use CoffeeMail\CoffeeMail; $client = new CoffeeMail(); [$data, $error] = $client->templates->preview('tpl_123', [    'nome' => 'João',    'codigo' => '9842',]);

Webhooks

.verifySignature()— Validar firma HMAC del webhook
Webhooks::verifySignature(string $payload, string $signature, string $secret): bool
verifySignature.php
use CoffeeMail\Resources\Webhooks; // No controller do seu framework (Laravel, Symfony, etc.):$payload = file_get_contents('php://input');$signature = $_SERVER['HTTP_X_COFFEEMAIL_SIGNATURE'] ?? '';$secret = getenv('COFFEEMAIL_WEBHOOK_SECRET'); $isValid = Webhooks::verifySignature($payload, $signature, $secret); if (! $isValid) {    http_response_code(401);    echo "Assinatura inválida";    exit;}

Métricas

.get()— Consultar métricas de entregabilidad
$client->stats->get(array $query = []): CoffeeMailResponse
get.php
use CoffeeMail\CoffeeMail; $client = new CoffeeMail(); [$data, $error] = $client->stats->get([    'from' => '2026-01-01',    'to' => '2026-01-31',]);