Просмотр исходного кода

feat(asaas): service para validar chave e registrar/remover webhook da unidade

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
ebagabee 1 месяц назад
Родитель
Сommit
c889955537
1 измененных файлов с 61 добавлено и 0 удалено
  1. 61 0
      app/Services/Integrations/Asaas/AsaasWebhookService.php

+ 61 - 0
app/Services/Integrations/Asaas/AsaasWebhookService.php

@@ -0,0 +1,61 @@
+<?php
+
+namespace App\Services\Integrations\Asaas;
+
+/**
+ * Gerencia o webhook na conta Asaas PRÓPRIA da unidade (Franchisee).
+ *
+ * O webhook aponta para o nosso endpoint público e usa o token global
+ * (ASAAS_WEBHOOK_TOKEN) — a identificação da unidade no evento vem do
+ * externalReference (STU_...), não do token.
+ */
+class AsaasWebhookService
+{
+    private const EVENTS = [
+        'PAYMENT_RECEIVED',
+        'PAYMENT_CONFIRMED',
+        'PAYMENT_OVERDUE',
+        'PAYMENT_DELETED',
+        'PAYMENT_REFUNDED',
+    ];
+
+    /**
+     * Valida a chave chamando um endpoint leve. Lança AsaasException se inválida.
+     */
+    public function validateKey(string $apiKey): void
+    {
+        $client = new AsaasClient($apiKey);
+        // /myAccount só responde 200 com uma chave válida.
+        $client->get('/myAccount');
+    }
+
+    /**
+     * Registra o webhook na conta da unidade e retorna o id criado.
+     */
+    public function register(string $apiKey): string
+    {
+        $client = new AsaasClient($apiKey);
+
+        $response = $client->post('/webhooks', [
+            'name'        => 'Ginástica do Cérebro',
+            'url'         => config('services.asaas.webhook_url'),
+            'email'       => config('mail.from.address'),
+            'enabled'     => true,
+            'interrupted' => false,
+            'authToken'   => config('services.asaas.webhook_token'),
+            'sendType'    => 'SEQUENTIALLY',
+            'events'      => self::EVENTS,
+        ]);
+
+        return $response['id'];
+    }
+
+    /**
+     * Remove o webhook da conta da unidade (best-effort).
+     */
+    public function delete(string $apiKey, string $webhookId): void
+    {
+        $client = new AsaasClient($apiKey);
+        $client->delete("/webhooks/{$webhookId}");
+    }
+}