Untitled

 avatar
unknown
php
a year ago
2.6 kB
5
Indexable
<?php declare(strict_types=1);

namespace App\Support\Moloni;

use App\Support\Moloni\Concerns\BuildBaseRequest;
use App\Support\Moloni\Exceptions\MoloniConnectionGetTokenException;
use Exception;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class MoloniConnection
{
	//	use CanSendPostRequest;
	// use CanSendGetRequest;
	use BuildBaseRequest;

	public mixed $token;

	public function __construct(
		private readonly string $baseUrl,
		private readonly string $developerId,
		private readonly string $clientSecret,
		private readonly string $username,
		private readonly string $password,
		public readonly int     $companyId,
	)
	{

		if (empty($this->baseUrl)) {
			throw new Exception('Moloni base url is not set');
		}
		if (empty($this->developerId)) {
			throw new Exception('Moloni developer id is not set');
		}
		if (empty($this->clientSecret)) {
			throw new Exception('Moloni client secret is not set');
		}
		if (empty($this->username)) {
			throw new Exception('Moloni username is not set');
		}
		if (empty($this->password)) {
			throw new Exception('Moloni password is not set');
		}
		if (empty($this->companyId)) {
			throw new Exception('Moloni company id is not set');
		}

		if (Cache::has('moloni_token')) {
			$this->token = Cache::get('moloni_token');
		} else {
			$this->token = $this->getToken();
			Cache::put('moloni_token', $this->token, now()->addMinutes(50));
		}
	}

	public function getToken()
	{
		$url = "https://api.moloni.pt/v1/grant/?grant_type=password&client_id=$this->developerId&client_secret=$this->clientSecret&username=$this->username&password=$this->password";

		try {
			$response = Http::get($url)->json();
			if (Arr::has($response, 'error')) {
				throw new MoloniConnectionGetTokenException($response['error_description']);
			}
			return $response['access_token'];

		} catch (MoloniConnectionGetTokenException $e) {
			throw new Exception($e->getMessage());
		}

	}

	/**
	 * @param string $url
	 * @param array|null $payload
	 * @return Response
	 * @throws Exception
	 */
	public function post(string $url, ?array $payload = []): Response
	{
		try {
			$response = $this
				->withBaseUrl()
				->asForm()
				->post(
					url: $this->appendTokenToUrl($url),
					data: ['company_id' => $this->companyId] + $payload
				);
			return $response;
		} catch (Exception $e) {
			throw new Exception($e->getMessage());
		}
	}

	public function appendTokenToUrl(string $url): string
	{
		return $url . "/?access_token=$this->token&human_errors=true";
	}
}
Editor is loading...
Leave a Comment