Navigation

Integrate ToDo with Twilio

The following tutorial builds upon the procedure in Getting Started and integrates the ToDo app with Twilio. With this integration, you can send messages to your Twilio number to add items to the ToDo list.

Prerequisites

For this app, you need the following:

  • The ToDo app set up according to ToDo (Web App).
  • A Twilio Account. If you do not have a Twilio account, create one before starting this procedure. You must also create a Twilio project for use with this procedure.

Procedure

A. Go to your ToDo app in MongoDB Stitch

Estimated Time to Complete: ~2 minutes

Log in to your Atlas account account and click Stitch Apps in the left-hand navigation. Click on the name of the MongoDB Stitch application you created for the ToDo (Web App) tutorial.

B. Configure the Stitch MongoDB Service for Twilio Integration

Estimated Time to Complete: ~10 minutes

You must specify a namespace for each collection the Stitch MongoDB service accessess. A namespace is a combination of the database name and the name of the collection. In Stitch, each namespace contains rules and filters that control access to documents during read and write operations. Stitch creates basic rules and filters for the namespace when you create it. See MongoDB Service Rules for more information.

1

Add the todo.users collection to the MongoDB service.

  1. Click on the MongoDB service mongodb-atlas.
  2. Click on the Rules tab.
  3. In the Rules tab, click New to add a new namespace. Enter the following information:
    • For Database, enter todo.
    • For Collection, enter users.
  4. Click Create.

Each document in the todo.users collection has the following form:

{
  "_id" : <string>, // Corresponds to the user logged into the app.
  "phone_number" : <string>,  // Twilio number in E.164 format.
  "number_status" : <string>, // Status of verification: pending,unverified, or verified
  "verify_code" : <string>    // Verification code.
}
2

Review Read Rules for Top-Level Documents in todo.users.

To view the read rule, click on the Top-Level Document in the Field Rules view.

By default, the collection has the following read rule for the top-level document:

{
  "owner_id" : "%%user.id"
}

With this rule, read and write operations can access all fields in a document if the document contains an owner_id field whose value equals the user ID (%%user.id) of the client issuing the read. If the owner_id field in the document does not equal the client user id, no field in the document is readable.

Modify the read rule at the top-level document to the following and click Save:

{ "_id": "%%user.id" }

The new rule specifies that the fields in a document are readable if the _id field in the document equals the id of the user logged in to the ToDo app.

For more information on MongoDB read rules, see MongoDB Service Read Rule.

3

Review Write Rules for Top-Level Documents in todo.users

To view the write rule, click on the Top-Level Document in the Field Rules view.

By default, the collection has the following write rule for the top-level document:

{
  "owner_id" : "%%user.id"
}

With this rule, the write operation must result in a document where the owner_id equals the user ID (%%user.id) of the client issuing the write. If the value of owner_id does not match the client user ID, MongoDB Stitch blocks the write.

Modify the write rule at the top-level document to the following:

{
  "%or": [
    { "%%prevRoot._id": "%%user.id" },
    { "%%prevRoot": { "%exists": 0 } }
  ]
}

The new rule specifies that the fields in a document are writable if before the write operation, either:

  • The document to be modified by the write operation contains an _id field that equals the id of the user logged in to the ToDo app (%%user.id)
  • The document to be modified by the write operation did not exist; i.e. the write operation results in an insert operation.

For more information on MongoDB read rules, see MongoDB Service Write Rule.

4

Review the Validation Rules for the owner_id field in todo.users.

To view a validation rule, click on the owner_id in the Field Rules view.

By default, the collection has the following validation rule specified on the owner_id field that determines whether a write operation is permissible:

{
  "%or": [
    { "%%prev": "%%user.id" },
    { "%%prev": { "%exists": false } }
  ]
}

With this rule, a write operation is valid if either:

  • The write operation modifies a document where the value of owner_id previous to the write operation (%%prev) equals the user ID (%%user.id) of the client issuing the write. An example of this kind of write operation is a client modifying a document that it previously inserted, or
  • The write operation modifies a document where there was no value for the owner_id field (%exists) previous to the write operation (%%prev). An example of this kind of write operation is an insert of a new document.

Delete the owner_id field by hovering over the owner_id field and clicking on the x that appears at the right.

5

Add the _id field and configure a validation rule for the field.

  1. Click +ADD.

  2. For Field Name, enter _id. Click Add.

  3. Click the _id field to view/modify its permissions.

  4. Enter the following rule into the Valid text entry and click Save.

    "%%user.id"
    

    This rule ensures that the only valid write operations are those that result in the _id field equal to the %%user.id.

6

Add the number_status field and configure a validation rule for the field.

  1. Click +ADD.

  2. For Field Name, enter number_status. Click Add.

  3. Click the number_status field to view/modify its permissions.

  4. Enter the following rule into the Valid text entry and click Save.

    { "%%this": { "%in": [ "pending", "unverified", "verified" ] } }
    

    This rule ensures that the only valid write operations are those that result in the number_status field equal to one of the specified strings.

7

Review All Other Fields Enabled option for todo.users.

By default, Allow All Other Fields flag is enabled so that any unlisted fields are readable/writeable as long as the document meets the read/write rules. Alternatively, you can explicitly define all the fields for this collection and disable Allow All Other Fields to control the shape of the documents.

8

Review Filters for todo.users.

Click on the Filters tab.

By default, the collection has the following filter rule:

When Match Expression
{ "%%true": true } { "owner_id": "%%user.id" }

This filter indicates that when %%true equals true (i.e. always), apply the following filter { "owner_id": "%%user.id" } to the read and write operations. This filter is in addition to the query predicates for read and write operations.

Click Delete to delete the default filter, then click Save.

For more information on filters, see MongoDB Service Filters.

C. Configure a MongoDB Stitch Named Pipeline for use with Twilio Integration

Estimated Time to Complete: ~5 minutes

1

Create a named pipeline.

Pipelines consist of stages that each defines an action to be performed. Each stage passes its output on as input for the next stage. A named pipeline is a pipeline saved within MongoDB Stitch that can be called by clients accessing the Stitch application.

Do the following to create the named pipeline:

  1. Click Pipelines.

  2. Click New Pipeline.

  3. Enter in the following properties for the pipeline.

    Name getIdFromPhone
    Private

    Make private.

    If private, the pipeline is inaccessible by a client and is only accessible in other MongoDB Stitch definitions, such as rules, webhooks and other pipelines.

    Skip Rules

    Enable Skip Rules.

    If enabled, rules do not apply to the service actions in the pipeline stages.

    Can Evaluate

    {}

    The condition that determines whether the pipeline can be run. An empty document always evaluates to true, indicating that the pipeline can always be run.

    Add Parameter

    Add the following parameter: paramTwilioPhone

    Mark the parameter as required when invoking this pipeline.

    When calling the pipeline, this parameter is required as an argument to the pipeline.

2

Configure the pipeline stage.

This pipeline consists of one stage that queries the todo.users collection by the phone_number field.

The pipeline has a single stage by default. Hover over this stage and click Edit to open the stage editor. Modify the stage as follows:

  1. For Service, select mongodb-atlas.

  2. For Action, select find.

  3. Copy the following code into the text entry box:

    {
       "collection": "users",
       "database": "todo",
       "query": { "phone_number": "%%vars.phoneNumberToFind" }
    }
    

    The document above describes a find operation on todo.users, where the query predicate returns any documents where phone_number is %%vars.phoneNumberToFind.

    %%vars contains the result of a let statement, which will be defined next.

  4. Toggle Bind data to %%vars to display the let statement panel.

    In the Create a named pipeline step, you configured the pipeline to require an argument paramTwilioPhone. This argument cannot be accessed directly by the stage. Instead, the let statement allows you to bind the argument (%%args)

    Copy the following code into the let statement:

    {
       "phoneNumberToFind": "%%args.paramTwilioPhone"
    }
    

    This let statement binds the argument (%%args) paramTwilioPhone passed to the pipeline to a variable, phoneNumberToFind. The pipeline stage can then access the variable (%%vars).

  5. Click Done in the stage editor.

  6. Click Save.

D. Configure the Stitch Twilio Service

Estimated Time to Complete: ~10 minutes

Note

This section assumes you have a Twilio account and that you have created a project to use with this procedure.

1

Add a Twilio service to your ToDo app.

  1. Click Add service.
  2. Click Twilio.
  3. For the Service Name, enter tw1.
  4. Click Add service.
2

Create the tw1 service.

  1. In the Config tab, enter your Twilio Account SID and Auth Token. You can find these values in the Twilio dashboard for the Twilio project you are using for the ToDo application.
  2. Click Save.
3

Create an incoming webhook to the tw1 service.

A MongoDB Stitch Incoming Webhook is a callback URL used by third-party service providers to execute a Stitch pipeline. For this webhook, the pipeline consists of two stages. The first stage creates a document that the second stage inserts into the todo.items collection.

To create an incoming webhook for the tw1 service, do the following:

  1. Click the Incoming Webhooks tab.

  2. Click New Webhook.

  3. Configure following properties for the webhook:

    Property Value
    Name twilioWebhook
    Respond With Result Toggle the switch to enable this property.
4

Configure the first pipeline stage for the twilioWebhook webhook.

The incoming webhook pipeline has a single stage by default. Hover over this stage and click Edit. Modify the stage as follows:

  1. For Action, select expr.

  2. Copy the following code into the text entry box:

    {
      "expression": {
        "text": "%%vars.text",
        "owner_id": "%%vars.ownerId._id"
      }
    }
    

    The expr action above outputs a document where text is %%vars.text and owner_id is %%vars.owner_id._id. %%vars contains the result of a let statement, which will be defined next.

  3. Toggle Bind data to %%vars to display the let statement panel.

    Copy the following code into the let statement:

    {
      "text": "%%args.Body",
      "ownerId": {
        "%pipeline": {
          "name": "getIdFromPhone",
          "args": { "paramTwilioPhone": "%%args.From" }
        }
      }
    }
    

    This document does the following:

    • Binds the Body argument (%%args) passed to the incoming webhook to the text variable. The Body argument corresponds to the Body paramter of the Twilio message .
    • Binds the result of the named pipeline getidFromPhone to the ownerId variable. The %pipeline expansion allows the pipeline stage to execute the named pipeline getIdFromPhone. The From argument corresponds to the From parameter of the Twilio message.
  4. Click Done.

5

Configure the second pipeline stage for the twilioWebhook webhook.

  1. Click Add Stage to add the second stage.

  2. Hover over the new stage and click Edit.

  3. For Service, select mongodb-atlas.

  4. For Action, select insert.

  5. Copy the following into the text entry box:

    {
      "collection": "items",
      "database": "todo"
    }
    

    This document performs an insert operation on the todo.items collection, using the document output from the previous stage.

  6. Click Done.

  7. Click Save.

Take note of the Webhook URL. You will need this when configuring the Twilio service.

6

Configure tw1 service rule.

Configure up a rule to enable the send action.

  1. Click the Rules tab.

  2. Click Add Rule.

  3. Set up the following rule which allows the service to send a message to any number.

    Actions When
    Enable Send. { }
  4. Click Save.

E. Create a Twilio Programmable SMS Service

Estimated Time to Complete: ~5 minutes

1

Log in to your Twilio account.

2

Open up the Programmable SMS dashboard.

From the Twilio dashboard:

  1. Click All Programs And Services in the left-hand navigation.
  2. Click Programmable SMS.
3

Configure Programmable SMS.

  1. Click Messaging Services.
  2. Click Create new Messaging Service. Enter a Friendly Name to describe the messaging service. For Use Case, select Mixed.
  3. Check the Process Inbound Messages checkbox. For Request URL, enter the Incoming Webhook URL you created when configuring the MongoDB Stitch Twilio service.
4

Configure Programmable SMS Phone Numbers.

  1. Click Numbers in the left-hand navigation bar for Programmable SMS.
  2. Select a Twilio number for the service. If you do not yet have a Twilio number, the Programmable SMS dashboard prompts you to Buy a Number.
  3. Click Add Selected.
5

Configure Verified Caller IDs for your Twilio number

  1. In the left-hand navigation, click All Products and Services, then click Phone Numbers.
  2. Click Verified Caller IDs.
  3. Click the plus-sign and add a phone number that you will use to send messages to the Twilio number.

For more information on the Twilio Programmable SMS service, including features and pricing, visit twilio.com/.

F. Add your Twilio Phone Number as a Stitch value

Estimated Time to Complete: ~2 minutes

Values are named constants that you can access in Stitch rules and pipelines. From the MongoDB Stitch UI, do the following:

1

Click Values in the left-hand navigation.

2

Enter ourNumber for the New Value Name.

3

Enter your Twilio number as the value.

Enter the Twilio number you selected while Creating a Twilio Programmable SMS Service as a E.164 formatted string. For example, +12223334444.

4

Click Save.

G. Set Up and Run the ToDo Application

Estimated Time to Complete: ~5 minutes

1

Review code to send a verification code using the Stitch Twilio service.

To access a Twilio service using the MongoDB service, use the StitchClient.executePipeline() function to execute a MongoDB Stitch pipeline.

For example, in the project, the index.js file has the following code:

stitchClient
  .executePipeline([
     { action: "literal", args: { items: [{ name: "hi" }] } },
       {
          service: "tw1",
          action: "send",
          args: {
            to: this._number.value,
            from: "%%values.ourNumber",
            body: "Your confirmation code is " + code
          }
       }
  ])

The %%values.ourNumber expansion retrieves the ourNumber value you configured in an earlier step.

This pipeline sends the confirmation code to the phone number the user inputs, setting the from field as the Twilio phone number.

2

Run the ToDo application.

If you are not running the ToDo application, start. Substitute your App ID in the following command and run from the todo directory:

APP_NAME=<App ID> npm start
3

Associate a phone number with your login id.

  1. Open a browser to http://localhost:8001/ to access the ToDo app. Sign in with Google or Facebook credentials, depending on which you have set up in the ToDo (Web App) tutorial.

  2. Click Settings.

  3. In the number box, enter a phone number from which you will send texts to your Twilio number.

    Important

    Do not enter the +<country> code; that is, enter just the 10 digits.

  4. Press the Return key.

  5. Upon successful messaging, a verify code box appears.

  6. Enter the verification code sent to the phone number you entered.

  7. Press the Return key.

Upon verification, messages sent from the phone number to your Twilio number associated with your messaging service will show up as items in your todo list.

4

Add todo items via Twilio.

  1. Click on the Lists link to return to the ToDo items list page.
  2. Send an SMS to your Twilio phone number.
  3. Refresh your browser to see your message.