File: //var/www/quadcode/app/Helpers/CalendlyHelper.php
<?php
namespace App\Helpers;
use Exception;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Psr\Log\LoggerInterface;
class CalendlyHelper
{
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
private static array $allowedMethods = [
self::METHOD_GET,
self::METHOD_POST,
];
private string $url;
private string $token;
private LoggerInterface $logger;
const LOG_CHANNEL = 'calendly';
const SCOPE_USER = 'user';
const SCOPE_ORGANIZATION = 'organization';
const EVENT_CREATED = 'invitee.created';
const EVENT_CANCELED = 'invitee.canceled';
const EVENT_INVITEE_NO_SHOW_CREATED = 'invitee_no_show.created';
const EVENT_ROUTING_FORM_SUBMISSION_CREATED = 'routing_form_submission.created';
public function __construct()
{
$this->url = env('CALENDLY_URL');
$this->token = env('CALENDLY_TOKEN');
$this->logger = Log::channel(self::LOG_CHANNEL);
}
public function check(): bool
{
return !empty($this->url) && !empty($this->token);
}
private function request(string $method, string $apiMethod, array $data = [])
{
if (empty($method) || !in_array($method, self::$allowedMethods)) {
throw new Exception('Undefined request method');
}
$http = Http::withToken($this->token);
$this->logger->info($apiMethod . ' request', $data);
$url = $this->url . $apiMethod;
switch ($method) {
case self::METHOD_GET:
$response = $http->get($url);
break;
case self::METHOD_POST:
$response = $http->post($url, $data);
break;
}
$response = $response->json();
$this->logger->info($apiMethod . ' response', $response);
return $response;
}
private function get(string $apiMethod)
{
return $this->request(self::METHOD_GET, $apiMethod);
}
private function post(string $apiMethod, array $data = [])
{
return $this->request(self::METHOD_POST, $apiMethod, $data);
}
public function me()
{
return $this->get('/users/me');
}
public function createWebhookSubscriptions(string $organizationId, string $url)
{
$data = [
'url' => $url,
'events' => [self::EVENT_CREATED],
'organization' => $this->url . '/organizations/' . $organizationId,
'scope' => self::SCOPE_ORGANIZATION,
];
return $this->post('/webhook_subscriptions', $data);
}
}