I need each time a contact is registered to create a record in an external service. For this purpose I have created the following hook
public/legacy/custom/modules/Contacts/logic_hooks.php
$hook_array['after_save'][] = [
'2',
'Create contact in External service',
'custom/modules/Contacts/logic_hooks/ExternalService.php',
'ExternalService',
'create_contact'
];
<?php
class ExternalService
{
public function create_contact($bean, $event, $arguments)
{
$api = new \name\external_service();
$data = [
"attributes" => [
'FNAME' => $bean->first_name,
'LNAME' => $bean->last_name,
"COUNTRY" => $bean->primary_address_country,
"CITY" => $bean->primary_address_city,
],
"updateEnabled" => false,
"email" => $bean->email,
"ext_id" => "10"
];
$api->createContact($data);
}
}
External service
<?php
namespace brevo;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
class brevo
{
private string $base_url;
private string $api_key;
private Client $client;
public function __construct()
{
global $sugar_config;
$this->base_url = $sugar_config['es']['base_url'];
$this->api_key = $sugar_config['es']['api_key'];
$this->client = new Client([
'base_uri' => $this->base_url,
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'api-key' => $this->api_key,
]
]);
}
public function createContact(array $data): string
{
$endpoint = '/contacts';
try {
$response = $this->client->post('https://api.es.com/v3/contacts', [
'json' => $data
]);
if ($response->getStatusCode() === 201) {
return "Contact created successfully";
}
return "Failed to create contact. Status code " . $response->getStatusCode();
} catch (RequestException $e) {
return "RequestException caught: " . $e->getMessage();
} catch (GuzzleException $e) {
return "GuzzleException caught: " . $e->getMessage();
}
}
}
The problem is that I need the email but when I try to get it from the $bean in the hook there is no value.
How do I get the contact’s main email in an after_save hook?
Thanks in advance