| Server IP : 162.214.74.102 / Your IP : 216.73.216.192 Web Server : Apache System : Linux dedi-4363141.lrsys.com.br 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64 User : lrsys ( 1015) PHP Version : 5.6.40 Disable Function : exec,passthru,shell_exec,system MySQL : ON | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /home/lrsys/www/lrsys_apps/leo/application/plugins/module_imobles/helpers/hubspot/ |
Upload File : |
<?php
use Zend\Validator\StringLength;
include_once __DIR__ . "/../LeadsManagementHelper.php";
class hubspotHelper {
protected $huspost_key = '2149faed-582c-48fa-950e-01d9cd403b06';
public function updateContactProperties($hsContactid, $data, $update = false) {
// Verifico os valores de cada propriedade
$properties = null;
$arr_properties = array();
$return = array("error" => null, "msg" => null, "data" => null);
foreach($data as $key => $value){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.hubapi.com/properties/v1/contacts/properties/named/'.$key,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
$jsonResponse = json_decode($response);
if(isset($jsonResponse->status) && $jsonResponse->status == "error"){
$return["error"] = true;
$return["msg"] = $jsonResponse->message;
} elseif(isset($jsonResponse->name) && $jsonResponse->name == $key) {
$type = $jsonResponse->type;
$fieldType = $jsonResponse->fieldType;
$options = $jsonResponse->options;
$arr_properties[$key] = array("type" => $type, "fieldType" => $fieldType, "options" => $options);
} else {
$return["error"] = true;
$return["msg"] = "Algo de inesperado aconteceu. Entre em contato com o webmaster.";
}
if($return["error"] === true){
return $return;
}
$properties .= $key.",";
}
$properties = substr($properties,0,-1);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.hubapi.com/crm/v3/objects/contacts/'.$hsContactid.'?properties='.$properties,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
$jsonResponse = json_decode($response);
if(isset($jsonResponse->status) && $jsonResponse->status == "error"){
$return["error"] = true;
$return["msg"] = $jsonResponse->message;
} elseif(isset($jsonResponse->id) && $jsonResponse->id == $hsContactid) {
foreach($jsonResponse->properties as $key => $value){
if(isset($arr_properties[$key])){
if(!empty($value)){
if($update === true){
if($arr_properties[$key]["fieldType"] == "checkbox"){
$propertiesOptions = explode(";", $value);
if(!in_array($data[$key],$propertiesOptions))
{
$data[$key] = $value.";".$data[$key];
}
else{
unset($data[$key]);
}
}
} else {
unset($data[$key]);
}
}
}
}
} else {
$return["error"] = true;
$return["msg"] = "Algo de inesperado aconteceu. Entre em contato com o webmaster.";
}
if($return["error"] === true){
return $return;
}
$postData = array("properties" => $data);
$postData = json_encode($postData);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.hubapi.com/crm/v3/objects/contacts/'.$hsContactid,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try{
$jsonResponse = json_decode($response);
if(isset($jsonResponse->status) && $jsonResponse->status == "error"){
$return["error"] = true;
$return["msg"] = $jsonResponse->message;
} elseif(isset($jsonResponse->id) && $jsonResponse->id == $hsContactid) {
$return["error"] = false;
$return["data"] = $jsonResponse;
} else {
$return["error"] = true;
$return["msg"] = "Algo de inesperado aconteceu. Entre em contato com o webmaster.";
}
}
catch (Exception $e) {
$return["error"] = true;
$return["msg"] = "Exception: ".$e->getMessage();
}
return $return;
}
public function hubspotGetUserByDeal($objectId) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.hubapi.com/crm/v3/objects/deals/'.$objectId.'/associations/contacts?limit=500',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try {
$hsUserId = null;
$response = json_decode($response);
if(isset($response->results) && count($response->results) > 0)
{
$hsUserId = $response->results[0]->id;
}
return $hsUserId;
}
catch (Exception $e) {
return false;
}
}
public function hubspotSyncLead($crm_account_id, $data = null, $crawlerController = null) {
$leadsHelper = new LeadsManagementHelper;
$lead = ORM::for_table('crm_accounts')->find_one($crm_account_id);
if(!isset($lead->id)){
$return = array("success" => false, "type" => "crm_contact_not_found");
return $return;
} elseif (preg_match_all("/(\s)+((test)e?)$|^((test)e?)(\s)+|(\s)+((test)e?)(\s)+|^((test)e?)$/i", $lead->account, $matches)) {
return true;
}
if(isset($data->input_data->client_details->phone) && !empty($data->input_data->client_details->phone)){
$lead->phone = $data->input_data->client_details->phone->country_code.$data->input_data->client_details->phone->number;
} else {
if(!empty($lead->phone)){
$lead->phone = preg_replace('/\D/', '', $lead->phone);
$lead->save();
} else {
return false;
}
}
$country_code = substr($lead->phone, 0, 2);
$phone_number = substr($lead->phone,2);
$phone_number_short = null;
$hs_contact_id = false;
if($country_code == 55)
{
if(strlen($phone_number) <= 10)
{
$ddd = substr($phone_number, 0, 2);
$phone_number = substr($phone_number,2);
if(in_array($phone_number[0],[9,8,7]))
{
$phone_number_short = $country_code.$ddd.$phone_number;
$phone_number = '9'.$phone_number;
}
$phone_number = $ddd.$phone_number;
} else {
$ddd = substr($phone_number, 0, 2);
$phone_number_aux = substr($phone_number,3);
if(in_array($phone_number_aux[0],[9,8,7]))
{
$phone_number_short = $country_code.$ddd.$phone_number_aux;
}
}
}
$hs_contacts_details = $leadsHelper->hubspotGetLeadByPhone($country_code.$phone_number);
if(isset($hs_contacts_details->vid))
{
$hs_contact_id = $hs_contacts_details->vid;
// echo $lead->account.' | '.$lead->id.' | '.$hs_contacts_details->vid.' | '.$phone_number." | SINCRONIZADO\n";
ORM::for_table('module_imobles_hubspot_contacts')->where('crm_account_id', $crm_account_id)->delete_many();
$lesdConParams = ORM::for_table('module_imobles_hubspot_contacts')->create();
$lesdConParams->hs_object_id = $hs_contacts_details->vid;
$lesdConParams->crm_account_id = $crm_account_id;
$lesdConParams->save();
}
elseif($phone_number_short !== null)
{
$hs_contacts_details = $leadsHelper->hubspotGetLeadByPhone($phone_number_short);
if(isset($hs_contacts_details->vid))
{
$hs_contact_id = $hs_contacts_details->vid;
// echo $lead->account.' | '.$lead->id.' | '.$hs_contacts_details->vid.' | '.$phone_number." | SINCRONIZADO\n";
ORM::for_table('module_imobles_hubspot_contacts')->where('crm_account_id', $crm_account_id)->delete_many();
$lesdConParams = ORM::for_table('module_imobles_hubspot_contacts')->create();
$lesdConParams->hs_object_id = $hs_contacts_details->vid;
$lesdConParams->crm_account_id = $crm_account_id;
$lesdConParams->save();
}
}
// Cadastrar o lead no DIGISAC e fazer o envio da mensagem automática
if(isset($data->input_data->client_details->first_name) && $data->input_data->client_details->first_name != ''){
$digsac = $leadsHelper->digisac($lead, $data->input_data->client_details->first_name, $lead->phone, null, $crawlerController, $data, $phone_number_short);
if(count($digsac) > 0){
$params = array('type' => 'error', 'msg' => 'DigiSac Controller Error', 'return' => $digsac);
$lesdConParams = ORM::for_table('module_imobles_logs')->create();
$lesdConParams->created_at = date('Y-m-d H:i:s');
$lesdConParams->type = 'digisac_controller_error';
$lesdConParams->params = json_encode($params);
$lesdConParams->save();
}
}
if($hs_contact_id === false){
$return = array("success" => false, "type" => "hubspot_sync_phone_not_found");
return $return;
} else {
$this->updateSinglePropertie($hs_contact_id, 'link_rocket', 'https://rocket.myside.com.br/?ng=contacts/view/'.$crm_account_id.'/module_imobles_leads_control');
if(!empty($lead->phone)){
$this->updateSinglePropertie($hs_contact_id, 'telefone_para_campanha_de_whatsapp', $lead->phone);
}
$update_deal = false;
if(!empty($data->conversion_id)){
$this->updateSinglePropertie($hs_contact_id, 'rocket_conversion_id', $data->conversion_id);
$update_deal = true;
// Mudo o status do Deal no Hubspot
}
// verifico se tem Deal aberto
$send_wiserads = true;
$hs_contacts_deals = $leadsHelper->hubspotGetDeals($hs_contact_id);
$hs_deal_id = null;
if(!empty($hs_contacts_deals))
{
foreach($hs_contacts_deals as $hs_deal)
{
if($hs_deal->properties->status_do_deal == 'Aberto - Conversando')
{
$deal_aux = ORM::for_table('module_imobles_leads_wiserleads_contacts')
->where('hs_deal_id', $hs_deal->id)
->find_one();
if(isset($deal_aux->id)){
$send_wiserads = false;
} else {
$hs_deal_id = intval($hs_deal->id);
}
// Faço a importação do Deal para o Rocket
// TODO: verificar a necessidade dessa importação
// $this->hubspotImportOpenDeal($hs_deal_id);
}
if($hs_deal->properties->status_do_deal == 'SYNC' && $update_deal == true)
{
$data_aux['status_do_deal'] = 'Aberto - Conversando';
$hs_update = $this->hubspotUpdateDealProperties($hs_deal->id, $data_aux);
}
}
}
$wl_data = null;
if(isset($data->wl_data) && !empty($data->wl_data)){
if($send_wiserads === true){
$wl_data = $data->wl_data;
$wiserLeads = new WiserLeadsHelper();
$results = $wiserLeads->postLead($wl_data);
if(isset($results->lead_id) && !empty($results->lead_id)){
$lesdConParams = ORM::for_table('module_imobles_leads_wiserleads_contacts')->create();
$lesdConParams->wiserlead_id = $results->lead_id;
$lesdConParams->crm_account_id = $crm_account_id;
$lesdConParams->hs_deal_id = $hs_deal_id;
$lesdConParams->save();
if($hs_deal_id === null){
$params = array('type' => 'warning', 'msg' => 'Deal ID not found');
$lesdConParams = ORM::for_table('module_imobles_logs')->create();
$lesdConParams->created_at = date('Y-m-d H:i:s');
$lesdConParams->type = 'wiser_leads_deal_error';
$lesdConParams->params = json_encode($params);
$lesdConParams->save();
}
} else {
$lesdConParams = ORM::for_table('module_imobles_logs')->create();
$lesdConParams->created_at = date('Y-m-d H:i:s');
$lesdConParams->type = 'wiser_leads_error';
$lesdConParams->params = json_encode(json_decode($wl_data));
$lesdConParams->save();
}
}
}
return true;
}
}
public function handleLogErros($crawlerController) {
$dataAtual = new DateTime();
$dataAtual->modify('-5 minutes');
$date_aux = $dataAtual->format('Y-m-d H:i:s');
$logs = ORM::for_table('module_imobles_logs')
->where('type', 'hubspot_contact_sync_error')
->where('verified', 0)
->where_lte('created_at', $date_aux)
->find_many();
foreach($logs as $log){
$data = json_decode($log->params);
if(isset($data->crm_account_id)){
$response = $this->hubspotSyncLead($data->crm_account_id, $data, $crawlerController);
if($response === true){
$log->verified = 1;
$log->save();
echo "CONTATO SINCRONIZADO\n";
} elseif(isset($response['type'])){
$log->type = $response['type'];
$log->save();
echo "TIPO DE LOG ANTERADO | TELEFONE NÃO ENCONTRADO NO HUBSPOT";
}
}
}
}
public function hubspotGetDealAssociations($objectId) {
$leadsHelper = new LeadsManagementHelper;
$curl = curl_init();
$url = "https://api.hubapi.com/crm/v3/objects/deals/".$objectId."?associations=note,task,call&archived=true";
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try {
$response = json_decode($response);
$notes_arr = array();
$calls_arr = array();
$tasks_arr = array();
if(isset($response->id) && $response->id > 0)
{
if(isset($response->associations->notes->results) && count($response->associations->notes->results) > 0)
{
foreach($response->associations->notes->results as $d){
$data = $this->hubspotGetNote($d->id);
if(isset($data->id) && $data->id > 0){
$owner = $leadsHelper->hubspotGetOwnerById($data->properties->hubspot_owner_id);
if(isset($owner->firstName)){
$owner_name = $owner->firstName.' '.$owner->lastName;
} else {
$owner_name = 'USUÁRIO DELETADO';
}
$notes_arr[] = array('hs_createdate' => date('Y-m-d H:i:s', strtotime($data->properties->hs_createdate)),
'hs_note_body' => @$data->properties->hs_note_body,
'hs_owner' => $owner_name);
}
}
}
if(isset($response->associations->calls->results) && count($response->associations->calls->results) > 0)
{
foreach($response->associations->calls->results as $d){
$data = $this->hubspotGetCall($d->id);
if(isset($data->id) && $data->id > 0){
$owner = $leadsHelper->hubspotGetOwnerById($data->properties->hubspot_owner_id);
if(isset($owner->firstName)){
$owner_name = $owner->firstName.' '.$owner->lastName;
} else {
$owner_name = 'USUÁRIO DELETADO';
}
$calls_arr[] = array('hs_createdate' => date('Y-m-d H:i:s', strtotime($data->properties->hs_createdate)),
'hs_call_recording_url' => @$data->properties->hs_call_recording_url,
'hs_call_duration' => @$data->properties->hs_call_duration,
'hs_owner' => $owner_name);
}
}
}
if(isset($response->associations->tasks->results) && count($response->associations->tasks->results) > 0)
{
foreach($response->associations->tasks->results as $d){
$data = $this->hubspotGetTask($d->id);
if(isset($data->id) && $data->id > 0){
$owner = $leadsHelper->hubspotGetOwnerById($data->properties->hubspot_owner_id);
if(isset($owner->firstName)){
$owner_name = $owner->firstName.' '.$owner->lastName;
} else {
$owner_name = 'USUÁRIO DELETADO';
}
$tasks_arr[] = array('hs_createdate' => date('Y-m-d H:i:s', strtotime($data->properties->hs_createdate)),
'hs_task_body' => @$data->properties->hs_task_body,
'hs_task_type' => @$data->properties->hs_task_type,
'hs_task_priority' => @$data->properties->hs_task_priority,
'hs_duedate' => date('Y-m-d H:i:s', strtotime($data->properties->hs_timestamp)),
'hs_owner' => $owner_name);
}
}
}
}
$return = array('notes' => $notes_arr,
'calls' => $calls_arr,
'tasks' => $tasks_arr);
return $return;
}
catch (Exception $e) {
return false;
}
}
public function hubspotGetTask($objectId) {
$curl = curl_init();
$url = "https://api.hubapi.com/crm/v3/objects/tasks/".$objectId."?properties=hs_task_body,hs_timestamp,hubspot_owner_id,hs_task_subjec,hs_task_statust,hs_task_priority,hs_task_type,hs_task_subject,hs_task_status";
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try {
$response = json_decode($response);
if(isset($response->id) && $response->id > 0)
if(isset($response->id) && $response->id > 0)
{
return $response;
} else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
public function hubspotGetCall($objectId) {
$curl = curl_init();
$url = "https://api.hubapi.com/crm/v3/objects/calls/".$objectId."?properties=hubspot_owner_id,hs_call_body,hs_call_duration,hs_call_recording_url,hs_call_disposition,hs_timestamp";
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try {
$response = json_decode($response);
if(isset($response->id) && $response->id > 0)
{
return $response;
} else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
public function hubspotGetNote($objectId) {
$curl = curl_init();
$url = "https://api.hubapi.com/crm/v3/objects/notes/".$objectId."?properties=hs_note_body,hs_attachment_ids,hubspot_owner_id,hs_timestamp";
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try {
$hsUserId = null;
$response = json_decode($response);
if(isset($response->id) && $response->id > 0)
{
return $response;
} else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
public function hubspotCreateNote($objectId, $crm_account_id) {
$curl = curl_init();
$post_data = '{
"properties": {
"hs_timestamp": "'.date('Y-m-d').'T'.date('H:i:s').'Z",
"hs_note_body": "LINK NO ROCKET: https://rocket.myside.com.br/?ng=contacts/view/'.$crm_account_id.'",
"hubspot_owner_id": "53025503"
},
"associations": [
{
"to": {
"id": '.$objectId.'
},
"types": [
{
"associationCategory": "HUBSPOT_DEFINED",
"associationTypeId": 202
}
]
}
]
}';
$url = "https://api.hubapi.com/crm/v3/objects/notes";
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $post_data,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try {
$hsUserId = null;
$response = json_decode($response);
if(isset($response->id) && $response->id > 0)
{
return $response;
} else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
public function updateSinglePropertie($hsContactid, $propertie, $value) {
$postData = array("properties" => array($propertie => $value));
$postData = json_encode($postData);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.hubapi.com/crm/v3/objects/contacts/'.$hsContactid,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try{
$jsonResponse = json_decode($response);
if(isset($jsonResponse->status) && $jsonResponse->status == "error"){
$return["error"] = true;
$return["msg"] = $jsonResponse->message;
} elseif(isset($jsonResponse->id) && $jsonResponse->id == $hsContactid) {
$return["error"] = false;
$return["data"] = $jsonResponse;
} else {
$return["error"] = true;
$return["msg"] = "Algo de inesperado aconteceu. Entre em contato com o webmaster.";
}
}
catch (Exception $e) {
$return["error"] = true;
$return["msg"] = "Exception: ".$e->getMessage();
}
return $return;
}
public function hubspotGetOpenDeals() {
$continue = true;
$limit = 100;
$offset = 0;
$arr_deals = array();
while($continue === true){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.hubapi.com/crm/v3/objects/deals/search',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => '{
"sorts": [
{
"propertyName": "createdate",
"direction": "ASCENDING"
}
],
"limit": '.$limit.',
"after": '.$offset.',
"properties": [ "engajado_", "evento_de_passagem_vgv_potencial", "espelhamento___escolha_do_cliente","primeiro_contato","engajado_", "data_entrada_na_ultima_etapa", "status_do_deal", "dono_do_lead__sdr_","motivo_da_perda_do_negocio","origem___nutricao_vs_site","dealstage"],
"filterGroups": [
{
"filters": [
{
"propertyName": "status_do_deal",
"operator": "EQ",
"value": "Aberto - Conversando"
},
{
"propertyName": "pipeline",
"operator": "IN",
"values": ["default",9881350]
}
]
}
]
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try {
$response = json_decode($response);
if(isset($response->results))
{
if(count($response->results) < $limit){
$continue = false;
}
$arr_deals = array_merge($arr_deals,$response->results);
}
}
catch (Exception $e) {
return false;
}
$offset = $offset + $limit;
}
foreach($arr_deals as $deal){
$this->hubspotImportOpenDeal($deal->id);
echo "ATENDIMENTO IMPORTADO COM SUCESSO |".$deal->id."\n";
}
}
public function hubspotImportOpenDeal($hs_deal_id, $sales_automation = false) {
$hs_contact_id = $this->hubspotGetUserByDeal($hs_deal_id);
$client_aux = ORM::for_table('module_imobles_hubspot_contacts')->where('hs_object_id', $hs_contact_id)->find_one();
if(isset($client_aux->crm_account_id)){
$crm_account_id = $client_aux->crm_account_id;
} else {
echo "LEAD NÃO CADASTRADO NO ROCKET | ".$hs_contact_id."\n";
$request_payload = '[
{
"subscriptionType": "contact.creation",
"objectId": '.$hs_contact_id.',
"changeFlag": "CREATED",
"changeSource": "FORM"
}
]';
$url = 'https://rocket.myside.com.br/?ng=api&key=787vrygo5tsuqvq6xn7bcjexxe63dppanmw5b3j6&method=plugin&plugin=module_imobles&pl_method=mandeUmZapHubspot';
$apiRequest = curl_init($url);
curl_setopt($apiRequest, CURLOPT_RETURNTRANSFER, true);
curl_setopt($apiRequest, CURLOPT_POST, 1);
curl_setopt($apiRequest, CURLOPT_POSTFIELDS, $request_payload);
$json_response = curl_exec($apiRequest);
$result_aux = json_decode($json_response);
if(!empty($result_aux->results->client_id)){
$crm_account_id = $result_aux->results->client_id;
} else {
echo "### ".$result_aux->results->msg." | ".$hs_contact_id."\n";
return false;
}
$client_aux = ORM::for_table('module_imobles_hubspot_contacts')->where('hs_object_id', $hs_contact_id)->find_one();
if(empty($client_aux->crm_account_id)){
// Vinculo o Rocket ao HS
ORM::for_table('module_imobles_hubspot_contacts')->where('crm_account_id', $crm_account_id)->delete_many();
$lesdConParams = ORM::for_table('module_imobles_hubspot_contacts')->create();
$lesdConParams->hs_object_id = $hs_contact_id;
$lesdConParams->crm_account_id = $crm_account_id;
$leads = $lesdConParams->save();
}
}
$deal_details = $this->hubspotGetDealDetails($hs_deal_id);
if(!isset($deal_details->id)){
return false;
}
$is_new = false;
$deal_aux = ORM::for_table('module_imobles_deals')->where('hs_deal_id', $hs_deal_id)->where_null('deleted_at')->find_one();
if(!empty($deal_aux->id)){
$deal_id = $deal_aux->id;
// echo "ATENDIMENTO JÁ REGISTRADO | ".$deal_id."\n";
// return false;
} else {
$deal_aux = ORM::for_table('module_imobles_deals')->create();
$is_new = true;
}
$deal_aux->hs_deal_id = intval($hs_deal_id);
$deal_aux->crm_account_id = $crm_account_id;
$deal_aux->title = $deal_details->properties->dealname;
$deal_aux->save();
if(!empty($deal_details->properties->data_entrada_na_ultima_etapa)){
$deal_aux->stage_update_at = date('Y-m-d H:i:s', strtotime($deal_details->properties->data_entrada_na_ultima_etapa));
}
if(!empty($deal_details->properties->createdate)){
$deal_aux->created_at = date('Y-m-d H:i:s', strtotime($deal_details->properties->createdate));
}
if(!empty($deal_details->properties->hs_lastmodifieddate)){
$deal_aux->updated_at = date('Y-m-d H:i:s', strtotime($deal_details->properties->hs_lastmodifieddate));
}
if(!empty($deal_details->properties->data_criacao_da_opp__sales_pipeline_)){
$deal_aux->opp_created_at = date('Y-m-d H:i:s', strtotime($deal_details->properties->data_criacao_da_opp__sales_pipeline_));
}
if(!empty($deal_details->properties->espelhamento___escolha_do_cliente)){
$deal_aux->first_choice = $deal_details->properties->espelhamento___escolha_do_cliente;
}
if(!empty($deal_details->properties->engajado_)){
if($deal_details->properties->engajado_ == 'true'){
$deal_aux->engagement_id = 2;
} else if($deal_details->properties->engajado_ == 'false'){
$deal_aux->engagement_id = 1;
}
}
if(!empty($deal_details->properties->evento_de_passagem_vgv_potencial)){
if($deal_details->properties->evento_de_passagem_vgv_potencial == "GYN - Até R$ 500 mil"){
$deal_aux->vgv_id = 1;
} else if($deal_details->properties->evento_de_passagem_vgv_potencial == "GYN - Até R$ 1 milhão"){
$deal_aux->vgv_id = 2;
} else if($deal_details->properties->evento_de_passagem_vgv_potencial == "GYN - Acima de R$ 1 milhão"){
$deal_aux->vgv_id = 3;
} else if($deal_details->properties->evento_de_passagem_vgv_potencial == "BCU - Até R$ 750 mil"){
$deal_aux->vgv_id = 4;
} else if($deal_details->properties->evento_de_passagem_vgv_potencial == "BCU - Até R$ 1,5 milhão"){
$deal_aux->vgv_id = 5;
} else if($deal_details->properties->evento_de_passagem_vgv_potencial == "BCU - Acima de R$ 1,5 milhão"){
$deal_aux->vgv_id = 6;
}
}
if(!empty($deal_details->properties->amount)){
$deal_aux->deal_amount = floatval($deal_details->properties->amount);
}
if(!empty($deal_details->properties->status_do_deal)){
if($deal_details->properties->status_do_deal == 'Aberto - Conversando'){
$deal_aux->status_id = 1;
} else if($deal_details->properties->status_do_deal == 'Fechado'){
$deal_aux->status_id = 2;
} else if($deal_details->properties->status_do_deal == 'Aberto - Parou de Responder'){
$deal_aux->status_id = 3;
} else if($deal_details->properties->status_do_deal == 'Aberto - Vendido'){
$deal_aux->status_id = 4;
}
}
if(isset($deal_aux->status_id) && $deal_aux->status_id != 1){
if(!empty($deal_details->properties->closedate)){
$deal_aux->closed_at = date('Y-m-d H:i:s', strtotime($deal_details->properties->closedate));
} else {
$deal_aux->closed_at = date('Y-m-d H:i:s');
}
} else {
// $deal_aux->closed_at = null;
}
if(!empty($deal_details->properties->origem___nutricao_vs_site)){
if(preg_match('/(bcu)/', mb_strtolower($deal_details->properties->origem___nutricao_vs_site))){
$deal_aux->service_region_id = 2;
} else {
$deal_aux->service_region_id = 1;
}
}
if(!empty($deal_details->properties->primeiro_contato)){
if(preg_match('/(Vídeo Chamada)/', ($deal_details->properties->primeiro_contato))){
$deal_aux->first_contact_id = 1;
} else if(preg_match('/(Ligação Telefônica)/', ($deal_details->properties->primeiro_contato))){
$deal_aux->first_contact_id = 2;
} else if(preg_match('/(Mensagem de WhatsApp)/', ($deal_details->properties->primeiro_contato))){
$deal_aux->first_contact_id = 3;
} else if(preg_match('/(Sem Contato)/', ($deal_details->properties->primeiro_contato))){
$deal_aux->first_contact_id = 4;
} else if(preg_match('/(Fechamento de Visita)/', ($deal_details->properties->primeiro_contato))){
$deal_aux->first_contact_id = 5;
}
}
if(!empty($deal_details->properties->dealstage)){
if($deal_details->properties->dealstage == '10780349'){
$deal_aux->sale_stage_id = 1;
} elseif($deal_details->properties->dealstage == '46791452'){
$deal_aux->sale_stage_id = 2;
} elseif($deal_details->properties->dealstage == '6568482'){
$deal_aux->sale_stage_id = 3;
} elseif($deal_details->properties->dealstage == '50005805'){
$deal_aux->sale_stage_id = 4;
} elseif($deal_details->properties->dealstage == '6950881'){
$deal_aux->sale_stage_id = 5;
} elseif($deal_details->properties->dealstage == '6950882'){
$deal_aux->sale_stage_id = 6;
} elseif($deal_details->properties->dealstage == 'closedwon'){
$deal_aux->sale_stage_id = 7;
} elseif($deal_details->properties->dealstage == '14019903'){
$deal_aux->sale_stage_id = 8;
} elseif($deal_details->properties->dealstage == '57109334'){
$deal_aux->sale_stage_id = 9;
} elseif($deal_details->properties->dealstage == '9881352'){
$deal_aux->sale_stage_id = 10;
} elseif($deal_details->properties->dealstage == '9881353'){
$deal_aux->sale_stage_id = 11;
} elseif($deal_details->properties->dealstage == '65328237'){
$deal_aux->sale_stage_id = 12;
} elseif($deal_details->properties->dealstage == '65328238'){
$deal_aux->sale_stage_id = 13;
} elseif($deal_details->properties->dealstage == '57109335'){
$deal_aux->sale_stage_id = 14;
} elseif($deal_details->properties->dealstage == '9881351'){
$deal_aux->sale_stage_id = 15;
} elseif($deal_details->properties->dealstage == '9881354'){
$deal_aux->sale_stage_id = 16;
} elseif($deal_details->properties->dealstage == '37156417'){
$deal_aux->sale_stage_id = 17;
} elseif($deal_details->properties->dealstage == '9624616'){
$deal_aux->sale_stage_id = 18;
} else {
$deal_aux->sale_stage_id = null;
}
}
// Faço a importação apenas do pipe de vendas
// TODO: tratar a importação para Automação de conversão
if ($is_new == true && $sales_automation == false && ($deal_aux->sale_stage_id >= 8 || $deal_aux->sale_stage_id == null)){
return false;
}
$leadsHelper = new LeadsManagementHelper;
if(!empty($deal_details->properties->dono_do_lead__sdr_)){
$owner = $leadsHelper->hubspotGetOwnerById($deal_details->properties->dono_do_lead__sdr_);
if(isset($owner->email)){
$sys_user = ORM::for_table('sys_users')->where('username', $owner->email)->find_one();
if(isset($sys_user->id)){
$deal_aux->sdr_id = $sys_user->id;
}
}
}
if(!empty($deal_details->properties->hubspot_owner_id)){
$owner = $leadsHelper->hubspotGetOwnerById($deal_details->properties->hubspot_owner_id);
if(isset($owner->email)){
$sys_user = ORM::for_table('sys_users')->where('username', $owner->email)->find_one();
if(isset($sys_user->id)){
$deal_aux->seller_id = $sys_user->id;
if($deal_aux->sdr_id == $deal_aux->seller_id){
$deal_aux->seller_id = null;
}
}
}
}
if(!empty($deal_details->properties->evento_de_passagem___tipo)){
if($deal_details->properties->evento_de_passagem___tipo == "Call"){
$deal_aux->passing_event_type = 'call';
} elseif($deal_details->properties->evento_de_passagem___tipo == "Visita presencial"){
$deal_aux->passing_event_type = 'in_person';
} elseif($deal_details->properties->evento_de_passagem___tipo == "Visita de vídeo"){
$deal_aux->passing_event_type = 'video';
} elseif($deal_details->properties->evento_de_passagem___tipo == "Outro"){
$deal_aux->passing_event_type = 'other';
}
}
if(!empty($deal_details->properties->evento_de_passagem_data)){
$deal_aux->passing_event_date = date('Y-m-d H:i:s', strtotime($deal_details->properties->evento_de_passagem_data));
}
$deal_aux->save();
$return_deal_id = $deal_aux->id;
// Tasks
if(isset($deal_details->associations->tasks->results)){
foreach($deal_details->associations->tasks->results as $task){
$data = $this->hubspotGetTask($task->id);
if(isset($data->id)){
$task_aux = ORM::for_table('module_imobles_deal_tasks')->where('hs_task_id', $data->id)->find_one();
if(isset($task_aux->id)){
$task_id = $task_aux->id;
echo "TAREFA JÁ REGISTRADA | ".$task_id."\n";
if($task_aux->closed == 1){
continue;
}
$task_aux->updated_at = date('Y-m-d H:i:s');
} else {
// echo "TAREFA CRIADA COM SUCESSO \n";
$task_aux = ORM::for_table('module_imobles_deal_tasks')->create();
$task_aux->created_at = date('Y-m-d H:i:s');
}
$task_aux->title = $data->properties->hs_task_subject;
$task_aux->description = @$data->properties->hs_task_body;
$task_aux->closed = $data->properties->hs_task_status == 'COMPLETED'? 1 :null;
$task_aux->deal_id = $deal_aux->id;
$task_aux->hs_task_id = $data->id;
if(!empty($data->properties->hs_timestamp)){
$task_aux->due_date = date('Y-m-d H:i:s', strtotime($data->properties->hs_timestamp));
}
$task_aux->title = $data->properties->hs_task_subject;
$task_aux->save();
}
}
}
// Notes
if(isset($deal_details->associations->notes->results)){
foreach($deal_details->associations->notes->results as $task){
$data = $this->hubspotGetNote($task->id);
if(isset($data->id)){
if(empty($data->properties->hs_note_body)){
continue;
}
// $task_aux = ORM::for_table('sys_activity')->where('icon', $data->id)->find_one();
$task_aux = ORM::for_table('module_imobles_deals_notes')->where('hs_note_id', $data->id)->find_one();
if(isset($task_aux->id)){
$task_id = $task_aux->id;
echo "NOTA JÁ REGISTRADA | ".$task_id."\n";
// continue;
} else {
// echo "NOTA CRIADA COM SUCESSO \n";
// $task_aux = ORM::for_table('sys_activity')->create();
$task_aux = ORM::for_table('module_imobles_deals_notes')->create();
$task_aux->crm_account_id = $crm_account_id;
// $n->msg = $d->msg;
$task_aux->deal_id = $deal_aux->id;
$task_aux->created_at = date('Y-m-d H:i:s');
// $task_aux->created_by = $d->o;
$task_aux->hs_note_id = $data->id;
// $n->sys_activity_id = $d->id;
// $task_aux->cid = $crm_account_id;
$owner = $leadsHelper->hubspotGetOwnerById($data->properties->hubspot_owner_id);
if(isset($owner->email)){
$sys_user = ORM::for_table('sys_users')->where('username', $owner->email)->find_one();
if(isset($sys_user->id)){
$task_aux->created_by = $sys_user->id;
}
}
}
// $task_aux->stime = strtotime($data->properties->hs_createdate);
// $task_aux->sdate = date('Y-m-d', strtotime($data->properties->hs_createdate));
// $task_aux->icon = $data->id;
$task_aux->msg = $data->properties->hs_note_body;
$task_aux->save();
}
}
}
return $return_deal_id;
}
public function hubspotGetDealDetails($hs_deal_id){
$properties = "evento_de_passagem_vgv_potencial,evento_de_passagem___tipo,evento_de_passagem_data,status_do_deal,dealstage,imobles_prime,dealname,num_contacted_notes,".
"origem___nutricao_vs_site,hubspot_owner_id,quantos_quartos_esta_buscando_,".
"status_do_deal,amount,venda_nome_do_empreendimento,venda_construtora,vgv___mbrl,".
"closedate,pipeline,dono_do_lead__sdr_,data_criacao_da_opp__sales_pipeline_,".
"origem___nutricao_vs_site,motivo_da_perda_do_negocio,nutricao___campanha,".
"engajado_,espelhamento___escolha_do_cliente,primeiro_contato,data_entrada_na_ultima_etapa,".
"alto_padrao,notes_next_activity_date,origem_do_lead,notes_last_updated,closed_won_reason";
$url = 'https://api.hubapi.com/crm/v3/objects/deals/'.$hs_deal_id.'?associations=deal,contact,note,task,call&properties='.$properties;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$responseDeal = curl_exec($curl);
curl_close($curl);
try {
return json_decode($responseDeal);
}
catch (Exception $e) {
return false;
}
}
public function hubspotCreateTask($objectId, $hs_timestamp, $hs_task_body, $hs_task_subject, $hs_task_status, $hs_task_type, $hubspot_owner_id, $hs_task_id = null) {
$curl = curl_init();
$post_data = '{
"properties": {
"hs_timestamp": "'.$hs_timestamp.'",
"hs_task_body": "'.$hs_task_body.'",
"hs_task_subject": "'.$hs_task_subject.'",
"hs_task_status": "'.$hs_task_status.'",
"hs_task_type": "'.$hs_task_type.'",
"hubspot_owner_id": "'.$hubspot_owner_id.'"
},
"associations": [
{
"to": {
"id": '.$objectId.'
},
"types": [
{
"associationCategory": "HUBSPOT_DEFINED",
"associationTypeId": 216
}
]
}
]
}';
$url = "https://api.hubapi.com/crm/v3/objects/tasks/".$hs_task_id;
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $post_data,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try {
$hsUserId = null;
$response = json_decode($response);
if(isset($response->id) && $response->id > 0)
{
return $response;
} else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
public function hubspotCreateNotesDeal($objectId, $hs_timestamp, $hs_task_body, $hs_task_subject, $hs_task_status, $hs_task_type, $hubspot_owner_id, $hs_task_id = null) {
$curl = curl_init();
$post_data = '{
"properties": {
"hs_timestamp": "'.$hs_timestamp.'",
"hs_task_body": "'.$hs_task_body.'",
"hs_task_subject": "'.$hs_task_subject.'",
"hs_task_status": "'.$hs_task_status.'",
"hs_task_type": "'.$hs_task_type.'",
"hubspot_owner_id": "'.$hubspot_owner_id.'"
},
"associations": [
{
"to": {
"id": '.$objectId.'
},
"types": [
{
"associationCategory": "HUBSPOT_DEFINED",
"associationTypeId": 216
}
]
}
]
}';
$url = "https://api.hubapi.com/crm/v3/objects/tasks/".$hs_task_id;
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $post_data,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try {
$hsUserId = null;
$response = json_decode($response);
if(isset($response->id) && $response->id > 0)
{
return $response;
} else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
public function hubspotGetOwners(){
$curl = curl_init();
$url = "https://api.hubapi.com/crm/v3/owners";
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try {
$hsUserId = null;
$response = json_decode($response);
if(isset($response->results) && count($response->results) > 0)
{
return $response->results;
} else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
public function hubspotUpdateDealProperties($hsContactid, $data){
$postData = array("properties" => $data);
$postData = json_encode($postData);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.hubapi.com/crm/v3/objects/deals/'.$hsContactid,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try{
$jsonResponse = json_decode($response);
if(isset($jsonResponse->status) && $jsonResponse->status == "error"){
$return["error"] = true;
$return["msg"] = $jsonResponse->message;
} elseif(isset($jsonResponse->id) && $jsonResponse->id == $hsContactid) {
$return["error"] = false;
$return["data"] = $jsonResponse;
} else {
$return["error"] = true;
$return["msg"] = "Algo de inesperado aconteceu. Entre em contato com o webmaster.";
}
}
catch (Exception $e) {
$return["error"] = true;
$return["msg"] = "Exception: ".$e->getMessage();
}
return $return;
}
public function webHookNewDeal($hs_deal_id){
$hs_contact_id = $this->hubspotGetUserByDeal($hs_deal_id);
$deal_details = $this->hubspotGetDealDetails($hs_deal_id);
if(!isset($deal_details->id)){
return false;
}
$sys_user_id = null;
$leadsHelper = new LeadsManagementHelper;
if(!empty($deal_details->properties->hubspot_owner_id)){
$owner = $leadsHelper->hubspotGetOwnerById($deal_details->properties->hubspot_owner_id);
if(isset($owner->email)){
$sys_user = ORM::for_table('sys_users')->where('username', $owner->email)->find_one();
if(isset($sys_user->id)){
$sys_user_id = $sys_user->id;
}
}
} else {
return false;
}
// verifico a etapa do Deal
if(empty($deal_details->properties->dealstage) || $deal_details->properties->dealstage != '81524401'){
return false;
}
// if(!empty($deal_details->properties->status_do_deal) && $deal_details->properties->status_do_deal == 'Aberto - Conversando'){
// $deal_status_id = 1;
// } else {
// return false;
// }
// verifico se tem Deal aberto
$hs_contacts_deals = $leadsHelper->hubspotGetDeals($hs_contact_id);
if(!empty($hs_contacts_deals))
{
foreach($hs_contacts_deals as $hs_deal)
{
if($hs_deal->id == $hs_deal_id){
continue;
}
if($hs_deal->properties->status_do_deal == 'Aberto - Conversando')
{
return false;
}
}
} else {
return false;
}
// Faço a importação do Deal para o Rocket
$deal_id = $this->hubspotImportOpenDeal($hs_deal_id, true);
if(!empty($deal_id)){
// verifico o tipo de conversão
$hs_contact_details = $leadsHelper->hubspotGetContactDetails($hs_contact_id);
$conversion_id = $hs_contact_details->properties->rocket_conversion_id->value;
$conversion_details = ORM::for_table('module_imobles_leads_conversion')->find_one($conversion_id);
// if(!empty($conversion_details->params)){
// $params = json_decode($conversion_details->params);
// $conversion_name = $params->client_details->first_name;
// if(!preg_match('(mygpt)i', $conversion_name)){
// return false;
// }
// } else {
// return false;
// }
$conversion_region = $hs_contact_details->properties->deal_conversion_region->value;
// TODO: fazer o agendamento apenas se o nome do lead tiver MYGPT
$auto = ORM::for_table('module_imobles_leads_automation')->where('deal_id', $deal_id);
if(empty($auto->id)){
$deal_details = ORM::for_table('module_imobles_deals')->find_one($deal_id);
if($deal_details->crm_account_id){
if($conversion_id != 12){
$date = new DateTime();
$date->modify('-24 hours');
$date_aux = $date->format('Y-m-d H:i:s');
$user_conversions = ORM::for_table('module_imobles_leads_conversion')
->where('crm_accounts_id',$deal_details->crm_account_id)
->where_gte('created_at', $date_aux)
->find_many();
foreach($user_conversions as $c){
if($c->conversion_type_id == 12){
$conversion_id = $c->id;
}
}
}
$auto = ORM::for_table('module_imobles_leads_automation')->create();
$auto->deal_id = $deal_id;
$auto->conversion_id = $conversion_id;
$auto->deal_id = $deal_id;
$auto->crm_account_id = $deal_details->crm_account_id;
$auto->save();
}
} else {
return false;
}
}
return true;
}
public function getContactDetails($hsContactid) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.hubapi.com/contacts/v1/contact/vid/'.$hsContactid.'/profile',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response);
return $response;
}
public function getDealsByContact($hsContactid) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.hubapi.com/crm/v3/objects/contacts/'.$hsContactid.'/associations/deals?limit=500',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
try {
$arr_deals = array();
$response = json_decode($response);
if(isset($response->results) && count($response->results) > 0)
{
foreach($response->results as $deal)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.hubapi.com/crm/v3/objects/deals/'.$deal->id.'?properties=status_do_deal,dealstage,imobles_prime,dealname.num_contacted_notes,origem___nutricao_vs_site,hubspot_owner_id,quantos_quartos_esta_buscando_,status_do_deal,amount,venda_nome_do_empreendimento,venda_construtora,vgv___mbrl,closedate,pipeline,dono_do_lead__sdr_,data_criacao_da_opp__sales_pipeline_,origem___nutricao_vs_site,motivo_da_perda_do_negocio,nutricao___campanha,alto_padrao,notes_next_activity_date,caracteristica_especial__ex__duas_garagens__var__gourmet__cozinha_integrada__etc_,origem_do_lead,tamanho___quartos___suites_e_ou_area_total,notes_last_updated,closed_won_reason&archived=true',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$responseDeal = curl_exec($curl);
curl_close($curl);
try {
$responseDeal = json_decode($responseDeal);
$arr_deals[] = $responseDeal;
}
catch (Exception $e) {
return false;
}
}
}
return $arr_deals;
}
catch (Exception $e) {
return false;
}
}
public function getOwnerById($ownerId) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.hubapi.com/owners/v2/owners/'.$ownerId,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
),
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response);
return $response;
}
}