Twilio Integration in Dot Net Core/Dot Net 6
Osama Nasir
Senior Dot Net Developer | Back-End Developer | .NET | ASP.NET CORE | ASP.NET MVC | React | Entity Framework | Angular | SQL | Azure | AWS
Twilio is a cloud communications platform that allows developers to integrate various communication methods into their applications. It offers APIs for services such as:
Key Features
Use Cases
Install Dot Net Package :
Install-Package Twilio
Or
Add Package Refrence:
<ItemGroup>
<PackageReference Include="Twilio" Version="7.5.0" />
</ItemGroup>
GitHub SDK Link: https://github.com/twilio/twilio-csharp
.NET Core Command Line Tools:
dotnet add package Twilio
Code:
//Package Imports
using Twilio.Types;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
//Declaring Const Variables
const string AUTH_TOKEN = "Your AUTH_TOKEN";
const string ACCOUNT_SID = "Your ACCOUNT_SID";
//Phone Numbers Used to Send and Receive Messages and Calls
//You can get the SENDER_PHONE_NUMBER from Twilio Dashboard
const string SENDER_PHONE_NUMBER= "Your SENDER_PHONE_NUMBER";
const string RECIEVER_PHONE_NUMBER = "Your RECIEVER_PHONE_NUMBER";
//Initializing TwilioClient
领英推荐
TwilioClient.Init(ACCOUNT_SID, AUTH_TOKEN);
//Call the RECIEVER_PHONE_NUMBER
var call = CallResource.Create(
new PhoneNumber(RECIEVER_PHONE_NUMBER),
from: new PhoneNumber(SENDER_PHONE_NUMBER),
url: new Uri("https://my.twiml.here")
);
Console.WriteLine(call.Sid);
//Sending Message To RECIEVER_PHONE_NUMBER
var message = MessageResource.Create(
new PhoneNumber(RECIEVER_PHONE_NUMBER),
from: new PhoneNumber(SENDER_PHONE_NUMBER),
body: $"Hello World! From Twilio {SENDER_PHONE_NUMBER} to {SENDER_PHONE_NUMBER}"
);
Console.WriteLine(message.Sid);
Explanation:
There are many merhods available to initialize the TwilioClient in dot net core but we are using the below method with UserName and Password
public static void Init(string username, string password)
{
SetUsername(username);
SetPassword(password);
}
ACCOUNT_SID will act as a UserName and
AUTH_TOKEN will act as a Password
TwilioClient.Init(ACCOUNT_SID, AUTH_TOKEN);
Exception:
When you are calling on Phone Number you will face the below exception
Twilio.Exceptions.ApiException: 'Account not authorized to RECIEVER_PHONE_NUMBER call . Perhaps you need to enable some international permissions: https://www.twilio.com/console/voice/calls/geo-permissions/low-risk'
then go to the above mentioned/given link of the Twilio Account Dshboard and enable the low-risk permission and then you are able to Call using the Twilio Calling Api