1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-09-21 08:51:34 +02:00
invoiceninja/app/Jobs/Util/WebhookHandler.php

102 lines
2.6 KiB
PHP
Raw Normal View History

<?php
namespace App\Jobs\Util;
2020-08-24 13:53:22 +02:00
use GuzzleHttp\RequestOptions;
use App\Transformers\ArraySerializer;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use League\Fractal\Manager;
use League\Fractal\Resource\Item;
2020-07-06 13:22:36 +02:00
class WebhookHandler implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private $entity;
private $event_id;
/**
* Create a new job instance.
*
* @return void
*/
2020-08-24 13:53:22 +02:00
public function __construct($event_id, $entity)
{
$this->event_id = $event_id;
$this->entity = $entity;
}
/**
* Execute the job.
*
* @return void
*/
public function handle() :bool
{
2020-08-24 13:53:22 +02:00
if(!$this->entity->company || $this->entity->company->company_users->first()->is_migrating == true)
return true;
2020-07-06 13:42:42 +02:00
$subscriptions = \App\Models\Webhook::where('company_id', $this->entity->company_id)
->where('event_id', $this->event_id)
->get();
if(!$subscriptions || $subscriptions->count() == 0)
return true;
$subscriptions->each(function($subscription) {
$this->process($subscription);
});
return true;
}
private function process($subscription)
{
// generate JSON data
$manager = new Manager();
$manager->setSerializer(new ArraySerializer());
2020-08-24 13:53:22 +02:00
$class = sprintf('App\\Transformers\\%sTransformer', class_basename($this->entity));
$transformer = new $class();
$resource = new Item($this->entity, $transformer, $this->entity->getEntityType());
$data = $manager->createData($resource)->toArray();
$this->postData($subscription, $data, []);
}
private function postData($subscription, $data, $headers = [])
{
2020-08-24 13:53:22 +02:00
$base_headers = [
2020-08-24 13:53:22 +02:00
'Content-Length' => strlen(json_encode($data)),
'Accept' => 'application/json'
];
$client = new \GuzzleHttp\Client(['headers' => array_merge($base_headers, $headers)]);
2020-08-24 13:53:22 +02:00
$response = $client->post($subscription->target_url, [
2020-08-24 13:53:22 +02:00
RequestOptions::JSON => $data // or 'json' => [...]
]);
if ($response->getStatusCode() == 410 || $response->getStatusCode() == 200) {
$subscription->delete();
}
}
public function failed($exception)
{
2020-08-24 13:16:35 +02:00
info(print_r($exception->getMessage(),1));
2020-08-24 13:53:22 +02:00
}
}
2020-08-24 13:53:22 +02:00