REST SMS API v.2 del desarrollador para comunicarse con el Portal de Enlace SMS

Este documento proporciona una referencia para todas las funciones disponibles a través de la interfaz HTTP para enviar SMS.
La API de HTTP te permite integrar su aplicación (cliente) al (portal) de premium-sms.gr utilizando el protocolo HTTP para enviar SMS.

Info General

El cliente envía una solicitud GET HTTP a la interfaz HTTP de premium-sms.gr al suministrar una lista de parámetros necesarios. premium-sms.gr emite de vuelta una respuesta HTTP que indica el éxito de la operación

Ten en cuenta que el delimitador utilizado para el status de la llamada API a continuación en datos devueltos, '|', es el carácter de barra vertical (ASCII 124).

Todos los parámetros pasados debe ser codificados en URL y también en UTF-8, tal como se describe en los siguientes ejemplos de código.

Formato de respuestas API

La API responde a todas las llamadas de acuerdo con el parámetro tipo. Los valores aceptados para el parámetrotipo son => v2 que es el valor por defecto, json y xml.
Ejemplo de respuestas para llamada a lakey/get de la API =>

...&type=v2

Responde:

6fe2dd9c06df83

...&type=json

Responde:

{
   "status" : "1",
   "key" : "6fe2dd9c06df83",
   "remarks" : "Success"
}

...&type=xml

Responde:

<response>
   <status>1</status>
   <key>6fe2dd9c06ff83</key>
   <remarks>Success</remarks>
</response>

Prúebalo   (key/get)

http://premium-sms.gr/api/key/get?username=&password=&type=
Prúebalo  

Los comandos disponibles en la v.2 de la API de premium-sms.gr se muestran a continuación.




API Key

La Clave de la API se debe utilizar en lugar del nombre de usuario y contraseña para todas las llamadas a la API. Puede seguir utilizando los parámetros de nombre de usuario y contraseña, pero se recomienda el uso de la Clave API por razones de seguridad.

Tú adquieres tu Clave API usando la llamada de key/get y lo utiliza para todas las llamadas a la API en lugar de los parámetros de usuario y contraseña. Si necesitas cambiar la Clave API, puedes hacerlo mediante la llamada de key/reset.
Las llamadas de key/get y key/reset son las únicas que requieren el uso de nombre de usuario y contraseña.
Una vez que obtienes tu Clave API puedes usarla para las otras llamadas de API.

Prúebalo   (key/get)

http://premium-sms.gr/api/key/get?username=&password=&type=
Prúebalo  

Prúebalo   (key/reset)

http://premium-sms.gr/api/key/reset?username=&password=&type=
Prúebalo  

Devolución

...&type=v2

Responde:

6fe2dd9c06df83

...&type=json

Responde:

{
   "status" : "1",
   "key" : "6fe2dd9c06df83",
   "remarks" : "Success"
}

...&type=xml

Responde:

<response>
   <status>1</status>
   <key>6fe2dd9c06ff83</key>
   <remarks>Success</remarks>
</response>
 

Enviando SMS

RESTful SMS API v.2

URL: http://premium-sms.gr/api/sms/send?key=[API Key]

Parámetros aceptados

Parámetro Descripción Presencia
text Mensaje que se enviará. Debe ser codificado en URL. Requerido
to MSIDSN del destinatario del mensaje que será enviado. Ej => 49175123456 Requerido
from ID del Remitente (Si es alfanumérico, máx 11 caracteres, o máx 16 dígitos numéricos) Opcional
flash Activar envío de Flash SMS Opcional
ucs Activar el envío de SMS utilizando codificación UCS Opcional
timestamp Establecer la fecha y la hora al estilo Unix Epoch para enviar el SMS Opcional
type Tipo de respuesta API, puede ser v2, json o xml Opcional

Devoluciones

...&type=v2

Responde:

1234567890

...&type=json

Responde:

{
   "status" : "1",
   "id" : "1234567890",
   "balance" : "1234",
   "remarks" : "Success"
}

...&type=xml

Responde:

<response>
   <status>1</status>
   <id>1234567890</id>
   <balance>1234</balance>
   <remarks>Success</remarks>
</response>
Descripción
código de resultado 1 para el mensaje enviado, de lo contrario envío fallido
sms_id el número de ID de mensaje (o 0 si no se envió). Los reportes de entrega se dan en los ID del mensaje
saldo el saldo de la cuenta
remarks Notas sobre la llamada

Prúebalo   (sms/send)

http://premium-sms.gr/api/sms/send?key=&to=&from=&text=Hello&type=
Prúebalo  

Ejemplos de código para el envío de SMS

<?php
	// Simple SMS send function
	function sendSMS($key, $to, $message, $originator) {
		$URL = "http://premium-sms.gr/api/sms/send?key=" . $key . "&to=" . $to;
		$URL .= "&text=" . urlencode( $message ) . '&from=' . urlencode( $originator );
		$fp = fopen( $URL, 'r' );
		return fread( $fp, 1024 );
	}
	// Example of use 
	$response = sendSMS( 'My API Key', '4917512345', 'My test message', 'MyMessage' );
	echo $response;
?>
<?php
    // Simple SMS send function
    function sendSMS($key, $to, $message, $originator) {
        $URL = "http://premium-sms.gr/api/sms/send?key=" . $key . "&to=" . $to;
        $URL .= "&text=".urlencode($message).'&from='.urlencode($originator);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $URL);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);
        return $output;
    }
    // Example of use
    $response = sendSMS('My API Key', '4917512345', 'My test message', 'MyMessage');
    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 key, String to, String message, String originator ) {

        String webPage;
        try {
            webPage = "http://premium-sms.gr/api/sms/send?key=" + key +
                "&to=" + to + "&text=" + URLEncoder.encode( message, "UTF-8" ) +
                "&from=" + URLEncoder.encode( originator, "UTF-8" );
        } catch ( UnsupportedEncodingException e ) {
            return "UnsupportedEncodingException";
        }

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

			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( "My API Key", "4917512345", "My test message", "MyMessage" );
        System.out.println( response );
    }
}
<%
    mykey = "My API Key" 'put your API Key here
    mobile = "4917512345"

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

    url = "http://premium-sms.gr/api/sms/send?key=" + mykey + "&to=" + mobile + "&text=" + message + "&from=" + originator

    set objSrvHTTP = Server.CreateObject("Msxml2.ServerXMLHTTP")
    objSrvHTTP.open "GET", url, False
    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 key, string to, string message, string originator ) {
            StringBuilder sb  = new StringBuilder();
            byte[] buf = new byte[ 1024 ];
            string url = "http://premium-sms.gr/api/sms/send?key=" + key +
                "&to=" + to + "&text=" + HttpUtility.UrlEncode( message ) +
                "&from=" + HttpUtility.UrlEncode( originator );
            HttpWebRequest request = ( HttpWebRequest ) WebRequest.Create( url );
            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( "My API Key", "4917512345", "My test message", "MyMessage" );
            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 *key, const char *to, char *message, char *originator) {
        static char url[URLSIZE] = "http://premium-sms.gr/api/sms/send?key=";
        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, key);
                strcat_s(url, URLSIZE, "&to=");
                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, "&from=");
                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("My API Key", "4917512345", "My test message", "MyMessage");
        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^ Key = "My API Key";

public:
        SMSSender()
        {}
        String^ SendSMS(String^ To, String^ Message, String^ From)
        {
                Message = HttpUtility::UrlEncode(Message);
                From = HttpUtility::UrlEncode(From);
                String^ URL = "http://premium-sms.gr/api/sms/send?key=" + Key + "&text=" + Message + "&from=" + From + "&to=" + 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", "My test message", "MyMessage");
        Console::WriteLine(resp);
        return 0;
}
require 'net/http'
require 'uri'

def send_sms( key, to, message, originator )
  requested_url = 'http://premium-sms.gr/api/sms/send?key=' + key +
                "&to=" + to + "&text=" + URI.escape( message ) +
                "&from=" + 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( 'My API Key', '4917512345', 'My test message', 'MyMessage' )

puts(resp)
Imports System.Web

Module Module1

	Public Function SendSMS( ByVal key 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 = "http://premium-sms.gr/api/sms/send?key=" & key &
		                "&to=" & toPhone & "&text=" & System.Web.HttpUtility.UrlEncode( message ) &
		                "&from=" & System.Web.HttpUtility.urlencode( originator )
		Try
		    ' Create the web request  
		    request = DirectCast(WebRequest.Create(url), HttpWebRequest)
		    ' 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( "My API Key", "4917512345", "My test message", "MyMessage" )
        Console.WriteLine( result )
        Console.ReadKey()
    End Sub

End Module


Obtener saldo

URL:   http://premium-sms.gr/api/balance/get?key=[API Key]

Devoluciones

El número de SMS que quedan en la cuenta

...&type=v2

Responde:

1234

...&type=json

Responde:

{
   "status" : "1",
   "balance" : "1234",
   "remarks" : "Success"
}

...&type=xml

Responde:

<response>
   <status>1</status>
   <balance>1234</balance>
   <remarks>Success</remarks>
</response>

Prúebalo   (balance/get)

http://premium-sms.gr/api/balance/get?key=&type=
Prúebalo  

Obtener Status

URL:   http://premium-sms.gr/api/status/get?key=[API Key]

Devoluciones

Devuelve todos los mensajes cuyo estado ha cambiado, separadas por una barra vertical | (cuando el parámetro tipo es v2)

El status puede ser s (enviado), d (entregado) o f (fallido)

...&type=v2

Responde:

...&type=json

Responde:

{
   "0" : {
           "id" : "1231223122",
           "status" : "d"
   },
   "1" : {
           "id" : "1234561232",
           "status" : "f"
   },
   "status" : "1",
   "total" : "2",
   "remarks" : "Success"
}

...&type=xml

Responde:

<response>
   <status>1</status>
   <total>2</total>
   <remarks>Success</remarks>
   <sms>
            <id>1231223122</id>
            <status>d</status>
   </sms>
   <sms>
            <id>1234561232</id>
            <status>f</status>
   </sms>
</response>

Prúebalo   (status/get)

http://premium-sms.gr/api/status/get?key=&type=
Prúebalo