Trigger CC via a Webhook

Webhooks can be configured to trigger a CloudCode task automatically. When the webhook fires, the task is automatically enqueued and executed.

To trigger a task called my_job_card_ready whenever a job_card is created on the backend, add the following webhook definition in the data model:

schema.xml
<model name="job_card" label="Job Card">
    <!-- ... -->
    
    <webhook type="ready" receiver="cloudcode" action="my_job_card_ready" />
</model>

In the CloudCode Task:

export async function run(event) {
  let object;
  if(this.source == CloudCode.WEBHOOK) {
    // Webhook
    object = event.object;
    // The object has the state of when the webhook was
    // triggered, which may be out of date. To work with the
    // current version, add:
    //   await object.reload();
  } else if(this.source == CloudCode.EDITOR_TEST && this.env == 'testing') {
    // Test - Create mock object
    object = DB.job_card.create();
  } else {
    throw new Error('Task must be run as a webhook');
  }
// Do something with the object here.
}

Here's an example of a task that sends an email to a specified email address on a webhook:

// Specify your details here
const SENDGRID_KEY = process.env.sendgrid_key; // Read the docs for env variables
const FROM_EMAIL = "you@example.com";

// Used for testing only
const TEST_EMAIL = "you@example.com";

async function email(params) {
  // Helper function to send an email via the sendgrid API.
  var response = await fetch('https://api.sendgrid.com/v3/mail/send', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + SENDGRID_KEY
    },
    accept: 'application/json',
    body: JSON.stringify(params)
  });
  if(response.ok) {
    return null;
  } else {
    throw new Error('Failed to send email: ' + response.statusText);
  }
}


export async function run(event) {
  let invoice;
  if(this.source == CloudCode.WEBHOOK) {
    invoice = event.object;
    // The invoice object has the state of when the webhook was
    // triggered, which may be out of date. To work with the
    // current version, add:
    //   await invoice.reload();
  } else if(this.source == CloudCode.EDITOR_TEST && this.env == 'testing') {
    // Test - Create mock object
    invoice = DB.invoice.create();
    invoice.client_name = 'Test Client';
    invoice.client_email = TEST_EMAIL;
  } else {
    throw new Error('Task must be run as a webhook');
  }

  console.log('Invoice', invoice);

  if(invoice.client_email == null) {
    return {error: 'no client email'};
  }

  console.log('Sending mail to', invoice.client_name, invoice.client_email);


  var body = `
Invoice for ${invoice.client_name}
----------------------------------------------

First Item    2 x R 12.00
Second Item   3 x R  6.00
----------------------------------------------
Total: R 42.00
`;


  await email({
    personalizations: [
      {
        to: [
          {
            email: invoice.client_email,
            name: invoice.client_name
          }
        ],
        subject: "Test Invoice: " + new Date().toISOString()
      }
    ],
    content: [
      {
        type: "text",
        value: body
      }
    ],
    from: {
      email: FROM_EMAIL,
      name: 'Invoice Mailer'
    }
  });
  console.log('Sent email.');

  return {success: true};
}

You can learn more about JourneyApps Webhooks in the documentation below:

pageWebhooks (External)

Last updated