Serverless Functions - Using OAuth2

Serverless Functions - Using OAuth2

Introduction

Functions can be made accessible through OAuth2 protocol. OAuth2 method allows you to share specific data with any application while keeping your usernames and passwords private, by having specific scopes which grant access to specfic data.

In order to make a function available through OAuth2 method, you need to first register your client with Zoho CRM. Please take a look here to know how to register your client application.

However, there are some key points that need to be noted

The scope for the client when using the HTTP GET Method should be:
  1. ZohoCRM.functions.execute.READ
The scope for the client when using the HTTP POST Method should be:
  1. ZohoCRM.functions.execute.CREATE
Once the authentication is done, you can proceed with creating your function.

See also

There are a lot of different situations where a function which is available as an API can be put to use. For instance, a function can be set to trigger whenever a certain limit has been crossed in statistical data of the performance of a company. This document is to give you a sample function which is triggered through external sources, where the function is provided as an API.

Sample function

Scenario

Say there is a requirement to get consent from customers and have them sign up for newsletters. This is to enable security and not infringe on their privacy.

You can have a button in View Page of a Contact record. The button can open a Widget, which pulls up a Subscription form(to be filled by your Agents). To create widgets, please refer our Widgets help.

Through the widget, the subscription form is submitted. Post which an email with the consent form is sent to the customer. After the customer accepts the consent form, the information about the contact is added to the MailChimp campaign list.

Required Applications

MailChimp - for Newsletter
Google Drive - Consent Form

Requirements

  1. Create Connections For MailChimp and Google Drive.
  2. Call MailChimp and Google Drive API in this Function.
  3. Turn the Function into an API.
  4. Create a Widget and invoke the Function within it.

Making the connection

In order for the Function to make use of third-party applications and facilitate data transfer, you need to first set up a connection between Zoho CRM and the said third-party software. In this case, it would be MailChimp and Google Drive. Read more.

For MailChimp



For Google Drive


Create the Function

The steps to create the function according to the requirement is split into 2 parts.

Part 1: Write the function code

Create a standalone function with the following code.



The Function Code is
  1. string subscribeNewsletter(string listId,string emailAddress,string extraDetails){
  2.     mailChimpURL = "https://us18.api.mailchimp.com/3.0/";
  3.     if(isNull(listId))
  4.     {
  5.         //Default List
  6.         listId = "2a9a3690fd";
  7.     }
  8.     if(isNull(emailAddress))
  9.     {
  10.         return "Email Address cannot be null";
  11.     }
  12.     //Get all members
  13.     membersList = invokeurl
  14.     [
  15.         url :mailChimpURL + "/lists/" + listId + "/members"
  16.         type :GET
  17.         parameters:""
  18.         connection:<CONNECTION_LINKNAME>
  19.     ];
  20.     //Is Member already in List
  21.     for each memberInfo in membersList.get("members")
  22.     {
  23.         if(emailAddress.equals(memberInfo.get("email_address")))
  24.         {
  25.             return "The member is already subscribed to Zoho Newsletter";
  26.         }
  27.     }
  28.     //Get all Documents from Google Drive
  29.     gdriveURL = "https://www.googleapis.com/drive/v2/files";
  30.     fileList = invokeurl
  31.     [
  32.         url :gdriveURL
  33.         type :GET
  34.         parameters:""
  35.         connection:<CONNECTION_LINKNAME>
  36.     ];
  37.     //Get Download URL of Consent Form
  38.     webContentLink = null;
  39.     for each fileInfo in fileList.get("items")
  40.     {
  41.         title = fileInfo.get("title");
  42.         if(title.equals("Consent-Form.docx"))
  43.         {
  44.             webContentLink = fileInfo.get("webContentLink");
  45.             break;
  46.         }
  47.     }
  48.     if(isNull(webContentLink))
  49.     {
  50.         return "No Document Found on Drive. Docuemnt Name ::: Consent-Form.docx";
  51.     }
  52.     //Send Notification
  53.     name = "Guest";
  54.     signature = "Zoho";
  55.     if(!isNull(extraDetails))
  56.     {
  57.         if(extraDetails.contains("name"))
  58.         {
  59.             name = extraDetails.get("name");
  60.         }
  61.         if(extraDetails.contains("signature"))
  62.         {
  63.             signature = extraDetails.get("signature");
  64.         }
  65.     }
  66.     sendmail
  67.     [
  68.         from :zoho.adminuserid
  69.         to :emailAddress
  70.         subject :"consent form"
  71.         message :"Hi " + name + ",<expression></expression><div><br></div><div>Before subscribing to Zoho Newsletter, </div><br /><div>Please download the <br /><a target='_blank' href='" + webContentLink + "'>Consent Form</a> and mail it to newsletter@xyz.com</div><div><br></div><div><br></div><div>Regards,</div><div>" + signature + "<br></div>" ]
  72.         if(extraDetails.contains("mobile"))
  73.         {
  74.             sendsms
  75.             [
  76.                 to :extraDetails.get("mobile")
  77.                 message:"Consent Form has been sent to your mail id :- " + emailAddress
  78.             ];
  79.         }
  80.     return "Consent form sent successfully";
  81. }
Note

The entire request body will not be available inside the Function. It needs to be sent or received inside the arguments.

Configure an argument which contains the entire request body

In the function given above, you can see that we have 'extraDetails' as one of our Function argument. It is used to get name and signature from the user. This will be helpful when there is no way of knowing the number of arguments that will be passed to your Function.

Since there is no way of knowing the number of arguments present in it, you can have the function contain the entire request body within a single argument, i'e "extraDetails" in this case.

Note
  1. Value of 'listId' will be '2a9a3690fd'(in case of null).
  2. 'emailAddress' is mandatory.
  3. 'extraDetails' argument is provided to pass extra info, the one which contains the entire request body.
  4. 'listId', 'emailAddress' are of type STRING.
  5. 'extraDetails' is of type STRING and we are passing JSON in 'extraDetails'.

Part 2: Make the function available as an API

Once the function has been created, tested and saved, you can proceed to turn the function into an API.
  1. Go to Setup > Developer Space > Functions.
  2. Click the Settings icon for the corresponding function which needs to be made an API.
  3. Click REST API.



  4. Enable OAuth2 slider.
  5. Click Save.


Calling the function inside Widgets

Now comes the actual working part. Since the function has been turned into an API call, you can use the API code for the function in any widget, app or software and set it up to trigger based on your requirement.

Use the following HTML code (Consent Form of the Newsletter), to create a Widget. To learn how to create widgets, please click here.

HTML Code

  1. <h2>XYZ Newsletter</h2>
  2. <div class="container">
  3. <h2<Subscribe to our Newsletter</h2>
  4. </div>
  5. <div class="container" style="background-color:white">
  6. <input type="text" id="name" placeholder="Name" name="name" required>
  7. <input type="text" placeholder="Email address" name="mail" required id="email">
  8. <label>
  9. <input type="checkbox" checked="checked" name="subscribe">Daily Newsletter
  10. </label>
  11. </div>
  12. <div class="container">
  13. <input type="submit" value="Subscribe" id="subscribeButton">
  14. </div>
  15. <span id="res1">Click on the above button to Subscribe</span>

Script(Javascript):

  1. <script type="text/javascript">

  2. $("#subscribeButton").click(function() {
  3.     var extraDetails = {};
  4.     extraDetails.name = $("#name").val();
  5.     extraDetails.signature = "XYZ";
  6.     var arguments = {};
  7.     arguments.extraDetails = extraDetails;
  8.     arguments.emailAddress = $("#email").val();
  9.     var data = {
  10.          "arguments": JSON.stringify(arguments),
  11.     }

  12.     ZOHO.embeddedApp.init()
  13.         .then(function() {

  14.             ZOHO.CRM.FUNCTIONS.execute("subscribenewsletter", data)
  15.                 .then(function(resp) {
  16.                 $('#res1').text(JSON.stringify(resp));
  17.                 }).catch(function(resp) {
  18.                     $('#res1').text(JSON.stringify(resp));
  19.                 })
  20.          });
  21. });
Note

The above script only works for widgets placed inside the CRM.
To learn more about the Integration Tasks for Functions, click here.

The Outcome

Subscribing to the Newsletter



Getting the subscription mail



Once the Consent form is sent back to the mailer, the newsletter subscription will be enabled.

Disadvantages of not using Serverless functions

The user has to manually:
  1. Register the application on MailChimp and Google Drive.
  2. Code to handle OAuth2 flow.
  3. Call Mailchimp API's to verify the user availability.
  4. Call Google Drive API, to retrieve document URL.
  5. Code to send Email and SMS to Customer.
As you can see from the above steps, there are a lot of steps involved, which requires you to manually write codes for the widget as well as the functionality of the widget. However, this method is time consuming and requires a ton of manual effort. You can avoid them by having the function as a serverless one.


    • Related Articles

    • Serverless Functions - Using API Key

      Introduction A severless function within your CRM can be invoked from any third-party application or within the CRM using a webhook. However, generally most of the webhooks do not support OAuth2, save for a few of them. In that case, you can execute ...
    • Serverless Functions - Authentication

      Authentication Method A serverless function within your CRM can be invoked from any third-party application or within the CRM. However, commonly not all of the applications support a single authentication method. Keeping that in mind, we have two ...
    • Serverless Functions - An Overview

      Serverless architecture, also known as “Function-as-a-service”(Faas), provides a platform for developers to execute their own codes in response of various business events. In Zoho CRM, all these codes can be written through deluge scripts and can be ...
    • Functions

      Set Up Functions   You can set up functions in six places: Create a standalone function. Associate function to a workflow rule. Use functions later by including them in Schedules. Set the function to get executed upon the click of a Custom Button. ...
    • Serverless Functions - Types of Inputs

      The input for the function can be acquired in the following types Parameters Parameters are passed in URL of query string and the data passed in the post "form-data" section in an input. The "params" in the crmAPIRequest map contains these parameters ...