exportasyncfunctionrun(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(); } elseif(this.source ==CloudCode.EDITOR_TEST&&this.env =='testing') {// Test - Create mock object object =DB.job_card.create(); } else {thrownewError('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 hereconstSENDGRID_KEY=process.env.sendgrid_key; // Read the docs for env variablesconstFROM_EMAIL="you@example.com";// Used for testing onlyconstTEST_EMAIL="you@example.com";asyncfunctionemail(params) {// Helper function to send an email via the sendgrid API.var response =awaitfetch('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) {returnnull; } else {thrownewError('Failed to send email: '+response.statusText); }}exportasyncfunctionrun(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(); } elseif(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 {thrownewError('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.00Second Item 3 x R 6.00----------------------------------------------Total: R 42.00`;awaitemail({ personalizations: [ { to: [ { email:invoice.client_email, name:invoice.client_name } ], subject:"Test Invoice: "+newDate().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: