export default async function main(args) {
let { body, priority, subject, ZDAPIKey, ZDEmail, subdomain, requesterEmail, requesterName } = args.inputVars;
//Check if we have the required variables
if (!body || !ZDEmail || !ZDAPIKey ) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variables for ZD Ticket function" } }]
};
}
//Create a base64 encoding function to encode our auth
function base64Encode(input) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let str = String(input);
let output = '';
for (let block = 0, charCode, idx = 0, map = chars;
str.charAt(idx | 0) || (map = '=', idx % 1);
output += map.charAt(63 & block >> 8 - idx % 1 * 8)) {
charCode = str.charCodeAt(idx += 3/4);
if (charCode > 0xFF) {
throw new Error("'base64Encode' failed: The string to be encoded contains characters outside of the Latin1 range.");
}
block = block << 8 | charCode;
}
return output;
}
//Base64 encode user authentication for the API call
const encoded = base64Encode(`${ZDEmail}/token:${ZDAPIKey}`)
//Create the API body
const data = JSON.stringify({
"ticket": {
"comment": {
"body": body
},
"priority": priority,
"subject": subject,
"requester": {
"name": requesterName,
"email": requesterEmail
}
}
});
//Define URL and config
const url = `https://${subdomain}.zendesk.com/api/v2/tickets`
const config = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${encoded}`, // Base64 encoded "username:password"
},
body : data,
};
//Make the fetch request & return relevant information
try {
const response = await fetch(url, config);
const responseBody = response.json;
const ticketID = responseBody.ticket.id
if (!responseBody || typeof responseBody !== 'object') {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Invalid or missing response body from ZD API" } }]
};
}
//Return variables, a debug message, and the path
return {
outputVars: { ZDResponse: JSON.stringify(responseBody), ID: ticketID }, // Temporarily return the response as a string
next: { path: 'success' },
trace: [{ type: "debug", payload: { message: "Ticket Created: " + JSON.stringify(ticketID) } }]
};
} catch (error) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Error fetching data from ZD: " + error.message } }]
};
}
}