Utility Script Use Cases

Calling an API

Based on user input, we retrieve data from an API and display the response to the end user. We support API calls using GET and POST methods, storing the responses in variables and using them in further interactions.

Example Implementation

Here, the user's input is stored in a variable called bookId, which is passed into the API call:

const response = await fetch('https://simple-books-api.glitch.me/books/'+_flow_variables.book_Id, {
       method: 'GET',
       redirect: 'follow'
   });
const result = await response.json();
_flow_variables.single_book_detail = result;
_flow_variables.book_name = result.name;
_flow_variables.book_author = result.author;
_flow_variables.book_type = result.type;
_flow_variables.book_price = result.price;
_flow_variables.book_availability = result.available;

// return JSON.stringify(result)
return "result";

The API response is stored in flow variables and displayed to the end user. MSG91's editor supports the fetch method for API calls.


Sending and Verifying OTP

When a specific event occurs, an OTP is sent to the user's mobile number via SMS. The user then enters the OTP in WhatsApp, and once verified, the bot confirms the authentication.

Sending OTP

const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/JSON");

const requestOptions = {
 method: "POST",
 headers: myHeaders,
 body: {}
};

const response = await fetch('https://control.msg91.com/api/v5/otp?template_id=679a05f7d6fc05753b6d9b82&mobile='+_flow_variables.customer_mobile+'&authkey=', requestOptions);
const result = await response.json();

if(result.type === "success"){
   return "true";
} else {
   return "false";
}

Once the mobile number is passed, the API sends a 4-digit OTP to the recipient.

Verifying OTP

const myHeaders = new Headers();
myHeaders.append("authkey", "");  //enter the auth key

const requestOptions = {
 method: "GET",
 headers: myHeaders,
 redirect: "follow"
};

const response = await fetch('https://control.msg91.com/api/v5/otp/verify?otp='+ _flow_variables.otp+'&mobile='+_flow_variables.customer_mobile, requestOptions);
const result = await response.json();

if(result.message === "OTP verified success"){
   return "true";
} else {
   return "false";
}

Here, the user's OTP input is stored in a variable and verified using the API. If the OTP is correct, the bot proceeds with the conversation flow.


Prev
Next