Mobile Number Verification using REST API in lightning

What is API?

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other. Each time you use an app like Facebook, send an instant message, or check the weather on your phone, you’re using an API.

What Is an Example of an API?

When you use an application on your mobile phone, the application connects to the Internet and sends data to a server. The server then retrieves that data, interprets it, performs the necessary actions and sends it back to your phone. The application then interprets that data and presents you with the information you wanted in a readable way. This is what an API is – all of this happens via API.

To explain this better, let us take a familiar example.

Imagine you’re sitting at a table in a restaurant with a menu of choices to order from. The kitchen is the part of the “system” that will prepare your order. What is missing is the critical link to communicate your order to the kitchen and deliver your food back to your table. That’s where the waiter or API comes in. The waiter is the messenger – or API – that takes your request or order and tells the kitchen – the system – what to do. Then the waiter delivers the response back to you; in this case, it is the food.

Image result for rest api lifecycle
Image result for rest api salesforce

REST API

REST API is a simple and powerful web service based on RESTful principles. It exposes all sorts of Salesforce functionality via REST resources and HTTP methods. For example, you can create, read, update, and delete (CRUD) records, search or query your data, retrieve object metadata, and access information about limits in your org. REST API supports both XML and JSON.

Because REST API has a lightweight request and response framework and is easy to use, it’s great for writing mobile and web apps.

Example of Rest API in Salesforce

We will be taking numverify API as an example to demonstrate the REST API capability.

Quick background of the API, this API is used to validate the Phone Numbers (from about 200+ countries).

To start Follow the https://numverify.com/ link and sign up for a free account.

Once signed up you will get access key on registered email, for example:”641e14e26b85429814687563a971a5d7”.

You can test the API working on the User interface provided on numverify site to see how it is working.

Now let’s build the same on salesforce using REST API.

  1. Remote site 

Add a remote site in salesforce.

Go to Setup 🡪 search remote site in quick find🡪 create a new remote site with the name of your choice and in Remote site URL type: http://apilayer.net 

  1. Let’s make a lightning component to add the Look and feel.

Component :-

<aura:component controller="numverify" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
<!-- define attribute-->
<aura:attribute name="DataFromCall" type="object" default="IN"/>
<aura:attribute name="Number" type="string"/>
<aura:attribute name="diallingCode" type="string" default="+91"/>
<aura:attribute name="countryVsCode" type="Map"/>
<aura:attribute name="NumresponseAPIResult" type="boolean" default="false"/>
<aura:attribute name="resultData" type="Map"/>
<aura:attribute name="selectedValue" type="string" access="PRIVATE" />
<aura:attribute name="isLoading" type="boolean" default="False"/>
<aura:attribute name="selectedCode" type="String" access="PRIVATE"/>
<aura:attribute name="selectedDialcode" type="String" access="PRIVATE" default="+91" />
<!-- Call handler-->
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:if isTrue="{!v.isLoading}">  
    <lightning:spinner alternativeText="Loading" size="medium" />
</aura:if>
<!-- layout Design-->
<lightning:layout class="slds-page-header slds-page-header--object-home">
    <lightning:layoutItem>
        <lightning:icon iconName="standard:scan_card" alternativeText="Number verify"/>
    </lightning:layoutItem>
    <lightning:layoutItem padding="horizontal-small">
        <div class="page-section page-header">
            <h1 class="slds-text-heading--label">Phone Verify</h1>
        </div>
    </lightning:layoutItem>
</lightning:layout>
<lightning:layout> 
    <lightning:layoutItem flexibility="auto" padding="horizontal-medium">
        <fieldset class="slds-box slds-theme--default slds-container--small">
            <legend id="newexpenseform" class="slds-text-heading--small slds-p-vertical--medium">
                Verify Number
            </legend>
            <lightning:layout>
                <div class="slds-col">
                    <aura:if isTrue="{!v.selectedValue!=''}">
                        <img src="{!'https://www.countryflags.io/'+v.selectedValue+'/shiny/64.png'}"/>
                    </aura:if>
                    <lightning:select aura:id='countryPicklist' name="select1" label="Country" value="{!v.selectedValue}" onchange="{!c.ValueChange}">
                        <option text="--None--" value=""/>
                        <aura:iteration items="{!v.countryVsCode}" var="code">
                            <option text="{!code.countryName}" value="{!code.countryCode}"/>
                        </aura:iteration>
                    </lightning:select>
                </div>
            </lightning:layout> 
            
            <aura:if isTrue="{!v.selectedValue!=''}">
                <form class="slds-form--stacked">  
                    <span><lightning:input disabled="true" label="Country Code" value="{!v.selectedDialcode}"/></span> 
                    <span><lightning:input type="tel" label="Enter Phone Number" value="{!v.Number}" maxlength="10"/></span> 
                    <lightning:button label="Validate" 
                        disabled="{!v.Number.length!=10}"
                        class="slds-m-top--medium"
                        variant="brand"
                        onclick="{!c.validateNum}"/>
                </form>
            </aura:if>
        </fieldset>
    </lightning:layoutItem>
</lightning:layout>
        <aura:if isTrue="{!v.NumresponseAPIResult}">
        <lightning:layoutItem flexibility="auto" padding="horizontal-medium">
            <fieldset class="slds-box slds-theme--default slds-container--medium">
                <legend id="Verifynum" class="slds-text-heading--small slds-p-vertical--medium">
                    Result<lightning:icon title="Result" iconName="action:call" size="x-small"/>
                </legend> 
                <form class="slds-form--stacked"> 
                    <table> 
                        <tbody>
                            <tr> 
                                <td>Valid</td>
                                <aura:if isTrue="{!v.DataFromCall.valid}">
                                    <td> <lightning:icon iconName="action:approval" alternativeText="Valid" size=" x-small"/></td>
                                    <aura:set attribute="else">
                                        <td> <lightning:icon iconName="action:close" alternativeText="Invalid" size="x-small"/></td>
                                    </aura:set>
                                </aura:if> 
                            </tr><br/>
                            <tr> 
                                <td>Local Format</td>
                                <td>{!v.DataFromCall.local_format}</td>
                            </tr><br/>
                            <tr> 
                                <td>Country</td>
                                <td>{!v.DataFromCall.country_name}</td>
                            </tr><br/>
                            <tr> 
                                <td>Location</td>
                                <td>{!v.DataFromCall.location}</td>
                            </tr><br/>
                            <tr> 
                                <td>Carrier</td>
                                <td>{!v.DataFromCall.carrier}</td>
                            </tr><br/>
                            <tr> 
                                <td>Line Type</td>
                                <td>{!v.DataFromCall.line_type}</td>
                            </tr> 
                        </tbody>
                    </table> 
                    <div class="slds-col" style="Width:50%">
                        <span></span>
                    </div>
                </form>
            </fieldset>
        </lightning:layoutItem>
    </aura:if>
</aura:component>

Controller:-

({
	doInit : function(component, event, helper) {
		helper.countryCodeDoInit(component, event,helper);
	},
    ValueChange:function(component, event, helper) {
        helper.CodeValueChanged(component, event,helper);
    },
    validateNum :function(component, event, helper) {
        helper.handleValidateNum(component, event, helper)
    },
})

Helper:-

({
	countryCodeDoInit : function(component, event,helper) {
        component.set('v.isLoading',true);
        var action = component.get('c.countryCodeDoInit');
        //action.setStorable();
        action.setCallback(this,function(response){
            var result = response.getReturnValue();
             component.set('v.resultData',result);
            console.log(component.get('v.resultData'));
            var arr=[];
          	for(var key in result)
            {  
                arr.push({countryCode:key,countryName:result[key].country_name,dialCode:result[key].dialling_code});
            }
            component.set('v.countryVsCode',arr);
            component.set('v.isLoading',false);
        },'SUCCESS');
		$A.enqueueAction(action);
	},
    CodeValueChanged :function(component, event,helper) {
        component.set('v.NumresponseAPIResult',false);
        var selValue =component.get('v.selectedValue');
        var resultdata =component.get('v.resultData');
        var SelectedData = resultdata[selValue];
        if(!$A.util.isUndefined(SelectedData))
        {
            component.set('v.selectedDialcode',SelectedData.dialling_code);
        }
        else
        {
              component.set('v.NumresponseAPIResult',false);
        }
    },
    handleValidateNum :function(component, event,helper) {
        component.set('v.isLoading',true);
        //server call to get the result 
        var action = component.get('c.CallRestAPI');
        action.setParams({'num':component.get('v.Number'),
                          'countryCode':component.get('v.selectedValue')})
        action.setCallback(this,function(response){
            var result = response.getReturnValue();
             component.set('v.DataFromCall',result);
            console.log(component.get('v.DataFromCall'));
            component.set('v.NumresponseAPIResult',true);
            component.set('v.isLoading',false);
        },'SUCCESS');
		$A.enqueueAction(action);
    },
})

Apex class:-

public class numverify {
    
    @AuraEnabled
    Public static Map<String, Object> countryCodeDoInit()
    {
        
        string accessKey =system.label.AccessKey;
        string endPoint='http://apilayer.net/api/countries?access_key='+accesskey;
        httpRequest Req = new httpRequest();
        req.setMethod('GET');
        req.setEndpoint(endpoint);
        http http = new  http();
        Map<String, Object> ResponseMap = new  Map<String, Object>();
        try{
            httpResponse resp =http.send(Req);
            if(resp.getStatusCode()==200)
            {
                ResponseMap = (Map<String, Object>) JSON.deserializeUntyped(resp.getBody());
            }
            
        }
        catch(exception ex)
        {
            system.debug('ex '+ex.getMessage());
        }
        return ResponseMap;
    }
    @AuraEnabled
    public static resultWrap CallRestAPI(string num,string countryCode)
        
    {
         string accessKey =system.label.AccessKey;
        string endpoint='http://apilayer.net/api/validate?'+
            'access_key='+accesskey+
            '& number ='+num+
            '& country_code='+countryCode+
            '&format = 1';
        httpRequest Req = new httpRequest();
        req.setMethod('GET');
        req.setEndpoint(endpoint);
        http http = new  http();
        Map<String, Object> ResponseMap = new  Map<String, Object>();
        string Response ='';
        resultWrap  Wrap = new resultWrap();
        try{
            httpResponse resp =http.send(Req);
            if(resp.getStatusCode()==200)
            {
                ResponseMap = (Map<String, Object>) JSON.deserializeUntyped(resp.getBody());
                wrap.valid =(boolean)ResponseMap.get('valid');
                wrap.local_format =(string)ResponseMap.get('local_format');
                wrap.dial_code =(string)ResponseMap.get('dial_code');
                wrap.country_code =(string)ResponseMap.get('country_code');
                wrap.country_name =(string)ResponseMap.get('country_name');
                wrap.location =(string)ResponseMap.get('location');
                wrap.carrier =(string)ResponseMap.get('carrier');
                wrap.line_type =(string)ResponseMap.get('line_type');
                wrap.intl_formal = (string)ResponseMap.get('intl_formal');
            }
            system.debug('Response '+Response);
        }
        catch(exception ex)
        {
            system.debug('ex '+ex.getMessage());
        }
        return Wrap;
    }
    
    public class resultWrap{
        @auraEnabled public boolean valid{get;set;}
        @auraEnabled public  string local_format{get;set;}
        @auraEnabled public  string intl_formal{get;set;}
        @auraEnabled public  string dial_code{get;set;}
        @auraEnabled public string country_code{get;set;}
        @auraEnabled public  string country_name{get;set;}
        @auraEnabled public  string location{get;set;}
        @auraEnabled public  string carrier{get;set;}
        @auraEnabled public  string line_type{get;set;}
        
    }
}

Hope you enjoy the article. Please subscribe the website and join our group for the latest updates.