AsaasClient.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace App\Services\Integrations\Asaas;
  3. use App\Exceptions\AsaasException;
  4. use Illuminate\Http\Client\PendingRequest;
  5. use Illuminate\Support\Facades\Http;
  6. class AsaasClient
  7. {
  8. protected string $baseUrl;
  9. protected string $apiKey;
  10. public function __construct(?string $apiKey = null)
  11. {
  12. $this->baseUrl = config('services.asaas.base_url');
  13. // Chave explícita (ex.: conta da unidade) tem prioridade. Sem ela, usa a
  14. // chave da matriz resolvida do banco (UI) com fallback para o .env.
  15. $this->apiKey = $apiKey ?? \App\Models\CompanyPaymentAccount::resolveApiKey();
  16. }
  17. protected function request(): PendingRequest
  18. {
  19. return Http::withHeaders([
  20. 'access_token' => $this->apiKey,
  21. ])->baseUrl($this->baseUrl);
  22. }
  23. public function get(string $endpoint, array $query = [])
  24. {
  25. $response = $this->request()->get($endpoint, $query);
  26. if ($response->failed()) {
  27. throw new AsaasException($response);
  28. }
  29. return $response->json();
  30. }
  31. public function post(string $endpoint, array $data = [])
  32. {
  33. $response = $this->request()->post($endpoint, $data);
  34. if ($response->failed()) {
  35. throw new AsaasException($response);
  36. }
  37. return $response->json();
  38. }
  39. public function delete(string $endpoint)
  40. {
  41. $response = $this->request()->delete($endpoint);
  42. if ($response->failed()) {
  43. throw new AsaasException($response);
  44. }
  45. return $response->json();
  46. }
  47. }