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.

freeclimb >= 4.8.0
Flask>=2.3.2
python-dotenv

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

import freeclimb
from freeclimb.api import default_api
from flask import Flask, request, jsonify
import os
from dotenv import load_dotenv

load_dotenv()
account_id = os.environ.get("ACCOUNT_ID")
api_key = os.environ.get("API_KEY")
api_server = os.environ.get("API_SERVER", "https://www.freeclimb.com/apiserver")
from_number = os.environ.get("FREECLIMB_NUMBER")

if not account_id or not api_key or not from_number:
    print("ERROR: ENVIRONMENT VARIABLES ARE NOT SET. PLEASE SET ALL ENVIRONMMENT VARIABLES AND RETRY.")
    quit()

app = Flask(__name__)

configuration = freeclimb.Configuration(
    host=api_server,
    username=account_id,
    password=api_key
)

api_client = freeclimb.ApiClient(configuration)
api_instance = default_api.DefaultApi(api_client)

# Specify this route with 'SMS URL' in App Config
@app.route('/incomingSms', methods=['POST'])
def incomingSms():
    if request.method == 'POST':
        message = "Hello, World!"
        _from = from_number #Your FreeClimb Number
        to = request.json['from']
        message_request = freeclimb.MessageRequest(_from=_from, text=message, to=to)
        api_instance.send_an_sms_message(message_request)
        return jsonify({'success':True}), 200, {'ContentType':'application/json'} 

# Specify this route with 'STATUS CALLBACK URL' in App Config
@app.route('/status', methods=['POST'])
def status():
    return jsonify({'success':True}), 200, {'ContentType':'application/json'} 
  
if __name__ == '__main__':
    quickstart_tutorial()
    app.run(host='0.0.0.0', port=3000)

Run the example:

python3 main.py