Skip to main content

Cookbook: Real-World Examples

Practical recipes for using Integration Hub for Moodle with its current v1.0 capabilities.


Recipe 1: Sending a Slack Notification when a User Logins

Goal: Send a JSON payload to a Slack Webhook every time a user logs in.

Prerequisites:

  • A Slack Incoming Webhook URL (e.g., https://hooks.slack.com/services/T000/B000/XXXX).

Steps:

  1. Create Service:

    • Go to Site Administration > Server > Integration Hub > Services.
    • Click Add Service.
    • Name: Slack Notifications
    • Base URL: https://hooks.slack.com
    • Method: POST
    • Save.
  2. Create Rule:

    • Go to Rules.
    • Click Add Rule.
    • Event: \core\event\user_loggedin
    • Service: Slack Notifications
    • Endpoint Path: /services/T000/B000/XXXX (the part after the base URL).
    • Payload Template:
      {
      "text": "User {{username}} just logged in from IP {{ip}}!"
      }
    • Save.
  3. Test:

    • Log out and log back in.
    • Check the Queue tab to see the event status.

Recipe 2: Syncing User Creation to an external CRM (PHP)

Goal: Use the MIH API in your own local plugin to sync data when a user is created.

Context: You are writing a custom plugin (local_myplugin) and want to call an external API reliably.

Code:

use local_integrationhub\mih;

// ... user data array ...

// Usage: mih::request(service_name, path, payload, method)
$response = mih::request(
'mi-crm-servicio',
'/api/v1/clientes',
$userData,
'POST'
);

// Or Fluent Style:
// mih::send('mi-crm-servicio')->to(...)->with(...)->dispatch();

if ($response->is_ok()) {
mtrace("Sync successful: " . $response->body);
}

Recipe 3: Debugging a Failed Webhook

Problem: You set up a webhook but it's not arriving.

Steps:

  1. Go to Integration Hub > Queue.
  2. Look for your task.
    • Status: Pending: It's waiting to run (check your Cron).
    • Status: Failed (Retry): It failed but will try again. Check the "Failures" count.
  3. View Payload:
    • Click the Code Icon (</>) next to the task to see exactly what JSON was generated.
  4. Dead Letter Queue (DLQ):
    • If the task failed too many times (e.g., > 5), it moves to the DLQ section at the bottom.
    • You can view the error message (e.g., 404 Not Found) and deciding whether to Replay or Delete.

Recipe 4: Using Circuit Breaker to Protect Moodle

Goal: Ensure Moodle doesn't hang if your external ERP goes offline.

Configuration:

  1. Go to Services and edit your ERP service.
  2. Resilience Settings:
    • Threshold: 5 (After 5 failures...)
    • Window: 60 (...in 1 minute)
    • Cooldown: 300 (Stop sending requests for 5 minutes).
  3. Behavior:
    • If the ERP returns 500 Error 5 times in a row, the Circuit Breaker OPENS.
    • Subsequent events are effectively "paused" or failed immediately depending on your code, saving Moodle from waiting on timeouts.