HTTP SMS приложение за разработчици за комуникация с централния сървър

Този документ предоставя справка за всички функции, достъпни за Вас чрез HTTP интерфейса за изпращане на текстови съобщения.
HTTP API-то Ви позволява да интегрирате Вашето приложение с easysms (портал) чрез използване на HTTP протокола за изпращане на съобщения. HTTPS се поддържа специфично за всички транзакции, използващи SSL криптиране.

Обща информация

Клиентът изпраща HTTP GET заявка към easysms HTTP интерфейса, предоставяйки списък с необходими параметри. easysms връща обратно HTTP отговор, който показва успеваемостта на транзакцията

Обърнете внимание, че разделителя '|', използван в много случаи по-долу във върнатата информация, е символа за вертикална черта (ASCII 124). Моля, не забравяйте да шифровате за URL всички подадени параметри.

омандите, достъпни в тази версия на API-то на easysms следват по-долу.

Изпращане на SMS

URL: https://www.net2sms.gr/srvauth/index?cmd=easysms&action=send_sms

Приемани параметри

Параметър Описание Наличност
text Съобщение за изпращане. Трябва да е шифровано за URL. Задължително
mobile_number MSIDSN на получателя, на когото съобщението ще бъде изпратено. Например: 49175123456 Задължителен
originator ID на подателя (ако е буквено-числов - максимум 11 символа, ако е числов - максимум 16 символа) Незадължителен
flash Задайте като вярно, за да изпратите Флаш съобщение Незадължителен
request_delivery Задайте като вярно, за да получите отчет за доставка Незадължителен

Връща

код на върнатото | sms_id | баланс
Описание
Код на върнатото 1 за изпратено съобщение, в противен случай изпращането неуспешно
ID на текстовото съобщение ID-то на съобщението, отчетите за доставка са дадени според ID-тата на съобщенията
баланс баланса на акаунта

Примерна заявка за изпращане на текстово съобщение

За да напишете 'Hello, World!' на '49175123456', показано като изпратено от 'МоятаКомпания', трябва да използвате:

https://www.net2sms.gr/srvauth/index?cmd=easysms&action=send_sms&text=Hello%20World&mobile_number=49175123456&originator=MyCompany

Порталът ще върне нещо от сорта на:

1|456123789|112

Което се превежда като текстово съобщение е успешно зададено с ID 456123789 и Вашият баланс е 112


Примери на кодове за изпращане на текстово съобщение

<?php
    // Simple SMS send function
    function sendSMS($username, $password, $to, $message, $originator) {
        $URL = "https://" . $username . ":" . $password . "@www.net2sms.gr/srvauth/index?cmd=easysms&action=send_sms&mobile_number=$to";
        $URL .= "&text=" . urlencode( $message ) . '&originator=' . urlencode( $originator );
        $fp = fopen( $URL, 'r' );
        return fread( $fp, 1024 );
    }
    // Example of use 
    $response = sendSMS( 'myUsername', 'myPassword', '4917512345', 'My test message', 'TextMessage' );
    echo $response;
?>
<?php
    // Simple SMS send function
    function sendSMS($username, $password, $to, $message, $originator) {
	$URL = "https://www.net2sms.gr/srvauth/index?cmd=easysms&action=send_sms&mobile_number=$to";
	$URL .= "&text=".urlencode($message).'&originator='.urlencode($originator);
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $URL);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	$output = curl_exec($ch);
	$info = curl_getinfo($ch);
	curl_close($ch);
	return $output;
    }
    // Example of use 
    $response = sendSMS('myUsername', 'myPassword', '4917512345', 'My test message', 'TextMessage');
    echo $response ;
?>
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
// Uses Apache Common URL utils, download from apache.org and put it in CLASSPATH
import org.apache.commons.codec.binary.Base64;

// Simple send SMS programm
public class SendSMS {
    public static String sendSMS( String username, String password, String to, String message, String originator ) {
		
        String webPage;
        // StringBuilder inBuffer = new StringBuilder();
        try {
            webPage = "https://www.net2sms.gr/srvauth/index?cmd=easysms&action=send_sms" +
                "&mobile_number=" + to + "&text=" + URLEncoder.encode( message, "UTF-8" ) +
                "&originator=" + URLEncoder.encode( originator, "UTF-8" );
        } catch ( UnsupportedEncodingException e ) {
            return "UnsupportedEncodingException";
        }

		String authString = username + ":" + password;
		System.out.println("auth string: " + authString);
		byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
		String authStringEnc = new String(authEncBytes);
		System.out.println("Base64 encoded auth string: " + authStringEnc);

		try{
			URL url = new URL(webPage);
			URLConnection urlConnection = url.openConnection();

			urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
			InputStream is = urlConnection.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);

			int numCharsRead;
			char[] charArray = new char[1024];
			StringBuffer sb = new StringBuffer();

			while ((numCharsRead = isr.read(charArray)) > 0) {
				sb.append(charArray, 0, numCharsRead);
			}
			String result = sb.toString();
			return result;		

		} catch ( Exception e ){
			return "MalformedURLException";
		}
    }


    public static void main( String[] args ){
        // Example of use 
        String response = sendSMS( "myUsername", "myPassword", "4917512345", "My test message", "TextMessage" );
        System.out.println( response );
    }
}
<%
    username = "myUsername"
    password = "myPassword"
    mobile = "4917512345"

    message = Server.URLEncode("My test message")
    originator  = Server.URLEncode("TextMessage")

    url = "https://www.net2sms.gr/srvauth/index?cmd=easysms&action=send_sms" + 
			"&mobile_number=" + mobile + "&text=" + message + "&originator=" + originator

    set objSrvHTTP = Server.CreateObject("Msxml2.ServerXMLHTTP")
    objSrvHTTP.open "GET", url, False, username, password
    objSrvHTTP.send()
    Resp = objSrvHTTP.responseText

    Response.Write( Resp )
%>
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace SendSMS {
    class Program {
        public static string SendSMS( string username, string password, string to, string message, string originator ) {
            StringBuilder sb  = new StringBuilder();
            byte[] buf = new byte[ 1024 ];
            string url = "https://www.net2sms.gr/srvauth/index?cmd=easysms&action=send_sms" +
                "&mobile_number=" + to + "&text=" + HttpUtility.UrlEncode( message ) +
                "&originator=" + HttpUtility.UrlEncode( originator );
            HttpWebRequest request = ( HttpWebRequest ) WebRequest.Create( url );
            request.Credentials = new NetworkCredential(username, password);
            HttpWebResponse response = ( HttpWebResponse ) request.GetResponse();
            Stream resStream = response.GetResponseStream();
            string tempString = null;
            int count = 0;
            do {
                count = resStream.Read( buf, 0, buf.Length );
                if ( count != 0 ) {
                    tempString = Encoding.ASCII.GetString( buf, 0, count );
                    sb.Append( tempString );
                }
            }
            while ( count > 0 );
            return sb.ToString();
        }
        static void Main( string[] args ) {
            string respXML = SendSMS( "myUsername", "myPassword", "4917512345", "My test message", "TextMessage" );
            Console.WriteLine( respXML );
       }
    }
}
/* * Send SMS C/C++ example need curllib download from http://curl.haxx.se/ */

#include <stdio.h>
#include <tchar.h>
#include <string.h>
#include <curl/curl.h>
#define URLSIZE 512

struct MemoryStruct {
        char *memory;
        size_t size;
};

/* Converts a hex character to its integer value */

char from_hex(char ch) {
        return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
}

/* Converts an integer value to its hex character*/

char to_hex(char code) {
        static char hex[] = "0123456789abcdef";
        return hex[code & 15];
}

/* Returns a url-encoded version of str */

char *url_encode(char *str) {
        char *pstr = str, *buf = (char *)malloc(strlen(str) * 3 + 1), *pbuf = buf;
        while (*pstr) {
                if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
                        *pbuf++ = *pstr;
                else if (*pstr == ' ')
                        *pbuf++ = '+';
                else
                        *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
                pstr++;
        }
        *pbuf = '\0';
        return buf;
}

/* CURL Callback write function */

static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
        size_t realsize = size * nmemb;
        struct MemoryStruct *mem = (struct MemoryStruct *)userp;
        mem->memory = (char *)realloc(mem->memory, mem->size + realsize + 1);
        if (mem->memory == NULL) {
                /* out of memory! */
                printf("not enough memory (realloc returned NULL)\n");
                exit(EXIT_FAILURE);
        }
        memcpy(&(mem->memory[mem->size]), contents, realsize);
        mem->size += realsize;
        mem->memory[mem->size] = 0;
        return realsize;
}

/* Send SMS */

char * sendSMS(const char *username, const char *password, const char *to, char *message, char *originator) {
        static char url[URLSIZE] = "https://";
		static char urlRest[URLSIZE] = "@www.net2sms.gr/srvauth/index?cmd=easysms&action=send_sms";
        char *encoded;
        CURL *curl;
        CURLcode res;
        struct MemoryStruct chunk;
        chunk.memory = (char *)malloc(1);  /* will be grown as needed by the realloc above */
        chunk.size = 0;    /* no data at this point */
        curl = curl_easy_init();
        if(curl) {
                strcat_s(url, URLSIZE, username);
                strcat_s(url, URLSIZE, ":");
                strcat_s(url, URLSIZE, password);
                strcat_s(url, URLSIZE, urlRest);;
                strcat_s(url, URLSIZE, "&mobile_number=");
                strcat_s(url, URLSIZE, to);
                strcat_s(url, URLSIZE, "&text=");
                encoded = url_encode(message);
                strcat_s(url, URLSIZE, encoded);
                free(encoded);
                encoded = url_encode(originator);
                strcat_s(url, URLSIZE, "&originator=");
                strcat_s(url, URLSIZE, encoded);
                free(encoded);
                curl_easy_setopt(curl, CURLOPT_URL, url);
                /* send all data to this function  */
                curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
                /* we pass our 'chunk' struct to the callback function */
                curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
                if((res = curl_easy_perform(curl)) != CURLE_OK) {
                        return NULL;
                }
                curl_easy_cleanup(curl);
        }
        return chunk.memory;
}

int main(void) {
        char *response;
        response = sendSMS("myUsername", "myPassword", "4917512345", "Hello World", "TextMessage");
        if(response != NULL) {
                printf(response);
                free(response);
        }
        getchar();
        return 0;
}
#include <iostream>
#include <string>
#using <System.Dll>
#using <System.Web.Dll>

using namespace std;
using namespace System;
using namespace System::Web;
using namespace System::Net;
using namespace System::IO;
using namespace System::Runtime::InteropServices;

ref class SMSSender
{

private:
        static String^ Username = "myUsername";
        static String^ Password = "myPassword";

public:
        SMSSender()
        {}
        String^ SendSMS(String^ To, String^ Message, String^ From)
        {
                Message = HttpUtility::UrlEncode(Message);
                From = HttpUtility::UrlEncode(From);
                String^ URL = "https://" + Username + ":" + Password + "@www.net2sms.gr/srvauth/index?cmd=easysms&action=send_sms&text=" + Message + "&originator=" + From + "&mobile_number=" + To;
                WebRequest^ Handle = WebRequest::Create(URL);
                WebResponse^ HTTPResponse = Handle->GetResponse();
                StreamReader^ Stream = gcnew StreamReader(HTTPResponse->GetResponseStream());
                String^ Response = Stream->ReadToEnd()->Trim();
                HTTPResponse->Close();
                return Response;
        }
};

int main() {
        SMSSender^ test = gcnew SMSSender();
        String^ resp = test->SendSMS("4917512345", "Hello World", "TextMessage");
        Console::WriteLine(resp);
        return 0;
}
require 'net/http'
require 'uri'

def send_sms( username, password, to, message, originator )
  requested_url = 'https://' + username + ':' + password + '@www.net2sms.gr/srvauth/index?cmd=easysms&action=send_sms' +
                "&mobile_number=" + to + "&text=" + URI.escape( message ) +
                "&originator=" + URI.escape( originator )
  url = URI.parse( requested_url )
  full_path = ( url.query.blank? ) ? url.path : "#{url.path}?#{url.query}"
  the_request = Net::HTTP::Get.new( full_path )
  the_response = Net::HTTP.start( url.host, url.port ) { |http|
    http.request( the_request )
  }
  raise "Response was not 200, response was #{the_response.code}" if the_response.code != "200"
  return the_response.bodyend
resp = send_sms( 'myUsername', 'myPassword', '4917512345', 'Hello World', 'TextMessage' )

puts(resp)
Imports System.Web

Module Module1

	Public Function SendSMS( ByVal username As String, ByVal password As String, ByVal toPhone As String, 
								ByVal message As String, ByVal originator As String )
		Dim request As HttpWebRequest  
		Dim response As HttpWebResponse = Nothing  
		Dim reader As StreamReader  
		Dim url As String = "https://www.net2sms.gr/srvauth/index?cmd=easysms&action=send_sms" &
		               "&mobile_number=" & toPhone & "&text=" & System.Web.HttpUtility.UrlEncode( message ) &
		                "&originator=" & System.Web.HttpUtility.urlencode( originator )
		Try  
		    ' Create the web request  
		    request = DirectCast(WebRequest.Create(url), HttpWebRequest)  
		    ' Add authentication to request  
		    request.Credentials = New NetworkCredential(username, password)  
		    ' Get response  
		    response = DirectCast(request.GetResponse(), HttpWebResponse)  
		    ' Get the response stream into a reader  
		    reader = New StreamReader(response.GetResponseStream())  
		    ' Return response
			SendSMS = reader.ReadToEnd()
		Finally  
		    If Not response Is Nothing Then 
				response.Close()  
				Console.WriteLine("Error connecting")
			End If
		End Try  
	End Function

    Sub Main()
        Dim result As String = SendSMS( "myUsername", "myPassword", "4917512345", "Hello World", "TextMessage" )
        Console.WriteLine( result )
        Console.ReadKey()
    End Sub

End Module

Вземи баланс

https://www.net2sms.gr/srvauth/index?cmd=easysms&action=get_balance&balance=true

Връща

Броя на оставащите текстови съобщения в акаунта

Вземи статус

Връща всички обновени статуси, разделени от вертикална черта |

https://www.net2sms.gr/srvauth/index?cmd=easysms&action=get_status&get_status=true

Връща

id_1 | status_1 | id_2 | status_2 | ...... | id_N | status_N

Статусът може да бъде s (изпратено), d (доставено) или f (неуспешно)