Sending SMS messages
In this example you can learn how to send SMS messages and handle the delivery 
report through an installed API Extension. 
Please write the following code into the right file on your web server:
In this example you can learn how to send SMS messages and handle the delivery report through Ozeki Phone System and OPS SDK. First of all, please login and connect to the API Extension. After that, use the SendMessage method of the API Extension.
Next: Receive an incoming SMS message
[HttpPost]
public void SendSMS(string apiExtensionId, string sender, string recipient, 
string message, string deliveryReportURL)
{
	var serverUri = "http://ozekixepbx.ip:7780/";
	var queryString =
		"?Command=SendSms" +
		"&ApiExtension=" + apiExtensionId +
		"&Sender=" + sender +
		"&Recipient=" + recipient +
		"&Message=" + message +
		"&DeliveryReportURL=" + deliveryReportURL;
	byte[] data = new ASCIIEncoding().GetBytes(queryString);
	// Prepare web request...
	var request = (HttpWebRequest)WebRequest.Create(serverUri);
	request.Method = "POST";
	request.ContentType = "application/x-www-form-urlencoded";
	request.ContentLength = data.Length;
	Stream newStream = request.GetRequestStream();
	// Send the data.
	newStream.Write(data, 0, data.Length);
	newStream.Close();
}
class SendSmsController < ApplicationController
  require 'uri'
  require 'net/http'
  # In routes.rb you need to set the following routing rule
  # get '/send_sms' => 'send_sms#index'
  
  def index
    ops_ip_address_with_port = "ozekixepbx.ip:7780"
    api_extension = "9999"
    sender = "1000"
    recipient = "2000"
    message = "Hello world"
    delivery_report_url = "http://yoursite.com:3000/handle_delivery_report"
    query = "http://#{ops_ip_address_with_port}/?Command=SendSms&ApiExtension=
    #{api_extension}&Sender=#{sender}&Recipient=#{recipient}&Message=#{URI::encode(message)}
    &DeliveryReportURL=#{URI::encode(delivery_report_url)}"
    uri = URI query
    response = Net::HTTP.get uri 
    render :text => '<b>Response: </b>' + response
  end
end
<?php
	$url = "http://yoursite.com/HandleDeliveryReport.php"; 
    $server = "http://ozekixepbx.ip:7780";  
    $commandParams['Command'] = "SendSMS"; 
    $commandParams['ApiExtension'] = "9000";
    $commandParams['Sender'] = "777";
    $commandParams['Recipient'] = "882";
    $commandParams['Message'] = "This is a test SMS";
    $commandParams['DeliveryReportURL'] = $url;
    $command = http_build_query($commandParams);
    
    $params = array('http' => array('method' => "POST",
                                    'content' => $command));   
    $context = stream_context_create($params);     
       
    $fp = @fopen($server, 'r', false, $context);
    echo "Response: ";
    $response = @stream_get_contents($fp);    
 	echo $response;
?>
#!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
$address = "ozekixepbx.ip:7780"; #ip address of PBX, and the port of HttpAPI (default: 7780)
$apiExtensionId = "9000"; 
$Sender = "777";
$Message = "Test Message";
$Recipient = "+0123456789";
$DeliveryReportURL = "http://yoursite.com/HandleDeliveryReport.pl";
use LWP::UserAgent;
$ua = LWP::UserAgent->new;
# prepare and send the request
$req = HTTP::Request->new(GET => "http://$address/?Command=SendSms&ApiExtension=
$apiExtensionId&Sender=$Sender&Recipient=$Recipient&Message=
$Message&DeliveryReportURL=$DeliveryReportURL");
$res = $ua->request($req);
# check the outcome
if ($res->is_success) { print "\n". $res->decoded_content . "\n" }
else { print "\nError: " . $res->status_line . "\n" }
Imports OPSSDK
Imports OPSSDKCommon.Model.Message
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.MessageDelivered,
            Sub(sender, e)
                Console.WriteLine("Delivered SMS id:" &e.CallbackId &"(" &e.Result &")")
            End Sub
        Dim sms = New SMSMessage("+123456789", "This is a test SMS")
        apiExtension.SendMessage(sms)
    End Sub
End Module
import urllib.parse
import urllib.request
def application(environ, start_response):
    result = ""
    if(environ["PATH_INFO"] == ''):
        result = sendSms()
    elif(environ["PATH_INFO"] == '/HandleDeliveryReport'):
        result = handleDeliveryReport(environ)  
    response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(result)))]
    start_response('200 OK', response_headers)
    return [result]
def sendSms():    
    dict = {}
    dict["Sender"] = "+123456789"
    dict["Recipient"] = "882"
    dict["Message"] = "Hello, this is a test message!"
    dict["ApiExtension"] = "9000"
    dict["DeliveryReportURL"] = "http://yoursite.com/HandleDeliveryReport"
    
    opsLocation = "ozekixepbx.ip"
    opsPort = 7780
    result = ""
    requestUrl = "http://{}:{}/?Command=SendSms&{}".format(opsLocation, 
    opsPort, urllib.parse.urlencode(dict))
    
    result += requestUrl
    request = urllib.request.Request(requestUrl)
    response = urllib.request.urlopen(request)
    if(response.status != 200):
        result += "\r\nThe HTTP Status received indicates errors: 
        {}".format(response.status)
        
        return result
    result += "\r\nSMS successfully sent."
    return result
using OPSSDK;
using System;
using OPSSDKCommon.Model.Message;
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.MessageDelivered += (sender, e) =>
                Console.WriteLine("Delivered SMS id: {0} ({1})",e.CallbackId,e.Result);
            var sms = new SMSMessage("+123456789", "This is a test SMS");
            apiExtension.SendMessage(sms);
        }
    }
}
package pbxsampleapp;
import com.sun.net.httpserver.*;
import java.io.*;
import java.net.*;
public class SendingSmsMessage
{
    public static void main(String[] args)
    {
        try
        {
            RundHttpServerForDelivery();
            sendSms("5500", "+061554670", "Hello world!", "http://yoursite.com/deliveryreport");
        }
        catch (IOException ex) { System.out.println("Error" + ex.toString()); }
    }
    private static void sendSms(String extension, String recipient, 
    String messageContent, String deliveryreportUrl) throws IOException
    {
        String queryParams = "command=SendSms&ApiExtension=" + URLEncoder.encode(extension, "UTF-8")
                + "&Recipient=" + URLEncoder.encode(recipient, "UTF-8")
                + "&Message=" + URLEncoder.encode(messageContent, "UTF-8")
                + "&DeliveryReportUrl=" + URLEncoder.encode(deliveryreportUrl, "UTF-8");
        URL url = new URL("http://ozekixepbx.ip:7780/?" + queryParams);
        URLConnection conn = url.openConnection();
        InputStream input = conn.getInputStream();
        byte[] b = new byte[input.available()];
        input.read(b);
        System.out.println(new String(b));
    }
}
<!DOCTYPE html> <html> <head> </head> <body> <form action="http://ozekixepbx.ip:7780" method="POST"> <input type="hidden" name="Command" value="SendSms"> <input type="text" name="ApiExtension" value="9999"> <input type="text" name="Sender" value="123456789"> <input type="text" name="Recipient" value="882"> <input type="text" name="Message" value="Test Message"> <input type="hidden" name="DeliveryReportURL" value="http://yoursite.com/HandleDeliveryReport.php"> <input type="submit" value="Send SMS"> </form> </body> </html>
First of all, configure your Request parameters.
These are HTTP API commands. The HTTP API is an API available for the 
Ozeki Phone System that allows calls to be created, controlled and monitored, 
it also allows SMS messages to be sent. In this scenario the Commad must be 
„SendSMS” because we want to send a text message. (Check the command and the parameters
of SendSms.) The ApiExtension parameter 
specifies which api extension is added to the command. The Sender is a phone number, 
the recipient will see as the sender and the Recipient is the destination phone number. 
The Message parameter is the content of the message. The SMS delivery report is sent to 
the adjusted URL as a notification. The Sender and the DeliveryReportURL are optional paramteres.
You can reach the same features in your Ozeki Phone System at the HTTP API section. Click on the Productivity menu point on the top of the screen and select the HTTP API option. Important to mention this is only a test interface and with this you can simulate incoming requests to initiate calls or send messages. With HTTP API Tester you can try all of the HTTP API commands and features. If you select the SendSMS command you can see the parameter settings (Command, APIExtension, Sendter etc.) what we set in the code earlier. And you can send a HTTP request, only need to click on the 'Send request' button to make it happen.
  
If you would like to know more about the Ozeki Phone System HTTP API, click on this page.
Please change the ozekixepbx.ip text to that ip 
address where the Ozeki Phone System is installed. On the yoursite.com 
the address should be that where the sample applications are running.
After the configuration, make a HTTP Request with these values and 
send it to the API Extension. The API will send back a delivery report 
(if your SMS service provider supports it) to the given DeliveryReportURL. 
At the DeliveryReportURL it is possible to make another application that 
will handle the reports, for example log it into file.
[HttpPost]
public void HandleDeliveryReport(string notificationName, 
string delivered, string iD, string apiExtension)
{
	using (var fs = new FileStream("c:\\deliveryReports.txt", 
	FileMode.Append, FileAccess.Write, FileShare.Read))
	{
		using (var writer = new StreamWriter(fs))
		{
			writer.Write(
				"NotificationName=" + notificationName + ";" +
				"Delivered=" + delivered + ";" +
				"ID=" + iD + ";" +
				"ApiExtension=" + apiExtension + ";" +
				"ReceiveDate=" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n");
			writer.Flush();
			writer.Close();
		}
		fs.Close();
	}
}
class HandleDeliveryReportController < ApplicationController
  protect_from_forgery except: :index
  # In routes.rb you need to set the following routing rule
  # post '/handle_delivery_report' => 'handle_delivery_report#index'
  # http://yoursite.com:3000/handle_delivery_report
  def index
    
    receive_time = Time.now.utc.iso8601
    out_string = "NotificationName " + params['NotificationName']
    out_string += ",Delivered " + params['Delivered']
    out_string += ",ID " + params['ID']
    out_string += ",ApiExtension " + params['ApiExtension']
    out_string += ",ReceiveDate " + receive_time + "\r\n"
    begin
        file = File.new("delivery_reports.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
<?php
	$receiveTime = date("c");
	$outString = "NotificationName=" .$_REQUEST['NotificationName']. 
				 ",Delivered=" .$_REQUEST['Delivered']. 
				 ",ID=" .$_REQUEST['ID']. 
				 ",ApiExtension=" .$_REQUEST['ApiExtension']. 
				 ",ReceiveDate=$receiveTime\r\n";
	file_put_contents('deliveryReports.txt', $outString , FILE_APPEND);
?>
def handleDeliveryReport(environ):
    body = ""
    try:
        length= int(environ.get('CONTENT_LENGTH', '0'))
    except ValueError:
        length= 0
    try:
        if(length != 0):
            body = environ['wsgi.input'].read(length)
            receivedData = urllib.parse.parse_qs(body.decode("utf-8"))
            
            f = open('C:/deliveryReports.txt', 'a')
            for key, value in receivedData.items():
                f.write("{}: {}\r\n".format(str(key), str(value)))
            f.write("\r\n")
            f.close()
    except IOError:
        pass
#!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, '>>', 'deliveryReport.txt');
print $fh "NotificationName:$in{'NotificationName'}; 
Delivered:$in{'Delivered'}; ID:$in{'ID'}; ApiExtension:$in{'ApiExtension'}\n";
close $fh;
private static void RundHttpServerForDelivery()
{
    try
    {
        System.out.println("Starting http server for delivery report...");
        HttpServer server = HttpServer.create(new InetSocketAddress
        (InetAddress.getByAddress(new byte[] { 0, 0, 0, 0 }), 12345), 0);
        
        server.createContext("/deliveryreport", 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);
        System.out.println(new String(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();
    }
}
Get the OPSSDK.dll
First you need to add the OPSSDK.dll reference to your 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 Ozeki Phone System through this client.
Get the client to log into the running Ozeki Phone System 
by using the address of the server(ozekixepbx.ip) and a valid username and password.
If you are ready, try to get an existing API Extension, 
with the GetApiExtension method of the OpsClient.
Read more about installation of API Extension.
Further steps
When you are ready with the initial steps above, subscribe the 
MessageDelivered event of the the apiExtension. This event will trigger 
when the recipient has read the content of the message. 
In this example you can learn how to send SMS messages and handle 
the delivery report through Ozeki Phone System and OPS SDK.
In the event handler you will get the ID of your sent SMS and the Result of SMS sending.
The next step is sending the SMS itself. Please instantiate a new SMSMessage.
The Recipient will be the first parameter of the constructor, 
the content of the SMS will be the second. 
(Every time when you instantiate a new SMSMessage, an ID will be generated 
in the instance of the SMSMessage. So if you store this ID, 
you can compare it with the Delivered messages.)
After you finished the initialisation of the SMSMessage you can add it 
as the parameter of the apiExtension's SendSMS method, as you can see 
in Code Example 1.
Next: Receive an incoming SMS message
Recommended reading
More information
- How to Say Hello with Ozeki Phone System VoIP PBX
 - How to Greet Caller by Name with Ozeki Phone System VoIP PBX
 - Play MP3 for caller with Ozeki Phone System VoIP PBX
 - How to create an alarm system with Ozeki Phone System
 - How to make outbound calls with Ozeki Phone System VoIP PBX
 - How to send SMS messages with Ozeki Phone System VoIP PBX
 - How to build an Autodialer in Ozeki Phone System VoIP PBX
 - How to setup OzML Appointment Reminder in Ozeki Phone System VoIP PBX
 - How to make Interactive Voice Response (IVR) in Ozeki using an OzML script
 - How to display a HTML popup window with JavaScript API
 
	    	     






