Skip to content

Instantly share code, notes, and snippets.

@WesleyDRobinson
Created December 3, 2019 23:18
Show Gist options
  • Save WesleyDRobinson/da9aa82675acc4d63ef198024f6a34bf to your computer and use it in GitHub Desktop.
Save WesleyDRobinson/da9aa82675acc4d63ef198024f6a34bf to your computer and use it in GitHub Desktop.
Twilio Studio Function

How to make any HTTP request with Twilio Studio Flow + Twilio Functions

Twilio Functions

Make a new function :)

Add your dependencies and keys to functions configuration: https://www.twilio.com/console/functions/configure

In this example, I use:

Keys: zendeskAccessToken, zendeskAccessEmail, zendeskUrl

Dependencies: node-fetch

Adapt CreateZendeskTicket.js code from this gist to use in the handler.

Twilio Studio

From the Widget Library, under TOOLS & EXECUTE CODE, choose Run Function.

Give your Widget a name like CreateZendeskTicket, Select the Twilio Function you made. Specify any keys you may be using in event In this example, only 'from' is used as event.from

You've done it.

Comments welcome.

exports.handler = function(context, event, callback) {
  const url = require('url')
  const fetch = require('node-fetch')
  const { zendeskAccessToken, zendeskAccessEmail, zendeskUrl } = context // context injected by Twilio Function
// using Basic Auth
  const encodedToken = new Buffer(`${zendeskAccessEmail}/token:${zendeskAccessToken}`).toString('base64')
  const headers = {
    'Authorization': `Basic ${encodedToken}`,
    'Content-type': 'application/json',
  }
  // Get Requester Info (event injected by Twilio Function)
  getRequesterInfo(event.from)
    .then(userInfo => closeFunction('successfully fetched requester info', userInfo))
    .catch(e => closeFunctionWithError(e))
  function getRequesterInfo(phoneString) {
    const query = (phoneString && phoneString.length === 12)
? phoneString.slice(2)
: phoneString
    const searchUrl = `${zendeskUrl}/users/search.json/?query=${query}`
    const getFetchOpts = {
      method: 'get',
      headers,
    }
    return new Promise((resolve, reject) => {
      fetch(searchUrl, getFetchOpts)
        .then(res => res.json())
        .then(usersObject => resolve(usersObject))
        .catch(err => reject(err))
    })
  }
function closeFunction(message, data) {
console.log('closing function', {
message,
data: JSON.stringify(data, null, 2),
})
// callback injected to Twilio Function
callback(null, { message, data: JSON.stringify(data, null, 2) })
}
function closeFunctionWithError(err) {
console.log('error occured', JSON.stringify(err))
closeFunction('an error occurred', err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment