SMS Chat

SMS chat can be easily being built with CallFire API, everything you need is to subscribe your endpoint to inbound SMS webhook then you are ready to send and receive text messages.

How to build a simple SMS chat with CallFire API

  1. Create CallFire account and API credentials, how to do that see on quick start guide page.
  2. Create a Webhook to listen for inbound SMS messages come to CallFire number: [[code-container]] [+curl] request:
    #!/usr/bin/env bash
    
    curl -u username:password -H "Content-Type:application/json" -X POST "https://api.callfire.com/v2/webhooks" -d '
        {
            "name":"inbound sms webhook",
            "resource":"InboundText",
            "events":["Finished"],
            "callback":"https://callback-service.com/listener"
        }'
    response:
    {
      "id": 4321
    }
    [-curl] [+java]
    import com.callfire.api.client.CallfireClient;
    import com.callfire.api.client.api.common.model.ResourceId;
    import com.callfire.api.client.api.webhooks.model.ResourceType;
    import com.callfire.api.client.api.webhooks.model.Webhook;
    
    class ApiClientSample {
        public static void main(String[] args) {
            CallfireClient client = new CallfireClient("api login", "api password");
            Webhook webhook = new Webhook();
            webhook.setName("inbound sms webhook");
            webhook.setResource(ResourceType.INBOUND_TEXT);
            webhook.getEvents().add(ResourceType.ResourceEvent.FINISHED);
            webhook.setCallback("https://callback-service.com/listener");
            ResourceId id = client.webhooksApi().create(webhook);
        }
    }
    [-java] [+csharp]
    using System.Collections.Generic;
    using CallfireApiClient;
    using CallfireApiClient.Api.Common.Model;
    using CallfireApiClient.Api.Webhooks.Model;
    
    public class ApiClientSample
    {
        public static void Main(string[] args)
        {
            var client = new CallfireClient("api_login", "api_password");
            var webhook = new Webhook
            {
                Name = "inbound sms webhook",
                Resource = ResourceType.INBOUND_TEXT,
                Events = new HashSet<ResourceEvent> {ResourceEvent.FINISHED},
                Callback = "https://callback-service.com/listener"
            };
            ResourceId resource = client.WebhooksApi.Create(webhook);
        }
    }
    [-csharp] [+js]
    'strict'
    
    const CallfireClient = require('callfire-api-client-js');
    const client = new CallfireClient('api-login', 'api-password');
    
    client.ready(() => {
        client.webhooks.createWebhook({
          body: {
            name: 'inbound sms webhook',
            resource: 'InboundText',
            events: ['Finished'],
            callback: 'https://callback-service.com/listener'
          }
        })
          .then((response) => {
            console.log(response.obj);
          })
          .catch((err) => {
            console.log('request error ' + err.data);
          });
      },
      (clientError) => {
        console.log('client error ' + clientError);
      }
    );
    [-js] [+python]
    from callfire.client import CallfireClient
    
    client = CallfireClient('api-login', 'api-password')
    response = client.webhooks.createWebhook(
        body={
            'name': 'inbound sms webhook',
            'resource': 'InboundText',
            'events': ['Finished'],
            'callback': 'https://callback-service.com/listener'
        }
    ).result()
    
    # see sample JSON response for this API
    # on 'curl' samples tab
    print(response)
    [-python] [+php]
    <?php
    
    class ApiClientSample {
    
        public static function main() {
            $client =\CallFire\Api\DocumentedClient::createClient ("login", "password");
            $request = $client -> createWebhook();
            $body = '{
                        "name":"inbound sms webhook",
                        "resource":"InboundText",
                        "events":["Finished"],
                        "callback":"https://callback-service.com/listener"
                     }';
            $request->getOperationConfig()->setBodyParameter($body);
            $result = $client->request($request);
            $json = json_decode($result->getBody());
        }
    }
    
    ApiClientSample::main();
    [-php] [[/code-container]] Once you receive an inbound text message CallFire will POST a JSON payload to your endpoint (e.g. https://callback-service.com/listener) Example of payload for incoming text message:
    {
    "timestamp":1469540830377,
    "webhookId":4321,
    "webhookName":"inbound sms webhook",
    "resourceType":"InboundText",
    "events":[
      {
         "timestamp":1469540830377,
         "webhookId":3749003,
         "resourceType":"InboundText",
         "eventType":"Finished",
         "resource":{
            "id":1023905054003,
            "fromNumber":"12132041238",
            "toNumber":"14246525473",
            "state":"FINISHED",
            "campaignId":9362663003,
            "contact":{
               "id":537189974003,
               "firstName":"John",
               "lastName":"Doe",
               "zipcode":"90025",
               "homePhone":"12132041238",
               "workPhone":"12132041238"
            },
            "inbound":true,
            "created":1469540830000,
            "modified":1469540828000,
            "labels":["Test"],
            "message":"Hi, this is an inbound text",
            "finalTextResult":"RECEIVED",
            "records":[
               {
                  "id":570794145003,
                  "billedAmount":1.0,
                  "finishTime":1469540830000,
                  "message":"Hi, this is an inbound text",
                  "textResult":"RECEIVED"
               }
            ],
            "media":[]
         }
      }
    ]
    }
    
    Please note that all timestamps are in unix milliseconds. See webhooks guide for more information about CallFire Webhooks.
  3. Now we can start conversation using Send Texts API. An example below shows how to send a simple text message to a phone number: [[code-container]] [+curl] request:
    #!/usr/bin/env bash
    
    curl -u username:password -H "Content-Type:application/json" -X POST -d '
        [
            {
                "phoneNumber":"12135551100",
                "message":"Hey there",
                "attributes":
                {
                    "external_user_id":"45450007002"
                },
            }
        ]' "https://api.callfire.com/v2/texts"
    response:
    {
      "items": [
        {
          "id": 13413,
          "fromNumber": "67076",
          "toNumber": "12135551100",
          "state": "READY",
          "campaignId": 20,
          "batchId": 14,
          "contact": {
            "id": 4096,
            "homePhone": "12135551100"
          },
          "attributes": {
            "external_user_id":"45450007002"
          },
          "inbound": false,
          "created": 1443403042000,
          "modified": 1443403042000,
          "message": "Hey there"
        }
      ]
    }
    [-curl] [+java]
    import java.util.Arrays;
    import java.util.List;
    
    import com.callfire.api.client.CallfireClient;
    import com.callfire.api.client.api.callstexts.model.Text;
    import com.callfire.api.client.api.campaigns.model.TextRecipient;
    
    class ApiClientSample {
        public static void main(String[] args) {
            CallfireClient client = new CallfireClient("api_login", "api_password");
    
            TextRecipient r1 = new TextRecipient();
            r1.setPhoneNumber("12135551100");
            r1.setMessage("Hey there");
            // Set custom attribute
            r1.getAttributes().put("external_user_id", "45450007002");
    
            List<TextRecipient> recipients = Arrays.asList(r1);
            List<Text> texts = client.textsApi().send(recipients);
        }
    }
    [-java] [+csharp]
    using System.Collections.Generic;
    using CallfireApiClient;
    using CallfireApiClient.Api.CallsTexts.Model;
    
    public class ApiClientSample
    {
        public static void Main(string[] args)
        {
            var client = new CallfireClient("api_login", "api_password");
            var recipient1 = new TextRecipient
            {
                Message = "Hey there",
                PhoneNumber = "12135551100",
                // set custom recipient attributes, they are available only to a single Call/Text
                //  action, do not confuse them with contact fields which are stored with contact
                //  and are available to each Call/Text where contact is attached to
                Attributes = new Dictionary<string, string>
                {
                    {"external_user_id", "45450007002"}
                }
            };
            IList<Text> texts = client.TextsApi.Send(new List<TextRecipient> {recipient1});
        }
    }
    [-csharp] [+js]
    'strict'
    
    const CallfireClient = require('callfire-api-client-js');
    const client = new CallfireClient('api-login', 'api-password');
    
    client.ready(() => {
        client.texts.sendTexts({
          body: [
            {
              phoneNumber: '12135551100',
              message: 'Hey there',
              attributes: {
                external_user_id: '45450007002'
              }
            }
          ]
        })
          .then((response) => {
            console.log(response.obj);
          })
          .catch((err) => {
            console.log('request error ' + err.data);
          });
      },
      (clientError) => {
        console.log('client error ' + clientError);
      }
    );
    [-js] [+python]
    from callfire.client import CallfireClient
    
    client = CallfireClient('api-login', 'api-password')
    response = client.texts.sendTexts(
        body=[
            {
                'phoneNumber': '12135551100',
                'message': 'Hey there',
                'attributes': {
                    'external_user_id': '45450007002'
                }
            }
        ]
    ).result()
    
    # see sample JSON response for this API
    # on 'curl' samples tab
    print(response)
    [-python] [+php]
    <?php
    
    class ApiClientSample {
    
        public static function main() {
            $client = \CallFire\Api\DocumentedClient::createClient("login", "password");
            $request = $client->sendTexts();
            $body = '[
                        {
                            "phoneNumber":"12135551100",
                            "message":"Hey there",
                            "attributes":
                            {
                                "external_user_id":"45450007002"
                            }
                        }
                     ]';
            $request->getOperationConfig()->setBodyParameter($body);
            $result = $client->request($request);
            $json = json_decode($result->getBody());
        }
    }
    
    ApiClientSample::main();
    [-php] [[/code-container]] CallFire allows you to attach custom attributes to a text record, attributes give you possibility to add some meta data to your outbound messages, they are optional.
  4. To select a list of received messages from particular conversation you should use Find Texts API, it provides filtering by from/to number, time range, inbound/outbound texts, and many more, see an example below how to fetch 50 messages (e.g. only text id, message text and timestamp) starting from 100' record, for particular fromNumber and a specific time range: [[code-container]] [+curl] request:
    #!/usr/bin/env bash
    
    curl -u "username:password" -H "Content-Type:application/json" -X GET "https://api.callfire.com/v2/texts?fromNumber=12135551100&intervalBegin=1473781817000&intervalEnd=1473781917000&offset=100&limit=50&fields=items(id,message,created)"
    response:
    {
      "items": [
        {
          "id": 13410,
          "created": 1443403042000,
          "message": "Hi support"
        },
        {
          "id": 13413,
          "created": 1443403043000,
          "message": "have an issue with API integration"
        },
    /* skipped */
        {
          "id": 13463,
          "created": 1443403044000,
          "message": "..."
        }
      ],
      "limit": 50,
      "offset": 100,
      "totalCount": 213
    }
    [-curl] [+java]
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    
    import com.callfire.api.client.CallfireClient;
    import com.callfire.api.client.api.callstexts.model.Text;
    import com.callfire.api.client.api.callstexts.model.request.FindTextsRequest;
    import com.callfire.api.client.api.common.model.Page;
    
    class ApiClientSample {
        public static void main(String[] args) {
            CallfireClient client = new CallfireClient("api_login", "api_password");
            FindTextsRequest request = FindTextsRequest.create()
                .fromNumber("12135551100")
                .intervalBegin(new GregorianCalendar(2016, Calendar.SEPTEMBER, 9, 15, 50, 17).getTime())
                .intervalEnd(new GregorianCalendar(2016, Calendar.DECEMBER, 10, 0, 0, 0).getTime())
                .offset(100L)
                .limit(50L)
                .fields("items(id,message,created)")
                .build();
            Page<Text> texts = client.textsApi().find(request);
        }
    }
    [-java] [+csharp]
    using System;
    using CallfireApiClient;
    using CallfireApiClient.Api.CallsTexts.Model;
    using CallfireApiClient.Api.CallsTexts.Model.Request;
    using CallfireApiClient.Api.Common.Model;
    
    public class ApiClientSample
    {
        public static void Main(string[] args)
        {
            var client = new CallfireClient("api_login", "api_password");
            var request = new FindTextsRequest
            {
                FromNumber = "12135551100",
                IntervalBegin = new DateTime(2016, 9, 13, 15, 50, 17),
                IntervalEnd = new DateTime(2016, 12, 1, 0, 0, 0),
                Offset = 100,
                Limit = 50,
                Fields = "items(id,message,created)"
            };
            Page<Text> texts = client.TextsApi.Find(request);
        }
    }
    [-csharp] [+js]
    'strict'
    
    const CallfireClient = require('callfire-api-client-js');
    const client = new CallfireClient('api-login', 'api-password');
    
    client.ready(() => {
        client.texts.findTexts({
          // filter by fromNumber
          fromNumber: '12135551100',
          // filter by time interval
          intervalBegin: 1473781817000,
          // filter by time interval
          intervalEnd: 1473781917000,
          // start from 100' item
          offset: 100,
          // return 50 items per request
          limit: 50,
          // return only specific fields
          fields: 'items(id,message,created)'
        })
          .then((response) => {
            console.log(response.obj);
          })
          .catch((err) => {
            console.log('request error ' + err.data);
          });
      },
      (clientError) => {
        console.log('client error ' + clientError);
      }
    );
    [-js] [+python]
    from callfire.client import CallfireClient
    
    client = CallfireClient('api-login', 'api-password')
    response = client.texts.findTexts(
        # filter by fromNumber
        fromNumber='12135551100',
        # filter by time interval
        intervalBegin=1473781817000,
        # filter by time interval
        intervalEnd=1473781917000,
        # start from 100' item
        offset=100,
        # return 50 items per request
        limit=50,
        # return only specific fields
        fields='items(id,message,created)'
    ).result()
    
    # see sample JSON response for this API
    # on 'curl' samples tab
    print(response)
    [-python] [+php]
    <?php
    
    class ApiClientSample {
    
        public static function main() {
            $client = \CallFire\Api\DocumentedClient::createClient("login", "password");
            $request = $client->findTexts();
            $request->getOperationConfig()->setQueryParameters(array("fromNumber" => "12135551100",
                                                                     "fields" => "items(id,message,created)",
                                                                     "intervalBegin" => 1473781817000,
                                                                     "intervalEnd" => 1473781917000,
                                                                     "limit" => 50,
                                                                     "offset" => 100));
            $result = $client->request($request);
            $json = json_decode($result->getBody());
        }
    }
    
    ApiClientSample::main();
    [-php] [[/code-container]] We used partial response to skip return fields that are not needed in order to reduce network traffic. See Partial response page for more information about fields parameter format.