You are here

public function WebhooksService::send in Webhooks 8

Send a webhook.

Parameters

\Drupal\webhooks\Entity\WebhookConfig $webhook_config: A webhook config entity.

\Drupal\webhooks\Webhook $webhook: A webhook object.

Overrides WebhookDispatcherInterface::send

1 call to WebhooksService::send()
WebhooksService::triggerEvent in src/WebhooksService.php
Trigger all webhook subscriptions associated with the given event.

File

src/WebhooksService.php, line 171

Class

WebhooksService
Class WebhookService.

Namespace

Drupal\webhooks

Code

public function send(WebhookConfig $webhook_config, Webhook $webhook) {
  $webhook
    ->setUuid($this->uuid
    ->generate());

  // Dispatch Webhook Send event.
  $this->eventDispatcher
    ->dispatch(WebhookEvents::SEND, new SendEvent($webhook_config, $webhook));
  $body = $this
    ->encode($webhook
    ->getPayload(), $webhook
    ->getMimeSubType());
  if ($secret = $webhook_config
    ->getSecret()) {
    $webhook
      ->setSecret($secret);
    $webhook
      ->setSignature($body);
  }
  try {
    $this->client
      ->post($webhook_config
      ->getPayloadUrl(), [
      'headers' => $webhook
        ->getHeaders(),
      'body' => $body,
      // Workaround for blocking local to local requests,
      // there will be 'Dispatch Failed' errors in the logs.
      'timeout' => strpos($webhook_config
        ->getPayloadUrl(), $this->requestStack
        ->getCurrentRequest()
        ->getHost()) ? 0.1 : 0,
    ]);
  } catch (\Exception $e) {
    $this->logger
      ->error('Dispatch Failed. Subscriber %subscriber on Webhook %uuid for Event %event: @message', [
      '%subscriber' => $webhook_config
        ->id(),
      '%uuid' => $webhook
        ->getUuid(),
      '%event' => $webhook
        ->getEvent(),
      '@message' => $e
        ->getMessage(),
      'link' => Link::createFromRoute($this
        ->t('Edit Webhook'), 'entity.webhook_config.edit_form', [
        'webhook_config' => $webhook_config
          ->id(),
      ])
        ->toString(),
    ]);
    $webhook
      ->setStatus(FALSE);
  }

  // Log the sent webhook.
  $this->logger
    ->info('Webhook Dispatched. Subscriber %subscriber on Webhook %uuid for Event %event. Payload: @payload', [
    '%subscriber' => $webhook_config
      ->id(),
    '%uuid' => $webhook
      ->getUuid(),
    '%event' => $webhook
      ->getEvent(),
    '@payload' => $this
      ->encode($webhook
      ->getPayload(), $webhook
      ->getMimeSubType()),
    'link' => Link::createFromRoute($this
      ->t('Edit Webhook'), 'entity.webhook_config.edit_form', [
      'webhook_config' => $webhook_config
        ->id(),
    ])
      ->toString(),
  ]);
}