AsaasWebhookService.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace App\Services\Integrations\Asaas;
  3. /**
  4. * Gerencia o webhook na conta Asaas PRÓPRIA da unidade (Franchisee).
  5. *
  6. * O webhook aponta para o nosso endpoint público e usa o token global
  7. * (ASAAS_WEBHOOK_TOKEN) — a identificação da unidade no evento vem do
  8. * externalReference (STU_...), não do token.
  9. */
  10. class AsaasWebhookService
  11. {
  12. private const EVENTS = [
  13. 'PAYMENT_RECEIVED',
  14. 'PAYMENT_CONFIRMED',
  15. 'PAYMENT_OVERDUE',
  16. 'PAYMENT_DELETED',
  17. 'PAYMENT_REFUNDED',
  18. ];
  19. /**
  20. * Valida a chave chamando um endpoint leve. Lança AsaasException se inválida.
  21. */
  22. public function validateKey(string $apiKey): void
  23. {
  24. $client = new AsaasClient($apiKey);
  25. // /myAccount só responde 200 com uma chave válida.
  26. $client->get('/myAccount');
  27. }
  28. /**
  29. * Registra o webhook na conta da unidade e retorna o id criado.
  30. */
  31. public function register(string $apiKey): string
  32. {
  33. $client = new AsaasClient($apiKey);
  34. $response = $client->post('/webhooks', [
  35. 'name' => 'Ginástica do Cérebro',
  36. 'url' => config('services.asaas.webhook_url'),
  37. 'email' => config('mail.from.address'),
  38. 'enabled' => true,
  39. 'interrupted' => false,
  40. 'authToken' => config('services.asaas.webhook_token'),
  41. 'sendType' => 'SEQUENTIALLY',
  42. 'events' => self::EVENTS,
  43. ]);
  44. return $response['id'];
  45. }
  46. /**
  47. * Remove o webhook da conta da unidade (best-effort).
  48. */
  49. public function delete(string $apiKey, string $webhookId): void
  50. {
  51. $client = new AsaasClient($apiKey);
  52. $client->delete("/webhooks/{$webhookId}");
  53. }
  54. }