Getting A Mobile Number In An Alexa Skill

Introduction

 
In this article on custom Alexa skills, I am going to demonstrate how to get a user’s mobile number for use in a custom Alexa skill on Alexa Hosted node.js server. For that, I will be creating a custom Alexa skill named user information. With the help of this skill, Users can ask Alexa for a user’s mobile number to be used in custom Alexa skill and Alexa fetches a user’s mobile number from the Amazon account linked with that particular Alexa skill and returns the mobile number as part of the information about the user.
 
The users can ask Alexa for the mobile number by saying some sample utterances such as “what is my mobile number”, Alexa will respond by fetching and prompting the user’s mobile number accordingly. Alexa can also respond by prompting please enable profile permissions from the Amazon Alexa app. The backend code required for the Alexa skill to work will be stored in a lambda function inside the Amazon developer console.
 

Creating Alexa Skill

 
To create a new skill, first, we need to login to the Alexa developer console. We then need to mention the unique skill name and select the default language according to our location.
 
 
After that, we can choose a model to add to our skill. To create a custom skill, we can select custom model.
 
 
We can also choose a method or a template to host the skill’s backend code inside a lambda function.
 
 
We can choose Alexa hosted node.js or python template. We can also mention our own endpoint or server to store backend resources for the required Alexa skills.
 
The next step is to choose a template to add to our skill, which we customize later according to our need and click on the create a skill button.
 
Now as a skill has been created, we need to make adjustments to the skill’s frontend. Now I will be creating intents, slots, and custom slot types to create skill’s frontend. First, we need to mention the invocation name. Users say a skill's invocation name to begin an interaction with a particular custom skill.
 
 
Now we have to create intents.
 
 
Here, I have added a new intent named MobileIntent along with some sample utterances such as mobile number, what’s my mobile number, and what is my mobile number. No slots and custom slot types are defined for this Alexa skill.
 
After creating a model for a particular skill, we can save and build the model by clicking on the save model and build model button on the top.
 
Json code for the above frontend is as follows:
  1. {  
  2.     "interactionModel": {  
  3.         "languageModel": {  
  4.             "invocationName""contact info",  
  5.             "intents": [  
  6.                 {  
  7.                     "name""AMAZON.NavigateHomeIntent",  
  8.                     "samples": []  
  9.                 },  
  10.                 {  
  11.                     "name""AMAZON.CancelIntent",  
  12.                     "samples": []  
  13.                 },  
  14.                 {  
  15.                     "name""AMAZON.HelpIntent",  
  16.                     "samples": []  
  17.                 },  
  18.                 {  
  19.                     "name""AMAZON.StopIntent",  
  20.                     "samples": []  
  21.                 },  
  22.                                   
  23.                 {  
  24.                     "name""MobileIntent",  
  25.                     "slots": [],  
  26.                     "samples": [  
  27.                         "mobile",  
  28.                         "phone",  
  29.                         "mobile number",  
  30.                         "what is my mobile number",  
  31.                         "what is my phone number"  
  32.                     ]  
  33.                 }  
  34.             ],  
  35.             "types": []  
  36.         }  
  37.     }  
  38. }  

Creating the backend resource for the Alexa skill

 
To create backend code inside the lambda function, we can write code inside the index.js node.js file. The code for the custom Alexa skill is as follows:
  1. const Alexa = require('ask-sdk-core');  
  2.   
  3. const messages = {  
  4.   NOTIFY_MISSING_PERMISSIONS: 'Please enable profile permissions in the Amazon Alexa app.',  
  5.   ERROR: 'Uh Oh. Looks like something went wrong.'  
  6. };  
  7.   
  8. const MOBILE_PERMISSION = "alexa::profile:mobile_number:read";  
  9.   
  10. const LaunchRequestHandler = {  
  11.   canHandle(handlerInput) {  
  12.     return handlerInput.requestEnvelope.request.type === 'LaunchRequest';  
  13.   },  
  14.   handle(handlerInput) {  
  15.       
  16.     const speechText = `Hello. You can say: what's my mobile number.`;  
  17.       
  18.     const reprompt = `say: what's my mobile number.`;  
  19.       
  20.     return handlerInput.responseBuilder  
  21.       .speak(speechText)  
  22.       .reprompt(reprompt)  
  23.       .getResponse();  
  24.   },  
  25. };  
  26.   
  27. const MobileIntentHandler = {  
  28.   canHandle(handlerInput) {  
  29.     return handlerInput.requestEnvelope.request.type === 'IntentRequest'  
  30.       && handlerInput.requestEnvelope.request.intent.name === 'MobileIntent';  
  31.   },  
  32.   async handle(handlerInput) {  
  33.     const { serviceClientFactory, responseBuilder } = handlerInput;  
  34.     try {  
  35.       const upsServiceClient = serviceClientFactory.getUpsServiceClient();  
  36.       const profileMobileObject = await upsServiceClient.getProfileMobileNumber();  
  37.       if (!profileMobileObject) {  
  38.         const errorResponse = `It looks like you are not having a mobile number set. You can set your mobile number from the companion app.`  
  39.         return responseBuilder  
  40.                       .speak(errorResponse)  
  41.                       .getResponse();  
  42.       }  
  43.       const profileMobile = profileMobileObject.phoneNumber;  
  44.       const speechResponse = `Your mobile number is, ${profileMobile}`;  
  45.         
  46.       return responseBuilder  
  47.                       .speak(speechResponse)  
  48.                       .getResponse();  
  49.     } catch (error) {  
  50.       console.log(JSON.stringify(error));  
  51.       if (error.statusCode === 403) {  
  52.         return responseBuilder  
  53.         .speak(messages.NOTIFY_MISSING_PERMISSIONS)  
  54.         .withAskForPermissionsConsentCard([MOBILE_PERMISSION])  
  55.         .getResponse();  
  56.       }  
  57.       console.log(JSON.stringify(error));  
  58.       const response = responseBuilder.speak(messages.ERROR).getResponse();  
  59.       return response;  
  60.     }  
  61.   },  
  62. }  
  63.   
  64. const HelpIntentHandler = {  
  65.   canHandle(handlerInput) {  
  66.     return handlerInput.requestEnvelope.request.type === 'IntentRequest'  
  67.       && handlerInput.requestEnvelope.request.intent.name === 'AMAZON.HelpIntent';  
  68.   },  
  69.   handle(handlerInput) {  
  70.     const speechText = 'You can say hello to me!';  
  71.   
  72.     return handlerInput.responseBuilder  
  73.       .speak(speechText)  
  74.       .reprompt(speechText)  
  75.       .withSimpleCard('Hello World', speechText)  
  76.       .getResponse();  
  77.   },  
  78. };  
  79.   
  80. const CancelAndStopIntentHandler = {  
  81.   canHandle(handlerInput) {  
  82.     return handlerInput.requestEnvelope.request.type === 'IntentRequest'  
  83.       && (handlerInput.requestEnvelope.request.intent.name === 'AMAZON.CancelIntent'  
  84.         || handlerInput.requestEnvelope.request.intent.name === 'AMAZON.StopIntent');  
  85.   },  
  86.   handle(handlerInput) {  
  87.     const speechText = 'Goodbye!';  
  88.   
  89.     return handlerInput.responseBuilder  
  90.       .speak(speechText)  
  91.       .getResponse();  
  92.   },  
  93. };  
  94.   
  95. const SessionEndedRequestHandler = {  
  96.   canHandle(handlerInput) {  
  97.     return handlerInput.requestEnvelope.request.type === 'SessionEndedRequest';  
  98.   },  
  99.   handle(handlerInput) {  
  100.     console.log(`Session ended with reason: ${handlerInput.requestEnvelope.request.reason}`);  
  101.   
  102.     return handlerInput.responseBuilder.getResponse();  
  103.   },  
  104. };  
  105.   
  106. const ErrorHandler = {  
  107.   canHandle() {  
  108.     return true;  
  109.   },  
  110.   handle(handlerInput, error) {  
  111.     console.log(`Error handled: ${error.message}`);  
  112.   
  113.     return handlerInput.responseBuilder  
  114.       .speak('Sorry, I can\'t understand the command. Please say again.')  
  115.       .reprompt('Sorry, I can\'t understand the command. Please say again.')  
  116.       .getResponse();  
  117.   },  
  118. };  
  119.   
  120. const skillBuilder = Alexa.SkillBuilders.custom();  
  121.   
  122. exports.handler = skillBuilder  
  123.   .addRequestHandlers(  
  124.     LaunchRequestHandler,  
  125.     MobileIntentHandler,  
  126.     HelpIntentHandler,  
  127.     CancelAndStopIntentHandler,  
  128.     SessionEndedRequestHandler  
  129.   )  
  130.     
  131.   .addErrorHandlers(ErrorHandler)  
  132.   .withApiClient(new Alexa.DefaultApiClient())  
  133.   .lambda();  
To receive request from the user, request handlers are created for each intent to handle. Inside each handlers, canHandle and handle functions are defined.
 
The canHandle() function is where you define what requests the handler responds to. The handle() function returns a response to the user. If your skill receives a request, the canHandle() function within each handler determines whether or not that handler can service the request.
 
LaunchRequestHandler
 
In this case, the user wants to launch the skill, which is a LaunchRequest. Therefore, the canHandle() function within the LaunchRequestHandler will let the SDK know it can fulfill the request. In computer terms, the canHandle returns true to confirm it can do the work.
With the help of the handle() function inside LaunchRequestHandler, Alexa greets a user by saying “Hello” and tells the user to say “what is my mobile number” to fetch and prompt the user’s mobile number.
 
MobileIntentHandler
 
After that, the MobileIntent Handler is defined to handle each and every user's request to ask Alexa to fetch and provide the user’s mobile number, whosoever has to enable this particular skill on their Amazon Alex app.
 
This handler will configure the skill to ask a user for permission to read his/her mobile number so that Alexa can fetch and provide user’s mobile number without having to ask for permission to access the user’s mobile number.
 
As we can see from the above code, inside the handle() function of MobileIntentHandler, the ServiceClientFactory is available to the handlers via the HandlerInput container object. It takes care of creating individual service client and configuring the ApiAccessToken and ApiEndpoint.
 
UpsServiceClient
 
UpsServiceClient can be used to query Alexa Customer Profile API for customer contact information and Alexa Customer Settings API for customer preferences of time zone, distance measuring, and temperature measurement unit.
The getProfileMobileNumber() method inside UpsServiceClient class returns string containing user’s mobile number.
 
Request Customer Contact Information for Use in Your Skill
 
When a customer enables your Alexa skill, your skill can request the customer's permission to their contact information, which includes name, email address, and phone number, if the customer has consented. You can then use this data to support personalized intents to enhance the customer experience without account linking.
 
To enable this skills capability to request the customer's permission to their contact information, the following steps needs to be taken
  • If you are using the developer console to manage your skill, configure your skill as follows:
  • Edit your skill in the developer console.
  • Navigate to the Build -> Permissions page in the console.
  • Select the Customer mobile number.
Sample response with permissions card
 
To query the Alexa Customer Profile API for customer contact information permissions card for requesting customer consent is required to define. Particular skills can display a special permissions card to ask customers for consent dynamically.
 
An in-session interaction can return a response that includes the new AskForPermissionsConsent card. 
 
The permission value for the mobile number is alexa::profile:mobile_number:read. 
 
The permission value always matches the scope that you declared for the skill on the Build -> Permissions page in the developer console. 
 
Output
 
 
As we can see from the output above, to invoke a skill, a user can say open followed by invocation name. Here contact info is an invocation name to invoke this skill. Once the skill is invoked, Alexa greets the user by saying hello and tells the user to say what is my mobile number, so that Alexa can fetch and provide the user’s mobile number.
 
If a user responds through a sample utterance that is by saying “what is my mobile number”, then Alexa will fetch and provide the user’s mobile number.
 
If this skill has permission to access the user’s mobile number then Alexa will return a string containing the user’s mobile number. If this skill does not have any permission to access the user’s mobile number then Alexa will prompt a message saying “Please enable profile permissions in Amazon Alexa app”.
 

Summary

 
In this article, I created a custom Alexa skill. I also defined the invocation name, intents, and sample utterances. I demonstrated how to get a user’s mobile number for use in a custom Alexa skill and how Alexa fetches a user’s mobile number from the amazon account linked with that particular Alexa skill and returns the mobile number as part of information about the user. Proper coding snippets along with the output for the backend of the skill is also provided.