Skip to content

Instantly share code, notes, and snippets.

@mbrammer
Created August 28, 2024 09:20
Show Gist options
  • Save mbrammer/0b6dec134f08643fe4f8b668e98380a6 to your computer and use it in GitHub Desktop.
Save mbrammer/0b6dec134f08643fe4f8b668e98380a6 to your computer and use it in GitHub Desktop.
Twilio frontend call with backend call initialization
<button id="call-button">Call</button>
<script src="//media.twiliocdn.com/sdk/js/client/v1.13/twilio.min.js"></script>
<script>
let device;
// Assume that the frontend already knows the user ID or session ID
const userId = 'example-user-id';
// Fetch the capability token from your backend
fetch('/token', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId })
})
.then(response => response.json())
.then(data => {
device = new Twilio.Device(data.token);
device.on('ready', () => {
console.log('Twilio.Device is ready to make the call');
});
device.on('error', (error) => {
console.error('Twilio.Device Error: ', error.message);
});
document.getElementById('call-button').addEventListener('click', () => {
device.connect(); // Initiates the call without exposing the number
});
});
</script>
const twilio = require('twilio');
const express = require('express');
const app = express();
app.use(express.json());
const accountSid = 'your_account_sid';
const authToken = 'your_auth_token';
const twilioAppSid = 'your_twilio_app_sid';
const client = twilio(accountSid, authToken);
// Endpoint to generate capability token
app.post('/token', async (req, res) => {
const { userId } = req.body;
// Lookup the phone number using the userId
const phoneNumber = await getUserPhoneNumber(userId); // Implement this function to fetch the phone number from your DB
if (!phoneNumber) {
return res.status(404).json({ error: 'Phone number not found' });
}
// Generate the capability token
const capability = new twilio.jwt.ClientCapability({
accountSid: accountSid,
authToken: authToken
});
capability.addScope(new twilio.jwt.ClientCapability.OutgoingClientScope({
applicationSid: twilioAppSid
}));
const token = capability.toJwt();
// Send the token back to the frontend
res.json({ token: token });
});
// TwiML endpoint to handle the call logic
app.post('/voice', async (req, res) => {
const { userId } = req.body;
// Lookup the phone number using the userId
const phoneNumber = await getUserPhoneNumber(userId); // Implement this function to fetch the phone number from your DB
if (!phoneNumber) {
return res.status(404).send('Phone number not found');
}
const twiml = new twilio.twiml.VoiceResponse();
twiml.dial({
callerId: 'your_twilio_number'
}).number(phoneNumber); // This tells Twilio to dial the number associated with the userId
res.type('text/xml');
res.send(twiml.toString());
});
async function getUserPhoneNumber(userId) {
// Replace with actual DB lookup logic
// Example return format:
return '+1234567890'; // This should be the user's phone number
}
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment