eliecerthoms1

inbound-call-status.js

Oct 20th, 2023
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { validateTwilioSignature, twilio } from '../../../shared/twilio';
  2. import { getBaseUrl } from '../../../shared/utils';
  3. import { updateInboundPhoneCall } from '../phone-call-actions';
  4. import * as qs from 'querystring';
  5. import { twiml } from 'twilio';
  6. import rqstbin from '../../../shared/rqstbin';
  7.  
  8. /**
  9.  * Inbound call status webhook handler.
  10.  *
  11.  * @param {object} event - 8base event.
  12.  * @param {object} ctx - 8base context.
  13.  *
  14.  * @returns {Promise} The webhook response.
  15.  */
  16. export default async function(event, ctx) {
  17.   console.log('call: Running Inbound Call Status Webhook...');
  18.   const body = qs.parse(event.body);
  19.   const url = `${getBaseUrl(ctx)}/webhook/inbound-call/status`;
  20.   const signature = event.headers['X-Twilio-Signature'];
  21.   const options = { checkPermissions: false };
  22.   let call = null;
  23.  
  24.   let twilioClient = await twilio(body.AccountSid);
  25.  
  26.   //rqstbin({msg: 'got here', from: "inbound-call-status"})
  27.  
  28.   if (validateTwilioSignature(signature, url, body) == false) {
  29.     console.log('call: inbound-call-status Invalid twilio signature [' + signature + ']');
  30.  
  31.     return {
  32.       statusCode: 401,
  33.       body: {
  34.         message: 'Unauthorized request',
  35.       },
  36.     };
  37.   } else {
  38.     rqstbin({ signature: 'valid', from: 'inbound-call-status' });
  39.   }
  40.  
  41.   console.log('call: inbound-call-status CallSid', body.CallSid + ' status: ', body.CallStatus);
  42.  
  43.   if (body.CallStatus === 'completed') {
  44.     try {
  45.       call = await twilioClient.calls(body.CallSid).fetch();
  46.       console.log('call: inbound-call-status', call);
  47.     } catch (e) {
  48.       console.error('call: inbound-call-status Error fetching call from Twilio:', e.message);
  49.  
  50.       const response = new twiml.VoiceResponse();
  51.  
  52.       response.say(`Could not fetch call from twilio: ${e.message}`);
  53.  
  54.       console.log('call: inbound-call-status Could not fetch call from twilio:', e.message);
  55.       return {
  56.         statusCode: 200,
  57.         body: response.toString(),
  58.       };
  59.     }
  60.   }
  61.  
  62.   try {
  63.     let callUpdate = await updateInboundPhoneCall(
  64.       { callSid: body.CallSid },
  65.       {
  66.         dialCallSid: body.DialCallSid,
  67.         status: body.CallStatus,
  68.         duration: Number(body.CallDuration),
  69.         ...(call && call.price
  70.           ? {
  71.             price: Math.abs(parseFloat(call.price)),
  72.             priceUnit: call.priceUnit || 'USD',
  73.           }
  74.           : {}),
  75.       },
  76.       ctx,
  77.       options,
  78.     );
  79.     console.log(
  80.       'call: inbound-call-status InboundPhoneCall was updated',
  81.       JSON.stringify(callUpdate),
  82.     );
  83.   } catch (e) {
  84.     console.error('call: inbound-call-status Error updating the call:', e.message);
  85.  
  86.     const response = new twiml.VoiceResponse();
  87.  
  88.     response.say(`Something happened updating the call: ${e.message}`);
  89.     return {
  90.       statusCode: 200,
  91.       body: response.toString(),
  92.     };
  93.   }
  94.  
  95.   return {
  96.     statusCode: 200,
  97.     body: JSON.stringify({
  98.       success: true,
  99.     }),
  100.   };
  101. }
  102.  
Advertisement
Add Comment
Please, Sign In to add comment