Skip to content

Instantly share code, notes, and snippets.

@mrbarletta
Last active December 24, 2018 15:26
Show Gist options
  • Save mrbarletta/5ae6cd129c66a7fee6831724ee08d4a7 to your computer and use it in GitHub Desktop.
Save mrbarletta/5ae6cd129c66a7fee6831724ee08d4a7 to your computer and use it in GitHub Desktop.
MailgunWebhooks Entrypoint - sets SuiteCRM email opted out + Note with details for reference
<?php
if (!defined('sugarEntry') || !sugarEntry) {
die('Not A Valid Entry Point');
}
function unsubscribeNote($recipient, $note, $description)
{
global $db;
$queryOptout = "UPDATE email_addresses SET opt_out=1 WHERE email_address='?'";
$queryBeans = "SELECT emr.bean_id, emr.bean_module FROM email_addresses ema
INNER JOIN email_addr_bean_rel emr ON ema.id=emr.email_address_id
WHERE email_address='?'";
$preparedStatementData = array(
$recipient,
);
$resultOptout = $db->pQuery($queryOptout, $preparedStatementData);
$resulBeans = $db->pQuery($queryBeans, $preparedStatementData);
if ($resulBeans->num_rows > 0) {
while ($row = $db->fetchByAssoc($resulBeans)) {
$bean = BeanFactory::getBean($row['bean_module'], $row['bean_id']);
$note = new Note();
$note->name = $note;
$note->description = $description;
$note->assigned_user_id = 'bot';
$note->parent_type = $row['bean_module'];
$note->parent_id = $row['bean_id'];
if (strtolower($row['bean_module']) == 'Contacts') {
// The following lines are to avoid incorrect "related to" links to contacts since Notes has a one-to-many relationship
// This if is to avoid overwrite an existing linked contact
if (empty($note->contact_id)) {
$note->contact_id = $row['bean_id'];
}
// This is the default behaviour when linking a contact
$note->parent_type = 'Accounts';
$note->parent_id = '';
}
$note->save();
}
}
}
$post_data = $_POST = json_decode(file_get_contents('php://input'), true);
if (!empty($post_data['event-data']) && !empty($post_data['event-data']['event']) && !empty($post_data['event-data']['recipient'])) {
$recipient = $post_data['event-data']['recipient'];
$severity = $post_data['event-data']['severity'];
$event = $post_data['event-data']['event'];
if (!empty($severity) && $severity == "permanent") {
$errorMessage = $post_data['event-data']['delivery-status']['message'];
if(strpos($errorMessage, "block list") == false){
//We should not invalidate email if we are temporary in a block list
unsubscribeNote($recipient, "Email opt out por fallo permanente", json_encode($post_data));
}
} elseif ($event == "unsubscribed") {
unsubscribeNote($recipient, "Email opt out por solicitud de baja", json_encode($post_data));
}
}
echo http_response_code(200);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment