PHP code example of marksamp / evolution-api
1. Go to this page and download the library: Download marksamp/evolution-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/ */
marksamp / evolution-api example snippets
volutionAPI\EvolutionAPIClient;
use EvolutionAPI\Utils\SafeSender;
// Criar cliente
$client = new EvolutionAPIClient(
'https://sua-evolution-api.com',
'sua-api-key',
'minha-instancia'
);
// Conectar automaticamente
$client->quickStart();
// Enviar mensagem
$client->sendQuickMessage('5511999999999', 'Olá! 🎉');
// Usar SafeSender para proteção anti-bloqueio
$safeSender = new SafeSender(
$client,
SafeSender::configNumeroEstabelecido()
);
$safeSender->send('5511999999999', 'Mensagem segura!');
// Criar e conectar (método rápido)
$client->quickStart();
// Verificar se está conectado
if ($client->isConnected()) {
echo "✅ Conectado!";
}
// Criar instância manualmente
$client->instance()->create('minha-instancia', [
'qrcode' => true,
'integration' => 'WHATSAPP-BAILEYS'
]);
// Conectar
$client->instance()->connect('minha-instancia');
// Status da conexão
$status = $client->instance()->getConnectionStatus('minha-instancia');
// Listar todas
$instances = $client->instance()->listAll();
// Reiniciar
$client->instance()->restart('minha-instancia');
// Deletar
$client->instance()->delete('minha-instancia');
// Simples
$client->sendQuickMessage('5511999999999', 'Olá!');
// Completo
$client->message()->sendText('5511999999999', 'Mensagem completa', [
'delay' => 1000
]);
// Imagem
$client->message()->sendMedia(
'5511999999999',
'https://exemplo.com/imagem.jpg',
'image',
'Legenda da imagem'
);
// Vídeo
$client->message()->sendMedia(
'5511999999999',
'https://exemplo.com/video.mp4',
'video',
'Vídeo incrível!'
);
// Documento
$client->message()->sendMedia(
'5511999999999',
'https://exemplo.com/doc.pdf',
'document',
'',
'documento.pdf'
);
// Áudio normal
$client->message()->sendAudio(
'5511999999999',
'https://exemplo.com/audio.mp3',
false
);
// PTT (Push to Talk - áudio de voz)
$client->message()->sendAudio(
'5511999999999',
'https://exemplo.com/audio.mp3',
true
);
$client->message()->sendLocation(
'5511999999999',
-3.7319, // Latitude
-38.5267, // Longitude
'Fortaleza',
'Fortaleza, Ceará, Brasil'
);
$client->message()->sendContact('5511999999999', [
[
'fullName' => 'João Silva',
'waid' => '5511888888888',
'phoneNumber' => '+55 11 88888-8888'
]
]);
$buttons = [
[
'buttonId' => 'btn1',
'buttonText' => ['displayText' => 'Opção 1'],
'type' => 1
],
[
'buttonId' => 'btn2',
'buttonText' => ['displayText' => 'Opção 2'],
'type' => 1
]
];
$client->message()->sendButtons(
'5511999999999',
'Escolha uma opção',
'Descrição',
$buttons,
'Rodapé'
);
$sections = [
[
'title' => 'Categoria',
'rows' => [
[
'rowId' => 'opt1',
'title' => 'Opção 1',
'description' => 'Descrição'
]
]
]
];
$client->message()->sendList(
'5511999999999',
'Título',
'Descrição',
'Ver Opções',
$sections
);
// Simular digitação
$client->presence()->simulateTyping('5511999999999', 3);
$client->message()->sendText('5511999999999', 'Olá!');
// Simular gravação de áudio
$client->presence()->simulateRecording('5511999999999', 4);
$client->message()->sendAudio('5511999999999', 'audio.mp3', true);
// Controle manual
$client->presence()->typing('5511999999999', 5000);
$client->presence()->recording('5511999999999', 3000);
$client->presence()->paused('5511999999999');
// Presença global
$client->presence()->available();
$client->presence()->unavailable();
// Conversação natural
$client->presence()->simulateTyping('5511999999999', 2);
$client->message()->sendText('5511999999999', 'Primeira mensagem');
sleep(1);
$client->presence()->simulateTyping('5511999999999', 3);
$client->message()->sendText('5511999999999', 'Segunda mensagem');
// Listar todos
$contacts = $client->contact()->fetchAll();
// Buscar específico
$contact = $client->contact()->fetch('5511999999999');
// Verificar se existe
$exists = $client->checkNumber('5511999999999');
// Verificar múltiplos
$results = $client->contact()->checkExists([
'5511999999999',
'5511888888888'
]);
// Foto do perfil
$photo = $client->contact()->getProfilePicture('5511999999999');
// Bloquear/Desbloquear
$client->contact()->block('5511999999999');
$client->contact()->unblock('5511999999999');
// Atualizar seu perfil
$client->contact()->updateProfileName('Meu Nome');
$client->contact()->updateProfileStatus('Disponível');
$client->contact()->updateProfilePicture('https://exemplo.com/foto.jpg');
// Listar grupos
$groups = $client->group()->fetchAll();
// Criar grupo
$group = $client->group()->create(
'Nome do Grupo',
['5511999999999', '5511888888888'],
'Descrição'
);
// Informações
$info = $client->group()->getInfo('[email protected] ');
// Atualizar
$client->group()->updateSubject('[email protected] ', 'Novo Nome');
$client->group()->updateDescription('[email protected] ', 'Nova descrição');
$client->group()->updatePicture('[email protected] ', 'https://foto.jpg');
// Gerenciar participantes
$client->group()->addParticipants('[email protected] ', ['5511777777777']);
$client->group()->removeParticipants('[email protected] ', ['5511777777777']);
$client->group()->promoteParticipants('[email protected] ', ['5511777777777']);
$client->group()->demoteParticipants('[email protected] ', ['5511777777777']);
// Link de convite
$inviteCode = $client->group()->getInviteCode('[email protected] ');
$client->group()->revokeInviteCode('[email protected] ');
// Sair
$client->group()->leave('[email protected] ');
// Configurar webhook
$client->webhook()->set(
'https://seu-servidor.com/webhook',
['MESSAGES_UPSERT', 'SEND_MESSAGE', 'CONNECTION_UPDATE']
);
// Webhook global
$client->webhook()->setGlobal(
'https://seu-servidor.com/webhook-global',
['MESSAGES_UPSERT']
);
// Obter configuração
$config = $client->webhook()->get();
// Remover
$client->webhook()->remove();
// Processar webhook recebido
$payload = file_get_contents('php://input');
$data = $client->webhook()->processWebhook($payload);
// Validar assinatura
$signature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
$valid = $client->webhook()->validateSignature($payload, $signature, 'secret');
use EvolutionAPI\Utils\TextHumanizer;
$humanizer = new TextHumanizer();
$texto = "Olá! Como você está? Obrigado por entrar em contato.";
$resultado = $humanizer->humanizar($texto);
echo $resultado['texto']; // Texto humanizado
echo $resultado['tempo_digitacao']; // Tempo em segundos
print_r($resultado['pausas']); // Pontos de pausa
// Gerar 5 variações diferentes do mesmo texto
$variacoes = $humanizer->gerarVariacoes($texto, 5);
foreach ($variacoes as $variacao) {
echo $variacao . "\n"; // Cada uma diferente!
}
// Ativar humanização no SafeSender
$safeSender = new SafeSender(
$client,
SafeSender::configNumeroEstabelecido(true) // true = com humanização
);
// Enviar - texto será automaticamente humanizado
$safeSender->send('5511999999999', 'Olá! Como vai?');
$config = [
'adicionar_erros_digitacao' => true,
'chance_erro' => 5, // 5% de chance
'variar_pontuacao' => true,
'quebrar_linhas' => true,
'variar_saudacoes' => true,
'adicionar_emojis' => true,
'chance_emoji' => 30, // 30% de chance
];
$humanizer = new TextHumanizer($config);
// ANTES (robótico)
"Ola. Como voce esta. Obrigado por entrar em contato."
// DEPOIS (humanizado)
"Oi! Como vc está?
Obrigado por entrar em contato 😊"
$partes = $humanizer->simularDigitacaoProgressiva($textoLongo);
foreach ($partes as $parte) {
$client->presence()->typing($number, $parte['tempo_digitacao']);
// Aguardar...
$client->message()->sendText($number, $parte['texto']);
sleep($parte['pausa_depois']);
}
// Para textos longos (200+ caracteres), SafeSender pode enviar
// progressivamente como se fosse um humano digitando!
$safeSender = new SafeSender(
$client,
SafeSender::configNumeroEstabelecido(true)
);
// Ativar envio progressivo
$resultado = $safeSender->send($number, $textoLongo, [
'envio_progressivo' => true
]);
// Resultado: Texto enviado em múltiplas partes com pausas naturais!
use EvolutionAPI\Utils\SafeSender;
// Para número NOVO (0-30 dias)
$safeSender = new SafeSender(
$client,
SafeSender::configNumeroNovo()
);
// Limites: 20 msgs/hora, 50 msgs/dia, delay 5-10s
// Para número ESTABELECIDO (30+ dias)
$safeSender = new SafeSender(
$client,
SafeSender::configNumeroEstabelecido()
);
// Limites: 100 msgs/hora, 300 msgs/dia, delay 2-5s
// Para número BUSINESS
$safeSender = new SafeSender(
$client,
SafeSender::configNumeroBusiness()
);
// Limites: 200 msgs/hora, 500 msgs/dia, delay 1-3s
// Envio único
$result = $safeSender->send('5511999999999', 'Mensagem segura');
// Envio em lote
$destinatarios = [
'5511999999999' => 'Olá João!',
'5511888888888' => 'Oi Maria!',
'5511777777777' => 'E aí Pedro!',
];
$stats = $safeSender->sendBatch($destinatarios);
$safeSender->mostrarStats();
$numbers = ['5511999999999', '5511888888888'];
$templates = [
'Olá {nome}! Como vai?',
'Oi {nome}, tudo bem?',
'E aí {nome}! Beleza?',
];
$variaveis = [
'5511999999999' => ['nome' => 'João'],
'5511888888888' => ['nome' => 'Maria'],
];
$stats = $safeSender->sendVariado($numbers, $templates, $variaveis);
// Obter estatísticas
$stats = $safeSender->getStats();
/*
Array (
[enviadas] => 50
[falhas] => 2
[bloqueios] => 0
[taxa_sucesso] => 96.15%
[tempo_total] => 450
[msgs_por_minuto] => 6.67
)
*/
// Exibir formatado
$safeSender->mostrarStats();
// Histórico
$historico = $safeSender->getHistorico(10); // Últimos 10
// Exportar CSV
$safeSender->exportarHistorico('relatorio.csv');
$configCustom = [
'mensagens_por_minuto' => 3,
'mensagens_por_hora' => 80,
'mensagens_por_dia' => 250,
'delay_minimo' => 2,
'delay_maximo' => 6,
'usar_presenca' => true,
'validar_numero' => true,
'horario_inicio' => 9,
'horario_fim' => 21,
'permitir_domingo' => false,
];
$safeSender = new SafeSender($client, $configCustom);
use EvolutionAPI\Utils\SafeSender;
// Configurar
$safeSender = new SafeSender(
$client,
SafeSender::configNumeroEstabelecido()
);
// Preparar com variação
$numbers = ['5511999999999', '5511888888888'];
$templates = [
'Olá {nome}! Como vai?',
'Oi {nome}, tudo bem?',
];
$vars = [
'5511999999999' => ['nome' => 'João'],
'5511888888888' => ['nome' => 'Maria'],
];
// Enviar
$stats = $safeSender->sendVariado($numbers, $templates, $vars);
$safeSender->mostrarStats();
// Exportar relatório
$safeSender->exportarHistorico('relatorio_' . date('Y-m-d') . '.csv');
function botAtendimento($client, $number, $mensagem) {
$client->presence()->available();
sleep(1);
$client->presence()->typing($number, 2000);
sleep(2);
if (stripos($mensagem, 'horário') !== false) {
$resposta = 'Atendemos de segunda a sexta, das 9h às 18h.';
} else {
$resposta = 'Olá! Como posso ajudá-lo(a)?';
}
$client->message()->sendText($number, $resposta);
}
$safeSender = new SafeSender(
$client,
SafeSender::configNumeroEstabelecido()
);
$lotes = array_chunk($destinatarios, 50, true);
foreach ($lotes as $indice => $lote) {
echo "Lote " . ($indice + 1) . "\n";
$stats = $safeSender->sendBatch($lote);
$safeSender->mostrarStats();
if ($indice < count($lotes) - 1) {
sleep(300); // 5 minutos entre lotes
}
}
$safeSender->exportarHistorico('campanha_final.csv');
function enviarComRetry($safeSender, $number, $message, $max = 3) {
for ($tentativa = 1; $tentativa <= $max; $tentativa++) {
$resultado = $safeSender->send($number, $message);
if ($resultado) {
return true;
}
if ($tentativa < $max) {
sleep(pow(2, $tentativa) * 60); // Exponential backoff
}
}
return false;
}
$payload = file_get_contents('php://input');
$data = $client->webhook()->processWebhook($payload);
if ($data['event'] === 'MESSAGES_UPSERT') {
// Processar mensagem
}
$status = $client->instance()->getConnectionStatus($instanceName);
if (isset($status['instance']['qrcode'])) {
$qrCode = base64_decode($status['instance']['qrcode']);
file_put_contents('qrcode.png', $qrCode);
}
$client1 = new EvolutionAPIClient($url, $key, 'instancia1');
$client2 = new EvolutionAPIClient($url, $key, 'instancia2');
use EvolutionAPI\Exceptions\EvolutionAPIException;
try {
$result = $client->message()->sendText($number, $message);
} catch (EvolutionAPIException $e) {
echo "Erro da API: " . $e->getMessage();
echo "Código: " . $e->getCode();
if (!empty($e->getContext())) {
print_r($e->getContext());
}
} catch (Exception $e) {
echo "Erro geral: " . $e->getMessage();
}
bash
composer bash
git clone https://github.com/seu-usuario/evolution-api-php.git
cd evolution-api-php
composer install
src/
├── Config/Config.php
├── Http/HttpClient.php
├── Services/
│ ├── InstanceService.php
│ ├── MessageService.php
│ ├── ContactService.php
│ ├── GroupService.php
│ ├── WebhookService.php
│ └── PresenceService.php
├── Utils/SafeSender.php
├── Exceptions/EvolutionAPIException.php
└── EvolutionAPIClient.php