Can't pull all the campaigns associated with a leadid in a new plugin

Hello, I am currently working in an upgrade for a plugin to send/receive whatsapp messages using a middleware called Zender.
The plugin already works and replaces the “text message” channel with this to send WhatsApps and do several other things.

Now I want to be able to fetch the answers and make Mautic react to those answers. The issue is that I can’t find a way to pull the list of all campaigns a lead (leadid) has been included in (that’s needed for a part of the logic to make Mautic react to answers and for me to learn how Mautic works). So I am stuck with that.
Supposedly this will help me get the campaigns: MauticCampaignBundle:CampaignEvent
But is not working or at least I might not be using it correctly.
Error log says the entity is not defined:
**‘MauticCampaignBundle:CampaignEvent’: Error: Class ‘Mautic\CampaignBundle\Entity\CampaignEvent’ is not defined. **

So, is there a way to pull all the campaigns if I have a leadid?

BTW, I am having no issues finding the leadid if I have the email or the phone and this code is currently using that.

So, here is the code I am using that let’s me achieve the leadid (and some other things not shown in here) but can’t fetch the list of campaigns that leadid has been included at.

Can you help me find a solution please?



namespace MauticPlugin\MauticZenderBundle\Controller;

use Mautic\ApiBundle\Controller\CommonApiController;
use Mautic\PluginBundle\Helper\IntegrationHelper;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;

class ZenderWebhookController extends CommonApiController
{
private $logger;
private $integrationHelper; // Add this line

// Update the constructor
public function __construct(LoggerInterface $logger, IntegrationHelper $integrationHelper)
{
    $this->logger = $logger;
    $this->integrationHelper = $integrationHelper; // Set the IntegrationHelper
    $this->logger->debug('ZenderWebhookController instantiated.');
}

public function receiveAction(Request $request, $key, $phone, $message, $time, $datetime)
{
    $this->logger->debug('Full URL received.', [
        'full_url' => $request->getSchemeAndHttpHost() . $request->getRequestUri(),
    ]);
    
    $this->logger->debug('Received variables.', [
        'key' => $key,
        'phone' => $phone,
        'message' => $message,
        'time' => $time,
        'datetime' => $datetime
    ]);

    if (!$this->validateKey($key)) {
        return new JsonResponse(['message' => 'Unauthorized'], JsonResponse::HTTP_UNAUTHORIZED);
    }

    $this->processMessage($phone);

    return new JsonResponse(['message' => 'Webhook received and key validated.'], JsonResponse::HTTP_OK);
}

private function validateKey($key)
{
    $integration = $this->integrationHelper->getIntegrationObject('Zender');
    if (!$integration || !$integration->getIntegrationSettings()->getIsPublished()) {
        $this->logger->debug('Integration not found or not published');
        return false; // Integration not found or not published
    }

    // Retrieve and decrypt the API keys
    $keys = $integration->getDecryptedApiKeys();
    
    // Log the decrypted settings for debugging
    $this->logger->debug('Decrypted API keys', $keys);

    // Check if 'webhook_key' is present after decryption
    $configuredKey = $keys['webhook_key'] ?? '';

    if (empty($configuredKey)) {
        $this->logger->debug('No key configured, validation failed.', [
            'received_key' => $key,
            'configured_key' => $configuredKey // Log the expected key
        ]);
        return false;
    }

    if ($key !== $configuredKey) {
        $this->logger->debug('Key validation failed.', [
            'received_key' => $key,
            'expected_key' => $configuredKey,
        ]);
        return false;
    }

    $this->logger->debug('Key validation successful.', [
        'received_key' => $key
    ]);

    return true;
}






private function processMessage($phone)
{
    $leadModel = $this->getModel('lead');
    $lead = $leadModel->getRepository()->findOneBy(['mobile' => $phone]);

    if ($lead) {
        // Log the lead ID for debugging
        $this->logger->debug('Lead found.', ['leadId' => $lead->getId()]);

        // Find and log campaigns for the lead
        $campaignIds = $this->findCampaignsForLead($lead->getId());
        $this->logger->debug('Campaign IDs found for lead.', [
            'leadId' => $lead->getId(),
            'campaignIds' => $campaignIds
        ]);

        // Other code...
    } else {
        $this->logger->debug('Lead not found.', ['phone' => $phone]);
    }
}



private function findCampaignsForLead($leadId)
{
    $entityManager = $this->get('doctrine.orm.entity_manager');

    try {
        $query = $entityManager->createQuery(
            "SELECT ce.campaignId 
             FROM MauticCampaignBundle:CampaignEvent ce 
             JOIN ce.lead l
             WHERE l.id = :leadId"
        )->setParameter('leadId', $leadId);

        $campaigns = $query->getResult();
        return array_map(function ($campaign) {
            return $campaign['campaignId'];
        }, $campaigns);
    } catch (\Exception $e) {
        $this->logger->error('Error finding campaigns for lead: ' . $e->getMessage());
        return [];
    }
}

Did some changes to the code to use MauticCampaignBundle:CampaignLead
Since I found that at namespace Mautic\CampaignBundle\Entity;

I think in here: /mautic_root/app/bundles/CampaignBundle/Entity/LeadEventLog.php

But didn’t work either

So still can’t find the campaign ID, and even less the sms/text message sent

Also tried to find in: /mautic_root/app/bundles/SmsBundle/Entity/Sms.php something that could help me find the SMS sent to a user but didn’t achieved anything.

Also tried to fetch this from DB but failed also. I mean, found this in DB but using the mautic db connector didn’t worked and only worked using the full name of the DB in a standard non Mautic SQL query but had to add the table prefix, rendering the plugin useless to be reused in another mautic installation.

Just for you to understand my goal:
Find if a leadid received an SMS/Text message from Mautic. If it did, then find the last and if he have not answered before, then add a tag and add points to the lead profile. If he had already answered and got the tag and points, then do nothing. Since I want to verify each time Mautic sends message, each SMS will create a unique tag (that includes text message id) to make him get points and a new tag each answer of a new whatsapp message.

So, have no ideas.
Any help would be appreciated.

Can’t add any insight to your challenge but I am interested in what you are building.

Will you be open sourcing the plugin or making it commercially available once built?

I can also offer help with testing if needed once you get to that stage.

1 Like

The plugin that already SENDS whatsapp is public, is downloadable from github GitHub - rcarabelli/Mautic-Zender-Plugin: Plugin to use Mautic with Zender to send WhatsApp messages

The issue is to now get the answers and make Mautic react on those.

This part will also be open sourced.

The next parts that include integrations with Telegram, messenger and the capability to send text messages as campaigns from a chat and other things, will be commercial, but that will take a few months.

Look at the description at the Github, you need a bridge, a system called ZENDER that some indonesian guys (maybe singapur guys) did and that platform cost or you can hire someone that already have Zender and use it as a SAAS (for example, my company).

If you need more info let me know.

1 Like