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/ */

    

sierratecnologia / integrations example snippets


'providers' => [
    // ...
    Integrations\IntegrationsProvider::class,
],

'aliases' => [
    // ...
    'Integrations' => Integrations\Facades\Integrations::class,
],

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
    }
}

return [
    // ...

    'facebook' => [
        'client_id' => env('FACEBOOK_CLIENT_ID'),
        'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
        'redirect' => env('FACEBOOK_REDIRECT_URI'),
    ],

    'jira' => [
        'host' => env('JIRA_HOST'),
        'user' => env('JIRA_USER'),
        'token' => env('JIRA_TOKEN'),
    ],
];



namespace App\Http\Controllers;

use Integrations\Connectors\Jira\Jira;
use Integrations\Connectors\Jira\Create;
use Integrations\Connectors\Jira\Import;
use Integrations\Models\Token;

class JiraController extends Controller
{
    public function createIssue()
    {
        // Obter token do usuário autenticado
        $token = Token::where('integration_id', 'jira')
            ->where('user_id', auth()->id())
            ->first();

        // Inicializar conector
        $jira = new Jira($token);

        // Criar issue
        $create = new Create($token);
        $issue = $create->execute([
            'project' => 'PROJECT_KEY',
            'summary' => 'Nova tarefa criada via API',
            'description' => 'Descrição detalhada da tarefa',
            'issuetype' => 'Task',
            'priority' => 'High',
        ]);

        return response()->json($issue);
    }

    public function importIssues()
    {
        $token = Token::where('integration_id', 'jira')
            ->where('user_id', auth()->id())
            ->first();

        $import = new Import($token);

        // Importar issues do projeto
        $issues = $import->fromProject('PROJECT_KEY');

        // Processar issues
        foreach ($issues as $issue) {
            // Salvar no banco de dados local
            // ou processar conforme necessário
        }

        return response()->json([
            'message' => 'Issues importadas com sucesso',
            'count' => count($issues),
        ]);
    }
}



namespace App\Services;

use Integrations\Connectors\Hubspot\Hubspot;
use Integrations\Connectors\Hubspot\Create;
use Integrations\Connectors\Hubspot\Update;
use Integrations\Models\Token;

class CrmService
{
    protected $hubspot;

    public function __construct()
    {
        $token = Token::where('integration_id', 'hubspot')
            ->where('user_id', auth()->id())
            ->first();

        $this->hubspot = new Hubspot($token);
    }

    public function createContact(array $data)
    {
        $create = new Create($this->hubspot->getToken());

        return $create->contact([
            'email' => $data['email'],
            'firstname' => $data['first_name'],
            'lastname' => $data['last_name'],
            'phone' => $data['phone'],
            'company' => $data['company'],
        ]);
    }

    public function updateContact(string $contactId, array $data)
    {
        $update = new Update($this->hubspot->getToken());

        return $update->contact($contactId, $data);
    }

    public function syncContactsFromLeads()
    {
        $leads = \App\Models\Lead::whereNull('hubspot_id')
            ->where('status', 'qualified')
            ->get();

        foreach ($leads as $lead) {
            $contact = $this->createContact([
                'email' => $lead->email,
                'first_name' => $lead->first_name,
                'last_name' => $lead->last_name,
                'phone' => $lead->phone,
                'company' => $lead->company,
            ]);

            $lead->update(['hubspot_id' => $contact['id']]);
        }
    }
}

// routes/web.php
Route::post('/webhook/{service}', [
    \Integrations\Http\WebhookReceivedController::class,
    'handle'
])->name('integrations.webhook');



namespace App\Listeners;

use Illuminate\Support\Facades\Log;

class ProcessWebhookListener
{
    public function handle($event)
    {
        $service = $event->service;
        $payload = $event->payload;

        Log::channel('sitec-integrations')->info(
            "Webhook recebido de {$service}",
            ['payload' => $payload]
        );

        // Processar baseado no serviço
        switch ($service) {
            case 'jira':
                $this->processJiraWebhook($payload);
                break;
            case 'hubspot':
                $this->processHubspotWebhook($payload);
                break;
        }
    }

    protected function processJiraWebhook($payload)
    {
        // Lógica específica para Jira
    }
}

// Validar assinatura do webhook
public function validateWebhookSignature(Request $request, string $service)
{
    $signature = $request->header('X-Hub-Signature');
    $payload = $request->getContent();

    $secret = config("services.{$service}.webhook_secret");
    $expectedSignature = 'sha256=' . hash_hmac('sha256', $payload, $secret);

    if (!hash_equals($expectedSignature, $signature)) {
        throw new WebhookException('Invalid signature');
    }
}

use Illuminate\Support\Facades\Http;

// Configurar timeout e retry
$response = Http::timeout(30)
    ->retry(3, 100)
    ->withToken($token->token)
    ->get('https://api.service.com/endpoint');

// Usar canal dedicado
\Log::channel('sitec-integrations')->info('Integração iniciada', [
    'service' => 'jira',
    'user_id' => auth()->id(),
    'action' => 'create_issue',
]);

\Log::channel('sitec-integrations')->error('Falha na integração', [
    'service' => 'hubspot',
    'error' => $exception->getMessage(),
    'trace' => $exception->getTraceAsString(),
]);

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;

use Integrations\Connectors\Connector;
use GuzzleHttp\Client;

class MeuServico extends Connector
{
    protected static $ID = 'meu-servico';

    protected $client;
    protected $baseUrl = 'https://api.meuservico.com/v1';

    protected function getConnection($token = false)
    {
        $this->client = new Client([
            'base_uri' => $this->baseUrl,
            'headers' => [
                'Authorization' => "Bearer {$token->token}",
                'Content-Type' => 'application/json',
            ],
            'timeout' => 30,
        ]);

        return $this;
    }

    public function get($path)
    {
        try {
            $response = $this->client->get($path);
            return json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            $this->setError($e->getMessage(), $e->getCode());
        }
    }

    public function post($path, $data)
    {
        try {
            $response = $this->client->post($path, [
                'json' => $data,
            ]);
            return json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            $this->setError($e->getMessage(), $e->getCode());
        }
    }
}



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']
        );
    }
}
bash
# Publicar configurações
php artisan vendor:publish --tag=integrations-config

# Publicar views (opcional)
php artisan vendor:publish --tag=integrations-views

# Publicar traduções (opcional)
php artisan vendor:publish --tag=integrations-lang
bash
php artisan migrate
bash
src/Connectors/MeuServico/
├── MeuServico.php
├── Create.php
├── Update.php
└── Import.php

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