JavaScript
Node.js, React, Vue, Angular
Python
Django, Flask, FastAPI
PHP
Laravel, CodeIgniter, WordPress
Configuração Básica
JavaScript/Node.js
Copiar
const axios = require('axios');
class ApiZap {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://b0fe4081af63.ngrok-free.app/api/v1';
this.headers = {
'Authorization': `ApiKey ${apiKey}`,
'Content-Type': 'application/json'
};
}
async sendMessage(data) {
try {
const response = await axios.post(`${this.baseUrl}/messages`, data, {
headers: this.headers
});
return response.data;
} catch (error) {
console.error('Erro ao enviar mensagem:', error.response?.data || error.message);
throw error;
}
}
async createInstance(data) {
const response = await axios.post(`${this.baseUrl}/instances`, data, {
headers: this.headers
});
return response.data;
}
}
// Uso
const client = new ApiZap('your_api_key_here');
Python
Copiar
import requests
import json
class ApiZap:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = 'https://b0fe4081af63.ngrok-free.app/api/v1'
self.headers = {
'Authorization': f'ApiKey {api_key}',
'Content-Type': 'application/json'
}
def send_message(self, data):
try:
response = requests.post(
f'{self.base_url}/messages',
headers=self.headers,
json=data
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f'Erro ao enviar mensagem: {e}')
raise
def create_instance(self, data):
response = requests.post(
f'{self.base_url}/instances',
headers=self.headers,
json=data
)
response.raise_for_status()
return response.json()
# Uso
client = ApiZap('your_api_key_here')
PHP
Copiar
<?php
class ApiZap {
private $apiKey;
private $baseUrl;
private $headers;
public function __construct($apiKey) {
$this->apiKey = $apiKey;
$this->baseUrl = 'https://b0fe4081af63.ngrok-free.app/api/v1';
$this->headers = [
'Authorization: ApiKey ' . $apiKey,
'Content-Type: application/json'
];
}
public function sendMessage($data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->baseUrl . '/messages');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200 && $httpCode !== 201) {
throw new Exception("Erro HTTP: $httpCode - $response");
}
return json_decode($response, true);
}
public function createInstance($data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->baseUrl . '/instances');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
}
// Uso
$client = new ApiZap('your_api_key_here');
?>
Casos de Uso Avançados
E-commerce - Carrinho Abandonado
Copiar
// Sistema de recuperação de carrinho abandonado
class CartRecovery {
constructor(apiZapClient) {
this.client = apiZapClient;
this.delays = [60, 180, 1440]; // 1h, 3h, 24h em minutos
}
async scheduleRecovery(cartData) {
const { phone, customerName, items, total, cartId } = cartData;
// Agendar 3 mensagens com delays diferentes
for (let i = 0; i < this.delays.length; i++) {
setTimeout(async () => {
const isStillAbandoned = await this.checkCartStatus(cartId);
if (isStillAbandoned) {
await this.sendRecoveryMessage(phone, customerName, items, total, i);
}
}, this.delays[i] * 60 * 1000);
}
}
async sendRecoveryMessage(phone, name, items, total, messageIndex) {
const messages = [
`🛒 Oi ${name}! Você esqueceu alguns itens no seu carrinho!\n\n💫 Finalize sua compra: R$ ${total}\n\n🔗 [Finalizar Pedido]`,
`⏰ ${name}, última chance! Seus itens ainda estão reservados.\n\n💰 Oferta especial: 10% OFF\nCódigo: VOLTA10\n\n🚀 [Comprar Agora]`,
`😢 ${name}, seus itens favoritos podem esgotar!\n\n🔥 ÚLTIMAS UNIDADES\n💳 Parcelamos em até 12x\n\n⚡ [Não Perder]`
];
await this.client.sendMessage({
type: 'API',
mediaType: 'TEXT',
content: messages[messageIndex],
phone: phone,
instanceId: process.env.INSTANCE_ID
});
}
}
Saúde - Lembretes de Consulta
Copiar
import schedule
import time
from datetime import datetime, timedelta
class AppointmentReminder:
def __init__(self, apizap_client):
self.client = apizap_client
def schedule_reminders(self, appointment):
"""Agenda lembretes 24h, 2h e 30min antes"""
appointment_time = datetime.fromisoformat(appointment['datetime'])
# 24 horas antes
reminder_24h = appointment_time - timedelta(hours=24)
schedule.every().day.at(reminder_24h.strftime('%H:%M')).do(
self.send_24h_reminder, appointment
).tag(f"reminder_{appointment['id']}")
# 2 horas antes
reminder_2h = appointment_time - timedelta(hours=2)
schedule.every().day.at(reminder_2h.strftime('%H:%M')).do(
self.send_2h_reminder, appointment
).tag(f"reminder_{appointment['id']}")
def send_24h_reminder(self, appointment):
message = f"""
🏥 *Lembrete de Consulta*
👋 Olá, {appointment['patient_name']}!
📅 *Amanhã às {appointment['time']}*
👨⚕️ {appointment['doctor']} - {appointment['specialty']}
📍 {appointment['location']}
⚠️ *Importante:*
• Chegue 15 minutos antes
• Traga RG e cartão do convênio
• Use máscara
✅ Para confirmar, digite: SIM
📞 Para reagendar, digite: NAO
❤️ Cuidamos da sua saúde!
""".strip()
self.client.send_message({
'type': 'API',
'mediaType': 'TEXT',
'content': message,
'phone': appointment['phone'],
'instanceId': appointment['instance_id']
})
Segurança - Confirmação OTP
Copiar
class OTPVerification {
constructor(apiZapClient) {
this.client = apiZapClient;
this.otpStorage = new Map(); // Em produção, use Redis/Database
this.otpExpiration = 5 * 60 * 1000; // 5 minutos
}
generateOTP() {
return Math.floor(100000 + Math.random() * 900000).toString();
}
async sendOTP(phone, purpose = 'verificação') {
const otp = this.generateOTP();
const expiresAt = Date.now() + this.otpExpiration;
// Armazenar OTP temporariamente
this.otpStorage.set(phone, {
code: otp,
expiresAt,
attempts: 0,
purpose
});
const message = `🔐 *Código de Verificação*
📱 Seu código para ${purpose}:
*${otp}*
⏰ *Válido por 5 minutos*
⚠️ *Importante:*
• Não compartilhe este código
• Use apenas no site oficial
• Código de uso único
🛡️ ApiZap - Sua segurança é nossa prioridade!`;
try {
const result = await this.client.sendMessage({
type: 'API',
mediaType: 'TEXT',
content: message,
phone: phone,
instanceId: process.env.INSTANCE_ID
});
console.log(`OTP enviado para ${phone}: ${result.id}`);
return { success: true, messageId: result.id, expiresAt };
} catch (error) {
console.error('Erro ao enviar OTP:', error);
this.otpStorage.delete(phone);
throw error;
}
}
verifyOTP(phone, userCode) {
const stored = this.otpStorage.get(phone);
if (!stored) {
return { success: false, error: 'Código não encontrado' };
}
if (Date.now() > stored.expiresAt) {
this.otpStorage.delete(phone);
return { success: false, error: 'Código expirado' };
}
if (stored.attempts >= 3) {
this.otpStorage.delete(phone);
return { success: false, error: 'Muitas tentativas. Solicite um novo código' };
}
if (stored.code !== userCode) {
stored.attempts++;
return { success: false, error: 'Código incorreto', attemptsLeft: 3 - stored.attempts };
}
// Código válido
this.otpStorage.delete(phone);
return { success: true, message: 'Número verificado com sucesso!' };
}
async sendVerificationSuccess(phone, userName = 'usuário') {
const message = `✅ *Verificação Concluída*
👋 Parabéns, ${userName}!
🎉 Seu número foi verificado com sucesso!
✨ Agora você pode:
• Fazer login com segurança
• Receber notificações importantes
• Acessar todos os recursos
🚀 Bem-vindo(a) à nossa plataforma!`;
return await this.client.sendMessage({
type: 'API',
mediaType: 'TEXT',
content: message,
phone: phone,
instanceId: process.env.INSTANCE_ID
});
}
}
// Exemplo de uso
const otpSystem = new OTPVerification(apiZapClient);
// Enviar OTP
await otpSystem.sendOTP('+5511999999999', 'cadastro na plataforma');
// Verificar OTP
const verification = otpSystem.verifyOTP('+5511999999999', '123456');
if (verification.success) {
await otpSystem.sendVerificationSuccess('+5511999999999', 'João');
}
Tratamento de Erros
Copiar
class ApiZapClient {
async sendWithRetry(data, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await this.sendMessage(data);
} catch (error) {
if (error.response?.status >= 500) {
// Erro do servidor - esperar antes de tentar novamente
const delay = Math.pow(2, attempt) * 1000; // Backoff exponencial
console.log(`Erro do servidor. Aguardando ${delay}ms...`);
await this.sleep(delay);
} else if (attempt === maxRetries) {
throw error;
} else {
console.log(`Tentativa ${attempt} falhou. Tentando novamente...`);
await this.sleep(1000 * attempt);
}
}
}
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
Próximo Passo: Após implementar o código, teste em ambiente de desenvolvimento antes de ir para produção. Use sempre as variáveis de ambiente para proteger suas credenciais.