PHP code example of sierratecnologia / integrations
1. Go to this page and download the library: Download sierratecnologia/integrations 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/ */
use Integrations\Services\IntegrationsService;
class IntegrationsService
{
public function __construct(array $config)
{
// Inicialização do serviço
}
// Métodos de negócio
}
namespace Integrations\Connectors\Facebook;
use Integrations\Connectors\Connector;
class Facebook extends Connector
{
protected static $ID = 'facebook';
protected function getConnection($token = false)
{
// Implementação específica do Facebook
}
}
use Integrations;
$data = Integrations::getData();
namespace Integrations\Connectors;
class Connector
{
protected $_connection = null;
protected $_token = null;
public function __construct($token = false)
{
$this->_token = $token;
$this->_connection = $this->getConnection($this->_token);
}
protected function getConnection($token = false)
{
return $this;
}
public function get($path)
{
// Implementação genérica de GET
}
public static function getCodeForPrimaryKey()
{
// Registra o conector no banco de dados
}
}
namespace Integrations\Models;
use Illuminate\Database\Eloquent\Model;
class Token extends Model
{
protected $table = 'integration_tokens';
protected $fillable = [
'integration_id',
'user_id',
'token',
'refresh_token',
'expires_at',
'scopes',
];
protected $casts = [
'expires_at' => 'datetime',
'scopes' => 'array',
];
// Relacionamentos
public function integration()
{
return $this->belongsTo(Integration::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
namespace Integrations\Services;
class IntegrationsService
{
protected $config;
public function __construct(array $config)
{
$this->config = $config;
\Log::channel('sitec-integrations')->info('IntegrationsService initialized');
}
// Métodos para gerenciar integrações
}
namespace Integrations\Http;
use Illuminate\Http\Request;
use Integrations\Exceptions\WebhookException;
class WebhookReceivedController extends Controller
{
public function handle(Request $request, string $service)
{
// Valida e processa o webhook
// Dispara eventos apropriados
}
}
use Muleta\Traits\Providers\ConsoleTools;
class IntegrationsProvider extends ServiceProvider
{
use ConsoleTools; // Registra comandos automaticamente
}
// Sincronizar produtos com marketplace externo
use Integrations\Connectors\Amazon\Amazon;
$amazon = new Amazon($token);
$amazon->syncProducts($marketProducts);
use Integrations\Connectors\Dropbox\Dropbox;
$dropbox = new Dropbox($token);
$file = $dropbox->upload($mediaFile);
use Integrations\Connectors\Facebook\Facebook;
$facebook = new Facebook($token);
$facebook->publishPost($article->title, $article->content);
// 1. Capturar lead do formulário
$lead = Lead::create($request->all());
// 2. Criar contato no Hubspot (CRM)
$hubspot = new Hubspot($crmToken);
$contact = $hubspot->createContact($lead->toArray());
// 3. Adicionar a lista de email marketing
$mailchimp = new Mailchimp($emailToken);
$mailchimp->addSubscriber($lead->email);
// 4. Notificar time de vendas no Slack
$slack = new Slack($slackToken);
$slack->sendMessage('#vendas', "Novo lead: {$lead->name}");
// 5. Criar task no Jira para follow-up
$jira = new Jira($jiraToken);
$jira->createTask([
'summary' => "Follow-up lead: {$lead->name}",
'assignee' => '[email protected]',
]);
namespace Integrations\Connectors\MeuServico;
class Create
{
protected $connector;
public function __construct($token)
{
$this->connector = new MeuServico($token);
}
public function resource(array $data)
{
return $this->connector->post('/resources', $data);
}
}
// Executar no boot do provider ou em um command
use Integrations\Models\Integration;
Integration::createIfNotExistAndReturn([
'id' => 'meu-servico',
'name' => 'Meu Serviço',
'code' => \Integrations\Connectors\MeuServico\MeuServico::class,
]);
namespace App\Traits;
trait CustomIntegrationBehavior
{
public function logActivity($message)
{
\Log::channel('custom')->info($message);
}
public function notifyOnError($exception)
{
// Notificar equipe
}
}
// Usar no conector
class MeuServico extends Connector
{
use CustomIntegrationBehavior;
}
class CustomJira extends \Integrations\Connectors\Jira\Jira
{
// Sobrescrever apenas o necessário
protected function getConnection($token = false)
{
// Lógica customizada
$connection = parent::getConnection($token);
// Adicionar configurações extras
$connection->setCustomConfig();
return $connection;
}
}
use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
class SyncContactsJob implements ShouldQueue
{
use Queueable, InteractsWithQueue;
public $tries = 3;
public $timeout = 120;
public function handle()
{
$hubspot = new Hubspot($this->token);
$hubspot->syncContacts();
}
}
use Illuminate\Support\Facades\Cache;
class CircuitBreaker
{
public function call($service, callable $callback)
{
$failureKey = "circuit_breaker:{$service}:failures";
$failures = Cache::get($failureKey, 0);
if ($failures >= 5) {
throw new \Exception("Circuit breaker aberto para {$service}");
}
try {
$result = $callback();
Cache::forget($failureKey);
return $result;
} catch (\Exception $e) {
Cache::put($failureKey, $failures + 1, now()->addMinutes(5));
throw $e;
}
}
}
use Illuminate\Support\Facades\Validator;
public function createContact(array $data)
{
$validator = Validator::make($data, [
'email' => 'row new \InvalidArgumentException(
'Dados inválidos: ' . $validator->errors()->first()
);
}
return $this->connector->post('/contacts', $data);
}
namespace App\Services;
use Integrations\Connectors\Jira\Jira;
use Integrations\Connectors\Jira\Create;
use Integrations\Connectors\Jira\Import;
use App\Models\Project;
use App\Models\Task;
class ProjectManagementService
{
protected $jira;
public function __construct()
{
$token = \Integrations\Models\Token::where('integration_id', 'jira')
->where('user_id', auth()->id())
->first();
$this->jira = new Jira($token);
}
public function syncProjectsFromJira()
{
$import = new Import($this->jira->getToken());
// Importar projetos
$jiraProjects = $import->allProjects();
foreach ($jiraProjects as $jiraProject) {
$project = Project::updateOrCreate(
['jira_key' => $jiraProject['key']],
[
'name' => $jiraProject['name'],
'description' => $jiraProject['description'],
'lead_id' => $this->findUserByEmail($jiraProject['lead']['email']),
]
);
// Importar issues do projeto
$this->syncTasksFromProject($project, $jiraProject['key']);
}
}
protected function syncTasksFromProject(Project $project, string $jiraKey)
{
$import = new Import($this->jira->getToken());
$issues = $import->fromProject($jiraKey);
foreach ($issues as $issue) {
Task::updateOrCreate(
['jira_id' => $issue['id']],
[
'project_id' => $project->id,
'title' => $issue['fields']['summary'],
'description' => $issue['fields']['description'],
'status' => $this->mapJiraStatus($issue['fields']['status']['name']),
'priority' => $issue['fields']['priority']['name'],
'assigned_to' => $this->findUserByEmail($issue['fields']['assignee']['email'] ?? null),
'due_date' => $issue['fields']['duedate'] ?? null,
]
);
}
}
public function createJiraIssueFromTask(Task $task)
{
$create = new Create($this->jira->getToken());
$issue = $create->execute([
'project' => $task->project->jira_key,
'summary' => $task->title,
'description' => $task->description,
'issuetype' => $this->mapTaskType($task->type),
'priority' => $task->priority,
'assignee' => $task->assignedUser->email ?? null,
]);
$task->update(['jira_id' => $issue['id']]);
return $issue;
}
}
namespace App\Services;
use Integrations\Connectors\Hubspot\Hubspot;
use Integrations\Connectors\Instagram\Instagram;
use Integrations\Connectors\Slack\Slack;
use App\Models\Lead;
use App\Models\Sale;
class MarketingAutomationService
{
protected $hubspot;
protected $instagram;
protected $slack;
public function __construct()
{
// Inicializar conectores
$this->hubspot = new Hubspot($this->getToken('hubspot'));
$this->instagram = new Instagram($this->getToken('instagram'));
$this->slack = new Slack($this->getToken('slack'));
}
public function processNewLead(array $data)
{
// 1. Criar lead no sistema
$lead = Lead::create($data);
// 2. Criar contato no Hubspot
$hubspotContact = $this->hubspot->createContact([
'email' => $lead->email,
'firstname' => $lead->first_name,
'lastname' => $lead->last_name,
'phone' => $lead->phone,
'lifecyclestage' => 'lead',
'lead_source' => $lead->source,
]);
$lead->update(['hubspot_id' => $hubspotContact['id']]);
// 3. Notificar equipe de vendas no Slack
$this->slack->sendMessage('#vendas', sprintf(
"🎯 *Novo Lead Qualificado*\n" .
"Nome: %s %s\n" .
"Email: %s\n" .
"Telefone: %s\n" .
"Origem: %s",
$lead->first_name,
$lead->last_name,
$lead->email,
$lead->phone,
$lead->source
));
return $lead;
}
public function trackInstagramCampaign(string $campaignId)
{
// Obter métricas da campanha
$metrics = $this->instagram->getPostMetrics($campaignId);
// Registrar no sistema
\App\Models\CampaignMetric::create([
'campaign_id' => $campaignId,
'platform' => 'instagram',
'impressions' => $metrics['impressions'],
'reach' => $metrics['reach'],
'engagement' => $metrics['engagement'],
'clicks' => $metrics['clicks'],
]);
// Notificar equipe de marketing
if ($metrics['engagement'] > 1000) {
$this->slack->sendMessage('#marketing', sprintf(
"🚀 *Campanha em Destaque!*\n" .
"ID: %s\n" .
"Engajamento: %d\n" .
"Alcance: %d",
$campaignId,
$metrics['engagement'],
$metrics['reach']
));
}
}
public function syncSalesWithHubspot()
{
$sales = Sale::whereNull('hubspot_deal_id')
->where('created_at', '>=', now()->subDays(7))
->get();
foreach ($sales as $sale) {
$deal = $this->hubspot->createDeal([
'dealname' => "Venda #{$sale->id}",
'amount' => $sale->total,
'dealstage' => $this->mapSaleStage($sale->status),
'pipeline' => 'default',
'closedate' => $sale->closed_at?->timestamp,
]);
$sale->update(['hubspot_deal_id' => $deal['id']]);
// Associar ao contato
if ($sale->lead && $sale->lead->hubspot_id) {
$this->hubspot->associateDealToContact(
$deal['id'],
$sale->lead->hubspot_id
);
}
}
}
}
namespace App\Services;
use Integrations\Connectors\Sentry\Sentry;
use Integrations\Connectors\Slack\Slack;
use Integrations\Connectors\Jira\Jira;
class ErrorMonitoringService
{
protected $sentry;
protected $slack;
protected $jira;
public function __construct()
{
$this->sentry = new Sentry($this->getToken('sentry'));
$this->slack = new Slack($this->getToken('slack'));
$this->jira = new Jira($this->getToken('jira'));
}
public function processErrorWebhook(array $data)
{
$error = $data['error'];
$severity = $error['level'];
// Notificar no Slack
$message = sprintf(
"🔴 *Erro %s Detectado*\n" .
"Mensagem: %s\n" .
"Ocorrências: %d\n" .
"Ambiente: %s\n" .
"Link: %s",
strtoupper($severity),
$error['message'],
$error['count'],
$error['environment'],
$error['url']
);
$this->slack->sendMessage('#tech-alerts', $message);
// Se for crítico, criar issue no Jira
if (in_array($severity, ['error', 'fatal'])) {
$this->jira->createIssue([
'project' => 'BUGS',
'summary' => "[{$severity}] {$error['message']}",
'description' => $this->formatErrorDescription($error),
'issuetype' => 'Bug',
'priority' => $severity === 'fatal' ? 'Critical' : 'High',
'labels' => ['auto-created', 'sentry', $error['environment']],
]);
}
}
protected function formatErrorDescription(array $error)
{
return sprintf(
"h2. Detalhes do Erro\n\n" .
"*Mensagem:* %s\n" .
"*Ocorrências:* %d\n" .
"*Ambiente:* %s\n" .
"*Primeira ocorrência:* %s\n" .
"*Última ocorrência:* %s\n\n" .
"h3. Stack Trace\n" .
"{code}\n%s\n{code}\n\n" .
"h3. Link no Sentry\n" .
"%s",
$error['message'],
$error['count'],
$error['environment'],
$error['first_seen'],
$error['last_seen'],
$error['stacktrace'],
$error['url']
);
}
}
src/Connectors/Stripe/
├── Stripe.php # Classe principal
├── Create.php # Criação de recursos
├── Update.php # Atualização de recursos
├── Import.php # Importação de dados
└── Webhook.php # Processamento de webhooks
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.