Jump to content

Google AI coded hook help


Recommended Posts

One of these days, AI may help me/us. Perhaps RI can help for now. 😉  

So basically, I was trying to create a custom hook that sends a different email based on the quantity of a configurable option ordered with a specific product. I.e. If a client orders a VPS with only a primary IP, he or she will receive the default product/service welcome email. However, if he or she orders 1, 2, 3, or 4 additional IP addresses, he or she will receive a different product/service welcome email. Below is what Google spit out at me. It doesn't work.  I did test with the real CID.

 

<?php

use WHMCS\Database\Capsule;

add_hook('AfterServiceActivation', 1, function($vars) {
    $serviceId = $vars['serviceid'];

    try {
        // Get the configurable option value for the activated service
        $configurableOptionValue = Capsule::table('tblhosting')
            ->join('tblhostingconfigoptions', 'tblhosting.id', '=', 'tblhostingconfigoptions.relid')
            ->join('tblproductconfigoptionssub', 'tblhostingconfigoptions.optionid', '=', 'tblproductconfigoptionssub.id')
            ->where('tblhosting.id', $serviceId)
            ->where('tblproductconfigoptionssub.configid', CID) // Replace with your configurable option ID
            ->value('tblproductconfigoptionssub.optionname');

        $emailTemplateName = '';

        // Determine which email template to send based on the configurable option value
        if ($configurableOptionValue == '0') {
            $emailTemplateName = 'Welcome Default';
        } elseif ($configurableOptionValue == '1') {
            $emailTemplateName = 'Welcome IPv4 1';
	} elseif ($configurableOptionValue == '2') {
            $emailTemplateName = 'Welcome IPv4 2';
	} elseif ($configurableOptionValue == '3') {
            $emailTemplateName = 'Welcome IPv4 3';
	} elseif ($configurableOptionValue == '4') {
            $emailTemplateName = 'Welcome IPv4 4';
        } else {
            // Fallback to a default welcome email if no specific option matches
            $emailTemplateName = 'Welcome Default';
        }

        // Get client ID
        $clientId = Capsule::table('tblhosting')->where('id', $serviceId)->value('userid');

        // Send the chosen email template
        localAPI('SendEmail', [
            'messagename' => $emailTemplateName,
            'id' => $clientId, // Send to the client
            'customvars' => [
                'service_id' => $serviceId, // Pass service ID as a custom variable if needed in the email template
            ],
        ]);

    } catch (\Exception $e) {
        // Log any errors for debugging
        logActivity("Custom Welcome Email Hook Error: " . $e->getMessage());
    }
});

 

Honestly, a better option would be opening up a ticket for assigning additional IPv4s. However, Google AI (Gemini?) didn't seem to have much to offer there. Essentially, I will need to manually assign additional IPs and restart the VPS afterwards. So, I don't want the client logging in early or during that event. The VPS is created through automation. 

Any advice would be much appreciated! Thanks!

Link to comment
Share on other sites

Update. I decided to give this a go on Chat GPT. The idea here is to open a new support ticket if there are one or more additional IPv4 addresses selected as configurable options in the order. Unfortunately, it didn't work either (including the WHMCS activity log output).

<?php

if (!defined("WHMCS")) {
die("This file cannot be accessed directly");
}

use WHMCS\Database\Capsule;
use WHMCS\Utility\Logging\Log;

add_hook('OrderPaid', 1, function($vars) {
$orderId = $vars['orderId'];
$userId = $vars['userId'];

// Target product group ID
$allowedGroupId = 17;

// Get all services in the order
$services = Capsule::table('tblhosting')
->where('orderid', $orderId)
->get();

foreach ($services as $service) {
// Get the product to check its group
$product = Capsule::table('tblproducts')
->where('id', $service->packageid)
->first();

if (!$product || $product->gid != $allowedGroupId) {
continue; // Skip services not in target group
}

// Get config options for the service
$configOptions = Capsule::table('tblhostingconfigoptions')
->where('relid', $service->id)
->get();

foreach ($configOptions as $option) {
$configOption = Capsule::table('tblproductconfigoptions')
->where('id', $option->configid)
->first();

$optionName = strtolower($configOption->optionname);

if (strpos($optionName, 'Additional IPv4 Addresses') !== false) {
$quantity = (int)$option->qty;
if ($quantity > 0) {
// Prepare ticket message
$serviceLabel = $service->domain ?: 'Service ID: ' . $service->id;
$ticketSubject = 'Priority Setup Requested for Service';
$ticketMessage = "Client has requested **{$quantity} Priority Setup(s)** for the following service:\n\n"
. "**Service**: {$serviceLabel}\n"
. "**Product**: {$product->name}\n"
. "**Service ID**: {$service->id}\n"
. "\nPlease process this request accordingly.";

// Create the ticket
$result = localAPI('OpenTicket', [
'clientid' => $userId,
'deptid' => 8, // Replace with your department ID
'subject' => $ticketSubject,
'message' => $ticketMessage,
'priority' => 'High',
]);

// Log to WHMCS activity log
if ($result['result'] === 'success') {
logActivity("Auto-ticket created for Service ID {$service->id} (Priority Setup x{$quantity})", $userId);
} else {
logActivity("Failed to auto-create ticket for Service ID {$service->id}. Error: " . $result['message'], $userId);
}

break; // No need to check more options for this service
}
}
}
}
});

I think opening a new ticket is the way to go. I would love any input/feedback/help. Thanks!

Link to comment
Share on other sites

  • WHMCS Technical Analyst

So the logic looks correct in both cases, so if they are not working that would mean some runtime errors in both cases. Can you provide the output you are getting or if there is anything logged in the Activity log at all?

Link to comment
Share on other sites

3 hours ago, WHMCS Sachin said:

So the logic looks correct in both cases, so if they are not working that would mean some runtime errors in both cases. Can you provide the output you are getting or if there is anything logged in the Activity log at all?

Thanks, Sachin! That's the thing. I cannot find any output. There is nothing in the activity log. I tailed the Apache error log during test orders and also checked the typical cPanel account error_logs (~/logs/domain.php.error.log, ~/public_html/error_log, ~/public/whmcs/error_log) after the test orders. There are no clues whatsoever.

Please advise. Thanks again!

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use & Guidelines and understand your posts will initially be pre-moderated