Buy Twilio Number From Available Number List

In my previous article Get Available Twilio Number List Using C#, I described that how to get an available Twilio number list. In this article, I will let you know that how to buy a Twilio number from that available number list. So let’s start it.

Once you’ve found an available number you want to buy, make an HTTP POST request to the IncomingPhoneNumbers list resource¬†passing the number as the ‘PhoneNumber’ parameter.

Note: In a trial account, we can buy only one number at a time. For example, I already have one number and I want to buy another number then first I need to release that number and after this, I can buy a new number.

for this, I’m saving one more value during I’m getting a list of available numbers. When we call API to get available numbers, we need to save the PhoneNumber parameter from their response. This phone number is in E.164 format, which consists of a + followed by the country code and subscriber number. We need to pass this number to the API for the buy number.

For this, I have updated the function like below

public JsonResult GetLocalResourceNumberList()
{
    try
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        TwilioClient.Init(TwilioSID, TwilioTOKEN);

        List<Numbersre> LocalNumbers = new List<Numbersre>();
        var local = LocalResource.Read(areaCode: 256, pathCountryCode: "US");
        foreach (var number in local)
        {
            Numbersre Num = new Numbersre();
            Num.FriendlyName = number.FriendlyName.ToString();
            Num.PhoneNumber = number.PhoneNumber.ToString(); //Newly Added
            Num.Region = string.IsNullOrEmpty(number.Region) ? "" : number.Region;
            Num.IsoCountry = number.IsoCountry;
            LocalNumbers.Add(Num);
        }
        return Json(new { IsSuccess = true, Numbers = LocalNumbers }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        return Json(new { IsSuccess = false }, JsonRequestBehavior.AllowGet);
    }
}

In the above code, I have added this line Num.PhoneNumber = number.PhoneNumber.ToString();. You need to add this line in other functions also. As per the back-end changes, we need to update our front-end changes to replace LoadGrid() function.

function LoadGrid(data) {
    $("#NumberGrid").empty();
    var html = ``;
    html += `<table class="table table-hover table-striped table-borderless">`;
    html += `<tr>`;
    html += `<th class="text-center">Phone Number</th>`;
    html += `<th class="text-center">Region</th>`;
    html += `<th class="text-center">Country</th>`;
    html += `<th class="text-center">Buy</th>`;
    html += `</tr>`;
    for (var i = 0; i < data.length; i++) {
        html += `<tr>`;
        html += `<td>${data[i].FriendlyName}</td>`;
        html += `<td>${data[i].Region}</td>`;
        html += `<td>${data[i].IsoCountry}</td>`;
        html += `<td><a class="btn btn-primary buy" data-number="${data[i].PhoneNumber}">Buy</a></td>`;
        html += `</tr>`;
    }
    html += `</table>`;
    $("#NumberGrid").html(html);
}

here I have added code for the buy button and I have set the E.164 format number into that button as a data-number attribute.

After this all, I have created one new function for buy a number. The below is the code for that function.

public JsonResult BuyTwilioNumber(string Number)
{
    try
    {
        bool Status = false;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        TwilioClient.Init(TwilioSID, TwilioTOKEN);
        var incomingPhoneNumber = IncomingPhoneNumberResource.Create(phoneNumber: new Twilio.Types.PhoneNumber(Number));
        if (!String.IsNullOrEmpty(incomingPhoneNumber.Sid))
        {
            Status = true;
        }

        return Json(new { IsSuccess = Status, Number = Number }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        return Json(new { IsSuccess = false }, JsonRequestBehavior.AllowGet);
    }
}

I’m passing a Number from the front-end side which we select for buy in the above function.

Below is the Script function which will call the method to buy a number.

$(document).on('click', '.buy', function () {
    var number = $(this).attr("data-number");
    if (number == null || number == "" || number == "undefined") {
        alert("Something went wrong");
        return false;
    }
    $(".loaderWrap").show();
    $.ajax({
        method: "POST",
        url: "/Home/BuyTwilioNumber",
        data: { "Number": number },
        success: function (res) {
            if (res.IsSuccess == true) {
                alert("Your Number: " + res.Number + " Is Purchesd Succssfully.");
            }
            else {
                alert("Something went wrong");
            }
            $(".loaderWrap").hide();
        },
        error: function () {
            $(".loaderWrap").hide();
            alert("Something went wrong");
        }
    });
});

Final Output

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories