In this article, we add a contact through hubspot API with example code in PHP.
Hubspot provides a REST API to create contact. In this example, we are going to create a contact using Hubspot Contact API. We are going to consume the rest api in PHP using curl
You need API Key before sending the request. Here is how you can get your HAPI Key. Create the contact information in an array.
define("HAPI_KEY", "dxxxxxe7-1xx3-4xx8-9bxx-6xxxxx8dd3xx");
$arr = array(
'properties' => array(
array(
'property' => 'email',
'value' => $email
),
array(
'property' => 'firstname',
'value' => $fname
),
array(
'property' => 'lastname',
'value' => $lname
),
array(
'property' => 'phone',
'value' => $phone
)
)
);
$post_json = json_encode($arr);
$endpoint = 'https://api.hubapi.com/contacts/v1/contact?hapikey=' . HAPI_KEY;
The create a new contact endpoint is used to create a new contact in HubSpot. The new contact will be assigned a unique ID (vid), which can be used to look it up later.
Use case for this endpoint: This endpoint can be used to perform a one-time sync of new contacts from an external system into HubSpot.
$ch = @curl_init();
@curl_setopt($ch, CURLOPT_POST, true);
@curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
@curl_setopt($ch, CURLOPT_URL, $endpoint);
@curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = @curl_exec($ch);
$status_code = @curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errors = curl_error($ch);
@curl_close($ch);
$resp_json = json_decode($response);
$vid = $resp_json->vid;
To add additional information to the contact, we must call the Hubspot engagement API. Use this endpoint to create an engagement (an email, call, meeting, task or note) on an object in HubSpot.
// add note to contact
if(!isset($note)) {
$note = '';
}
$arr = array(
'engagement' => array(
'active' => true,
'ownerId' => 1,
'type' => 'NOTE',
'timestamp' => round(microtime(true) * 1000)
),
'associations' => array(
'contactIds' => array( $vid )
),
'metadata' => array(
'body' => $note
)
);
$post_json = json_encode($arr);
$endpoint = 'https://api.hubapi.com/engagements/v1/engagements?hapikey=' . HAPI_KEY;
$ch = @curl_init();
@curl_setopt($ch, CURLOPT_POST, true);
@curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
@curl_setopt($ch, CURLOPT_URL, $endpoint);
@curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = @curl_exec($ch);
$status_code = @curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errors = curl_error($ch);
@curl_close($ch);