==> Twilio Account more info instagram - mr.mori_vinay WhatsApp: 9067954201
Add White List Number: Phone Numbers Manage > Verified Caller IDs > Add a new Caller ID button after select country > after add number > show OTP > then call then enter this OTP in your call 6 digits number OTP.
Create new TwiML App: Phone Numbers > Manage > TwiML App.
Click Top right Create new TwiML App Button Add Friendly Name like your app name.
After Voice Configuration add Request URL like this : https://voice-quickstart-server-nodes-7835.twil.io/make-call This Url only for demo here your function create URL add.
After Create button click then here your app create successfully.
Then Click Application name: COPY TwiML App SID : **********************************
Here we Update url after Save this TwiML App.
Make New API keys & Tokens: Click here this url then goto this page : https://console.twilio.com/us1/account/keys-credentials/api-keys
After Create API Key button click.
After Create new API keys then here add Friendly name after Create this API then open new automatic Copy secret key Screen.
Show this success message : You have successfully created a new API key in us1. Please make sure to copy the secret key from this page. SID: ********************************** Secret: ********************************** After here checkBox click : Got it! I have saved my API key SID and secret in a safe place to use in my application. Then Done Button Click.
Add Credentials : Click this URL: https://console.twilio.com/us1/account/keys-credentials/credentials
Credentials : here show two option public key and Push credentials so here click option two select Push credentials follow step 17.
Here click button : Create new Credential then open dialog.
This dialog inner add FRIENDLY NAME and TYPE and FCM SECRETE add. Example: Android & IOS (only type change) FRIENDLY NAME : pharmcrm-dev TYPE: FCM Push Credentials FCM SECRET:
Find FCM SECRET: Firebase Dev
COPY: CREDENTIAL SID (Dev) CREDENTIAL SID (Prod)
Services:
Here add all function code.
Here this all function are is protected so all the function is Public.
Like my number is +99999999999 so this number use our function and application.
After this number click and add function
Voice configuration : Click A call comes in
by default web hook selected then select Function.
Service: by default here Default select I am select my voice-quickstart-server-nodes.
Environment: UI select.
Function Path: here my /Incoming-call function select.
Save Configuration
Now Calling functionality Done.
—————————————————— Functions —————————————————
make-call
const AccessToken = require('twilio').jwt.AccessToken;
const VoiceGrant = AccessToken.VoiceGrant;
const VoiceResponse = require('twilio').twiml.VoiceResponse;
/**
Creates an endpoint that can be used in your TwiML App as the Voice Request Url.
In order to make an outgoing call using Twilio Voice SDK, you need to provide a
TwiML App SID in the Access Token. You can run your server, make it publicly
accessible and use /makeCall endpoint as the Voice Request Url in your TwiML App.
@returns {Object} - The Response Object with TwiMl, used to respond to an outgoing call
@param context
@param event
@param callback
*/
exports.handler = function(context, event, callback) {
// The recipient of the call, a phone number or a client
console.log(event);
const from = event.From;
let to = event.to;
if (isEmptyOrNull(to)) {
to = event.To;
if (isEmptyOrNull(to)) {
console.error("Could not find someone to call");
to = undefined;
}
}
const voiceResponse = new VoiceResponse();
if (!to) {
voiceResponse.say("Welcome, you made your first call.");
} else if (isNumber(to)) {
const dial = voiceResponse.dial({ callerId: from });
dial.number(to);
} else {
console.log(Calling [${from}] -> [${to}]);
const dial = voiceResponse.dial({ callerId: from, timeout: 30, record: "record-from-answer-dual", trim: "do-not-trim"});
dial.client(to);
}
callback(null, voiceResponse);
}
const isEmptyOrNull = (s) => {
return !s || s === '';
}
const isNumber = (s) => {
return !isNaN(parseFloat(s)) && isFinite(s);
}
———————————————————————————————————————————————
incoming-call
const AccessToken = require('twilio').jwt.AccessToken;
const VoiceGrant = AccessToken.VoiceGrant;
const VoiceResponse = require('twilio').twiml.VoiceResponse;
const axios = require('axios'); // Ensure axios is required
/**
Returns a specific string based on the toClient value.
@param {string} toClient - The client number to check.
@returns {string} - The corresponding string for the toClient value.
*/
const getClientSpecificString = (toClient) => {
switch (toClient) {
case '+999999999':
return 'valcare_789';
case '+665115166536512':
return 'asdsdkhdkahsdkashd';
case '+155478901':
return 'stringForClient1';
case '+155655478902':
return 'stringForClient2';
case '+356433543453':
return 'stringForClient3';
default:
return 'defaultString';
}
};
/**
Handles the call and dials a client or a number based on the To parameter.
@returns {Object} - The Response Object
@param context
@param event
@param callback
*/
exports.handler = async function(context, event, callback) {
// Get the fromNumber from the event
const fromNumber = event.From || event.Caller || event.CallerNumber;
// const storeNumber = event.extraOptions; // API Testing Store Number not get
console.log("From Number:", fromNumber);
// Get the toClient from the event
const toClient = event.To || 'valcare_123';
console.log("To Client:", toClient);
// Create a voiceResponse object
const voiceResponse = new VoiceResponse();
try {
// Call your API to get whitelisted numbers
const response = await axios.get('https://voice-quickstart-server-nodes-4119.twil.io/white-list');
const whitelistedNumbers = response.data;
console.log('Whitelisted Numbers:', whitelistedNumbers);
// Check if fromNumber is in the list of whitelisted numbers
const isWhitelisted = whitelistedNumbers.includes(fromNumber);
if (isWhitelisted) {
// Get the specific string for the given toClient
const specificString = getClientSpecificString(toClient);
console.log('Specific String for toClient:', specificString);
// Dial the client if fromNumber is whitelisted
const dial = voiceResponse.dial({
callerId: fromNumber,
timeout: 30,
record: "record-from-answer-dual",
trim: "trim-silence"
});
dial.client(specificString);
} else {
console.log('Non-whitelisted Call:');
console.log('From Number:', fromNumber);
console.log('To Client:', toClient);
// Dial the number if fromNumber is not whitelisted
const dial = voiceResponse.dial({
callerId: fromNumber
});
dial.number('9067954201'); // Vinay Mori
// dial.number(storeNumber); // API fetching store No. not get
}
callback(null, voiceResponse.toString());
} catch (error) {
console.error('Error fetching whitelisted numbers:', error);
// Handle the error accordingly
callback(error);
}
};
const isEmptyOrNull = (s) => {
return !s || s === '';
}
const isNumber = (s) => {
return !isNaN(parseFloat(s)) && isFinite(s);
}
———————————————————————————————————————————————
white-list
const twilio = require('twilio');
// Your Twilio Account SID and Auth Token
const accountSid = '**********************************';
const authToken = '**********************************';
// Create a Twilio client
const client = new twilio(accountSid, authToken);
exports.handler = async function(context, event, callback) {
try {
// Fetch the list of verified caller IDs
const callerIds = await client.outgoingCallerIds.list();
// Extract the verified caller IDs
const verifiedCallerIds = callerIds.map(callerId => callerId.phoneNumber);
console.log('Verified Caller IDs:', verifiedCallerIds);
// Return the list of verified caller IDs as JSON
callback(null, verifiedCallerIds);
} catch (error) {
console.error('Error fetching verified caller IDs:', error);
callback(error);
}
}
———————————————————————————————————————————————
generate-access-token
const twilio = require('twilio');
exports.handler = function (context, event, callback) {
const TWILIO_ACCOUNT_SID = '**********************************';
const TWILIO_API_KEY = '**********************************';
const TWILIO_API_SECRET = '**********************************';
const TWILIO_APPLICATION_SID = '**********************************';
const ANDROID_PUSH_CREDENTIAL_SID_DEV = '**********************************';
const ANDROID_PUSH_CREDENTIAL_SID_PROD = '**********************************';
const IOS_PUSH_CREDENTIAL_SID_SANDBOX = '**********************************';
const IOS_PUSH_CREDENTIAL_SID_PRODUCTION ='**********************************';
const identity = event.identity;
const platform = event.platform;
const isProduction = event.isProduction;
if (!identity || !platform) {
return callback(null, {
statusCode: 400,
message: 'Identity and platform are required',
});
}
try {
const AccessToken = twilio.jwt.AccessToken;
const VoiceGrant = AccessToken.VoiceGrant;
let pushCredentialSid = null;
if (platform === 'ios') {
pushCredentialSid = isProduction ? IOS_PUSH_CREDENTIAL_SID_PRODUCTION : IOS_PUSH_CREDENTIAL_SID_SANDBOX;
} else if (platform === 'android') {
pushCredentialSid = isProduction ? ANDROID_PUSH_CREDENTIAL_SID_PROD : ANDROID_PUSH_CREDENTIAL_SID_DEV;
} else {
return callback(null, {
statusCode: 400,
message: 'Invalid platform',
});
}
const voiceGrant = new VoiceGrant({
outgoingApplicationSid: TWILIO_APPLICATION_SID,
pushCredentialSid: pushCredentialSid,
incomingAllow: true,
});
const token = new AccessToken(TWILIO_ACCOUNT_SID, TWILIO_API_KEY, TWILIO_API_SECRET, { identity });
token.addGrant(voiceGrant);
const jwtToken = token.toJwt();
console.log('jwtToken is here :', jwtToken);
return callback(null, {
token: jwtToken,
});
} catch (error) {
return callback(null, {
statusCode: 500,
message: "Unable to generate token: ${error.message}",
});
}
};
———————————————————————————————————————————————
server
const twilio = require('twilio');
exports.handler = function (context, event, callback) {
const TWILIO_ACCOUNT_SID = '**********************************';
const TWILIO_API_KEY = '**********************************';
const TWILIO_API_SECRET = '**********************************';
const TWILIO_APPLICATION_SID = '**********************************';
const ANDROID_PUSH_CREDENTIAL_SID_DEV = '**********************************';
const ANDROID_PUSH_CREDENTIAL_SID_PROD = '**********************************';
const IOS_PUSH_CREDENTIAL_SID_SANDBOX = '**********************************';
const IOS_PUSH_CREDENTIAL_SID_PRODUCTION ='**********************************';
const identity = event.identity;
const platform = event.platform;
const isProduction = event.isProduction;
if (!identity || !platform) {
return callback(null, {
statusCode: 400,
message: 'Identity and platform are required',
});
}
try {
const AccessToken = twilio.jwt.AccessToken;
const VoiceGrant = AccessToken.VoiceGrant;
let pushCredentialSid = null;
if (platform === 'ios') {
pushCredentialSid = isProduction ? IOS_PUSH_CREDENTIAL_SID_PRODUCTION : IOS_PUSH_CREDENTIAL_SID_SANDBOX;
} else if (platform === 'android') {
pushCredentialSid = isProduction ? ANDROID_PUSH_CREDENTIAL_SID_PROD : ANDROID_PUSH_CREDENTIAL_SID_DEV;
} else {
return callback(null, {
statusCode: 400,
message: 'Invalid platform',
});
}
const voiceGrant = new VoiceGrant({
outgoingApplicationSid: TWILIO_APPLICATION_SID,
pushCredentialSid: pushCredentialSid,
incomingAllow: true,
});
const token = new AccessToken(TWILIO_ACCOUNT_SID, TWILIO_API_KEY, TWILIO_API_SECRET, { identity });
token.addGrant(voiceGrant);
const jwtToken = token.toJwt();
console.log('jwtToken is here :', jwtToken);
return callback(null, {
token: jwtToken,
});
} catch (error) {
return callback(null, {
statusCode: 500,
message: "Unable to generate token: ${error.message}",
});
}
};
——————————————————————————————————————————————————————