Categories
technical

Use Webhook from Mailpoet when a new subscriber is added

Took a bit of trial and error to get this code to work. Definitely not perfect, as I am using the subscriber id to get the subscriber email and then sending it…

Basically, just replace the URL for $webhook_url.

You can put this within a plugin or functions.php in order to work. However, it may get overwritten when wp or a plugin updates so better to create one on your own.

 

<?
function send_webhook_on_new_subscriber($subscriber_id) {
// The URL of your webhook receiver
$webhook_url = ‘Put URL Here’;

// Check if MailPoet API class exists
if (!class_exists(\MailPoet\API\API::class)) {
error_log(‘MailPoet API class does not exist.’);
return;
}

// Get MailPoet API instance
$mailpoet_api = \MailPoet\API\API::MP(‘v1’);

// Try to fetch subscriber details using the API
try {
// Now, we’ll fetch subscriber data using the subscriber ID
$subscriber_data = $mailpoet_api->getSubscriber($subscriber_id);

// Send the entire subscriber data to the webhook
wp_remote_post($webhook_url, array(
‘body’ => json_encode($subscriber_data),
‘headers’ => array(‘Content-Type’ => ‘application/json’),
));

} catch (\Exception $e) {
error_log(‘Failed to fetch subscriber details using MailPoet API: ‘ . $e->getMessage());
}
}

add_action(‘mailpoet_subscriber_created’, ‘send_webhook_on_new_subscriber’);

?>