You are here

public function Hubspot::submitHubspotForm in HubSpot 8

Submit a hubspot form.

Parameters

string $form_guid: Hubspot Form GUID.

array $form_field_values: Hubspot submission values, keyed by hubspot form item id.

array $context: Options to pass to hubspot.

Return value

array The request response info.

Throws

\GuzzleHttp\Exception\GuzzleException

File

src/Hubspot.php, line 276

Class

Hubspot
Define a service for interacting with the HubSpot CRM.

Namespace

Drupal\hubspot

Code

public function submitHubspotForm(string $form_guid, array $form_field_values, array $context = []) : array {

  // Convert list values into semicolon separated lists.
  array_walk($form_field_values, function (&$value) {

    // Encode e-mail addresses.
    if (is_string($value) && $this->emailValidator
      ->isValid($value)) {
      $value = str_replace('%40', '@', urlencode($value));
    }
    if (is_array($value)) {
      $value = implode(';', $value);
    }
  });
  $portal_id = $this->config
    ->get('hubspot_portal_id');
  $api = 'https://forms.hubspot.com/uploads/form/v2/' . $portal_id . '/' . $form_guid;
  $url = Url::fromUri($api)
    ->toString();
  $hs_context = [
    'hutk' => $this->currentRequest->cookies
      ->get('hubspotutk') ?? '',
    'ipAddress' => $this->currentRequest
      ->getClientIp(),
    'pageName' => isset($context['pageName']) ? $context['pageName'] : '',
    'pageUrl' => $this->currentRequest->headers
      ->get('referer'),
  ];
  $hs_context = array_merge($hs_context, $context);
  $request_options = [
    RequestOptions::HEADERS => [
      'Content-Type' => 'application/x-www-form-urlencoded',
    ],
    RequestOptions::FORM_PARAMS => $form_field_values + [
      'hs_context' => Json::encode($hs_context),
    ],
  ];
  return $this
    ->request('POST', $url, $request_options);
}