Receive an incoming SMS message



Let us discover how to receive incoming SMS messages. When your configured API Extension gets an SMS, that will be forwarded to the Incoming message URL that has been given previously during the configuration. So first of all, please install an API Extension and specify an Incoming message URL .


Learn how to receive incoming SMS messages using the following example. First of all, please login and connect to the API Extension. Wait for an Incoming SMS, and when it is occured you can log it into a simple text file.


Example code coming soon...
<?php
	$receiveTime = date("c");
	$outString = "Date: " . $receiveTime . "\r\n";
	$outString .= "Sender: " . $_REQUEST['Sender'] . "\r\n";
	$outString .= "Message: " . $_REQUEST['Message'] . "\r\n\r\n";
	file_put_contents('sms.txt', $outString, FILE_APPEND);	
?>
using OPSSDK;
using System;

namespace OPS_QuickStartExample_CSharp
{
	class Program
	{		
		static void Main(string[] args)
		{
			var client = new OpsClient();
            client.ErrorOccurred += (sender, info) => 
                Console.WriteLine(info.Message);

            if (!client.Login("ozekixepbx.ip", "admin", "12345"))
                return;
                
            var apiExtension = client.GetAPIExtension("9000");
			apiExtension.MessageReceived += (sender, e) =>
                Console.WriteLine("Sender: " + e.Sender + ". Content:" + e.Content);

			Console.ReadLine();
		}
	}
}
[HttpPost]
public void ReceiveSMS(string notificationName, string sender, string recipient, string iD, string apiExtension, string message)
{
	using (var fs = new FileStream("c:\\sms.txt", FileMode.Append, FileAccess.Write, FileShare.Read))
	{
		using (var writer = new StreamWriter(fs))
		{
			writer.Write(
				"NotificationName=" + notificationName + ";" +
				"Sender=" + sender + ";" +
				"Recipient=" + recipient + ";" +
				"ID=" + iD + ";" +
				"ApiExtension=" + apiExtension + ";" +
				"Message=" + message + "\n");

			writer.Flush();
			writer.Close();
		}
		fs.Close();
	}
}
class ReceiveSmsController < ApplicationController
  
  require 'time'
  protect_from_forgery except: :index

  # In routes.rb you need to set the following routing rule
  # post '/receive_sms' => 'receive_sms#index'
  
  def index
    
    receive_time = Time.now.utc.iso8601
    out_string = "Date: " + receive_time + "\r\n"
    out_string += "Sender: " + params['Sender'] + "\r\n"
    out_string += "Message: " + params['Message'] + "\r\n\r\n"

    begin
        file = File.new("sms.txt", "a")
        file.write(out_string)
      rescue IOError => e
        #Some error occurred, directory not writeable etc.
      ensure
        file.close unless file == nil
    end

  end
end
Imports OPSSDK

Module Module1
    Public Sub Main(args As String())
        Dim client = New OpsClient()
        AddHandler client.ErrorOccurred, Sub(sender, info)
                                             Console.WriteLine(info.Message)
                                         End Sub

        If Not client.Login("ozekixepbx.ip", "admin", "12345") Then
            Return
        End If

        Dim apiExtension = client.GetAPIExtension("9000")
        AddHandler apiExtension.MessageReceived,
            Sub(sender, e)
                Console.WriteLine("Sender: " & e.Sender & ". Content:" & e.Content)
            End Sub

        Console.ReadLine()
    End Sub
End Module
import urllib.parse

def application(environ, start_response):

    try:
        length= int(environ.get('CONTENT_LENGTH', '0'))
    except ValueError:
        length= 0

    body = ""
    if(length != 0):
        body = environ['wsgi.input'].read(length)
        receivedData = urllib.parse.parse_qs(body.decode("utf-8"))

        f = open('C:/sms.txt', 'a')
        for key, value in receivedData.items():
            f.write("{}: {}\r\n".format(str(key), str(value)))
        f.write("\r\n")
        f.close()

    start_response('200 OK', [('Content-Type', 'text/html')])
    return ""
#!c:/Perl64/bin/perl.exe   
print "Content-Type: text/plain\n\n";
#You have to add the directory route of perl.exe, and print the content type

use CGI qw(:cgi-lib :standard);  # Use CGI modules that let read data passed
&ReadParse(%in); #Read in from HTTPPost parameters

#Logging into file
open(my $fh, '>>', 'incomingMessages.txt');
print $fh "NotificationName:$in{'NotificationName'}; Sender:$in{'Sender'}; Recipient:$in{'Recipient'}; ID:$in{'ID'}; ApiExtension:$in{'ApiExtension'}; Message:$in{'Message'}\n";
close $fh;
package pbxsampleapp;

import com.sun.net.httpserver.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class ReceiveMessageSample
{
    public static void main(String[] args)
    {
        try
        {
            System.out.println("Starting http server...");
            HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getByAddress(new byte[] { 0, 0, 0, 0 }), 12345), 0);
            server.createContext("/incomingsms", new PbxSampleApp.PBXRequestHandler());
            server.start();
            System.out.println("http server running on " + server.getAddress().toString());
        }
        catch (IOException ex) { System.out.println("Error" + ex.toString());}     
    }

    static class PBXRequestHandler implements HttpHandler
    {

        @Override
        public void handle(HttpExchange httpExchange) throws IOException
        {
            InputStream inputStream = httpExchange.getRequestBody();
            byte[] body = new byte[inputStream.available()];
            inputStream.read(body);
            parseBody(body);
            httpExchange.getResponseHeaders().add("Content-type", "text/html");
            String response = "";
            httpExchange.sendResponseHeaders(200, response.length());
            OutputStream os = httpExchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }

        private Map<String, String> parseBody(byte[] params) throws UnsupportedEncodingException
        {
            Map<String, String> body_pairs = new LinkedHashMap<String, String>();
            String[] pairs = URLDecoder.decode(new String(params), "UTF-8").split("&");
            String paramname;
            String value;
            for (String pair : pairs)
            {
                int idx = pair.indexOf("=");
                paramname = pair.substring(0, idx);
                value = pair.substring(idx + 1);
                body_pairs.put(paramname, value);
                System.out.println(String.format("%s: %s", paramname, value));
            }
            return body_pairs;
        }
    }
}
Code example 1 - Handle the IncomingSMS notification and log the SMS (parameters) into file

This application will write all parameters into a file every time, when it gets a request from the API Extension. Read more about the parameters of the notification.
IN MORE DETAILS

Get the OPSSDK.dll

First you need to add the OPSSDK.dll reference to the project
(You can find OPSSDK.dll at C:\Program Files\Ozeki\Ozeki Phone System\Examples\.NET API\OPSSDK.dll).

Login and connect

Create a new instance of OpsClient, and subscribe to the ErrorOccurred event. Your program will communicate with the Ozeki Phone System through this client. Try to login with the client into the running Ozeki Phone System, with the address of the server(ozekixepbx.ip) and a valid username, password combination.

If you are ready, try to get an existing API Extension, with the GetApiExtension method of the OpsClient. Get more information on how to install an API Extension in Ozeki Phone System.

Further steps

When you are ready with the initial steps above, subscribe the MessageReceived event of the apiExtension. This event will be triggered every time, when the selected API Extension gets an SMS. This event will provide you the received SMS itself. In the event handler you can use the SMS message as you wish (write the SMS into file, Database etc.).

More information