Receive a Message

👍

You're ready for this how-to guide if you've got the following:

A FreeClimb account
A registered application
A configured FreeClimb number
Your tools and language installed
Trial accounts: A verified number


Node.js

An incoming message is initiated by FreeClimb POSTing to the resource specified in the SMS URL set in the App Config in the FreeClimb dashboard. You can respond to the message by sending a create message request to FreeClimb. The phone number of the texter can be found in the request body. To send an outbound SMS message, the To variable is the phone number receiving the message and the From variable must be an incoming phone number you've purchased from FreeClimb.

Create your package.json file and save in the root directory of your project:

{
  "name": "node-receive-a-message-tutorial",
  "version": "1.0.0",
  "license":"MIT",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "@freeclimb/sdk": "^3.4.0",
    "body-parser": "^1.20.2",
    "dotenv": "^16.3.1",
    "express": "^4.18.2"
  }
}

Implement the sms url endpoint that FreeClimb can request with the following code:

require('dotenv').config()
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json())
const freeclimbSDK = require('@freeclimb/sdk')

const port = process.env.PORT || 3000
const accountId = process.env.ACCOUNT_ID
const apiKey = process.env.API_KEY
const fromNumber = process.env.FREECLIMB_NUMBER
const baseServer = new freeclimbSDK.ServerConfiguration(process.env.API_SERVER || "https://www.freeclimb.com/apiserver")
const freeclimbConfig = freeclimbSDK.createConfiguration({ baseServer, accountId, apiKey })
const apiInstance = new freeclimbSDK.DefaultApi(freeclimbConfig);

app.post('/incomingSms', (req, res) => {
  const { from: userPhoneNumber } = req.body
  const messageRequest = {
    _from: fromNumber, // Your FreeClimb Number 
    to: userPhoneNumber,
    text: 'Hello, World!'
  }
  apiInstance.sendAnSmsMessage(messageRequest)
    .then(() => {
      res.sendStatus(200);
    })
    .catch(err => {
      console.log(err)
      res.sendStatus(500)
    })
})

// Specify this route with 'Status Callback URL' in App Config
app.post('/status', (req, res) => {
  // handle status changes
  res.status(200)
})

app.listen(port, () => {
  console.log(`\nListening on port: ${port}`);
});

Start the Node server:

node index.js

Java

An incoming message is initiated by FreeClimb POSTing to the ReceiveMessage controller. FreeClimb uses the SMS URL set in the App Config in the dashboard. You can respond to the message by sending a create message request to FreeClimb. To send an outbound SMS message, the To variable is the phone number receiving the message and the From variable must be an incoming phone number you've purchased from FreeClimb.

Create your build.gradle file and save it to the root directory in your project:

/*
 * This file was generated by the Gradle 'init' task.
 *
 * This is a general purpose Gradle build.
 * Learn how to create Gradle builds at https://guides.gradle.org/creating-new-gradle-builds
 */
 
buildscript {
    repositories {
        mavenCentral()
        maven { url 'https://jitpack.io' }
    }
  //Add the dependency
    dependencies {
        classpath "org.springframework.boot:spring-boot-gradle-plugin:2.1.6.RELEASE"
    }
}
 
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
 
bootJar {
    baseName = 'gs-spring-boot'
    version =  '0.1.0'
}
 
repositories {
    mavenCentral()
    maven { url 'https://jitpack.io' }
}
 
sourceCompatibility = 1.8
targetCompatibility = 1.8
 
dependencies {
    compile "org.springframework.boot:spring-boot-starter-web"
    testCompile "junit:junit"
    compile 'com.github.FreeClimbAPI:java-sdk:3.0.0'
}
 
sourceSets {
    main {
        java {
            srcDirs = ['src'] // changed line
        }
    }
}

Implement the ReceiveMessage controller:

package main.java.receive_a_message;
 
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.vailsys.freeclimb.api.FreeClimbClient;
import com.vailsys.freeclimb.api.FreeClimbException;
 
@RestController
public class ReceiveMessageController {
  private final String fromNumber = System.getenv("FREECLIMB_PHONE_NUMBER");
  private final String toNumber = System.getenv("TO_PHONE_NUMBER");
  private final String accountId = System.getenv("ACCOUNT_ID");
  private final String apiKey = System.getenv("API_KEY");
 
  @RequestMapping(value = { "/InboundSms" }, method = RequestMethod.POST)
  public void inboundSms(@RequestBody String body) {
    FreeClimbClient client;
    try {
      client = new FreeClimbClient(accountId, authToken);
      client.messages.create(fromNumber, toNumber, "Hello from the FreeClimb API!");
    } catch (FreeClimbException e) {
      // Handle Error
    }
  }
 
}

Build and run the example:

> gradle build && java -Dserver.port=3000 -jar build/libs/gs-spring-boot-0.1.0.jar

C#

An incoming message is initiated by FreeClimb POSTing to the SMS URL set in the App Config in the FreeClimb dashboard. In response to a POST request from FreeClimb, you can create an outbound SMS message to send back. To send an outbound SMS message, the To variable is the phone number receiving the message and the From variable must be an incoming phone number you've purchased from FreeClimb.

Install the SDK with the following command:

dotnet add package freeclimb-cs-sdk --version 2.0.0

Example code for Controller:

using com.freeclimb;
using com.freeclimb.percl;
using com.freeclimb.webhooks.call;
using System;
using Microsoft.AspNetCore.Mvc;
using com.freeclimb;
using com.freeclimb.api;
 
namespace ReceiveMessage.Controllers {
  [Route ("inboundSms")]
  [ApiController]
  public class FreeClimbController : ControllerBase {
 
    [HttpPost]
    public ActionResult smsConnect (CallStatusCallback freeClimbRequest) {
        string acctId = getAcctId ();
        string apiKey = getApiKey ();
        FreeClimbClient client = new FreeClimbClient (acctId, apiKey);
        string to = freeClimbRequest.getFrom;
        string from = "";
        client.getMessagesRequester.create(from, to, "Hello from the C# SDK!");
        
        return Ok();
    }
 
    private string getAcctId () {
        return System.Environment.GetEnvironmentVariable("ACCOUNT_ID");
    }
 
    private string getApiKey () {
        return System.Environment.GetEnvironmentVariable("API_KEY");
    }
  }
}

Python

An incoming message is initiated by FreeClimb POSTing to the URL specified in SMS URL of the associated FreeClimb application. You can respond to the message by sending a create message request to FreeClimb. To send an outbound SMS message, the to argument is the phone number receiving the message and the from argument must be an incoming phone number you've purchased from FreeClimb.

Save the following requirements.txt file in your project folder.

urllib3 >= 1.15.1
certifi >= 14.05.14
six >= 1.10
python-dateutil >= 2.5.3
freeclimb >= 4.0.0
Flask==1.1.1

Implement the /sms and /status endpoints with the following code:

from __future__ import print_function
import time
import freeclimb
from freeclimb.api import default_api
import os
import json
from flask import Flask, request

configuration = freeclimb.Configuration(
    # Defining host is optional and default to https://www.freeclimb.com/apiserver
    host     = "https://www.freeclimb.com/apiserver",
    # Configure HTTP basic authorization: fc
    username = os.environ['ACCOUNT_ID'],
    password = os.environ['API_KEY']
)

# Create an instance of the API class
api_instance = default_api.DefaultApi(freeclimb.ApiClient(configuration))

app = Flask(__name__)

# Specify this route with 'SMS URL' in App Config
@app.route('/incomingSms', methods=['POST'])
def incomingSms():
    if request.method == 'POST':
        message = "Hello! You texted FreeClimb's Python SDK the following: " + request.json['text']
        message_request = freeclimb.MessageRequest(_from=request.json['from'], to=request.json['to'], text=message)
        api_instance.send_an_sms_message(message_request=message_request)

        return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 


# Specify this route with 'STATUS CALLBACK URL' in App Config
@app.route('/status', methods=['POST'])
def status():
    return json.dumps({'success':True}), 200, {'ContentType':'application/json'}

Run the example:

> env FLASK_APP=python_receive_a_message_tutorial.py flask run