event_id = $event_id; $this->entity = $entity; $this->company = $company; $this->includes = $includes; } /** * Execute the job. * * @return bool */ public function handle() { MultiDB::setDb($this->company->db); //If the company is disabled, or if on hosted, the user is not a paid hosted user return early if (! $this->company || $this->company->is_disabled || (Ninja::isHosted() && !$this->company->account->isPaidHostedClient())) { return true; } $subscriptions = Webhook::where('company_id', $this->company->id) ->where('event_id', $this->event_id) ->cursor() ->each(function ($subscription) { $this->process($subscription); }); } private function process($subscription) { $this->entity->refresh(); // generate JSON data $manager = new Manager(); $manager->setSerializer(new ArraySerializer()); $manager->parseIncludes($this->includes); $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 = []) { $base_headers = [ 'Content-Length' => strlen(json_encode($data)), 'Accept' => 'application/json', ]; $client = new Client(['headers' => array_merge($base_headers, $headers)]); try { $response = $client->post($subscription->target_url, [ RequestOptions::JSON => $data, // or 'json' => [...] ]); SystemLogger::dispatch( array_merge((array) $response, $data), SystemLog::CATEGORY_WEBHOOK, SystemLog::EVENT_WEBHOOK_SUCCESS, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->resolveClient(), $this->company ); if ($response->getStatusCode() == 429){ nlog("429 retry after 10 seconds internally"); sleep(10); $response = $client->post($subscription->target_url, [ RequestOptions::JSON => $data, // or 'json' => [...] ]); SystemLogger::dispatch( array_merge((array) $response, $data), SystemLog::CATEGORY_WEBHOOK, SystemLog::EVENT_WEBHOOK_SUCCESS, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->resolveClient(), $this->company ); } } catch (\Exception $e) { nlog("429 occurred in the expcetion handler"); nlog($e->getMessage()); SystemLogger::dispatch( $e->getMessage(), SystemLog::CATEGORY_WEBHOOK, SystemLog::EVENT_WEBHOOK_RESPONSE, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->resolveClient(), $this->company, ); } } private function resolveClient() { //make sure it isn't an instance of the Client Model if ((! $this->entity instanceof ClientModel) && $this->entity->client()->exists()) { return $this->entity->client; } return $this->company->clients()->first(); } public function failed($exception) { sleep(2); nlog(print_r($exception->getMessage(), 1)); } }