Codi d'exemple en llenguatge de programació PHP per integració SMS API

A continuació trobaràs els exemples de codi de programació en el llenguatge PHP per enviar missatges SMS a través de l'API de la plataforma LabsMobile.

També disposes d'exemples de codi en JavaScript, Python i altres llenguatges de programació.

Et recomanem consultis i tinguis en compte els següents recursos i ajuda al teu integració:

Enviar missatges - REST API - JSON

Aquest és el codi d'exemple en PHP per enviar missatges SMS amb la SMS API de LabsMobile en la versió JSON. Com es pot veure s'ha de crear una estructura JSON amb tots els paràmetres de l'enviament i realitzar una trucada HTTP/POST amb les dades JSON en el cos de la trucada.

És imprescindible realitzar la crida amb l'autenticació del nom d'usuari (email de registre) i la contrasenya (o token API) del compte.

            
<?php
$auth_basic = base64_encode("myusername:mypassword");

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.labsmobile.com/json/send",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => '{"message":"Text of the SMS message", "tpoa":"Sender","recipient":[{"msisdn":"12015550123"},{"msisdn":"447400123456"},{"msisdn":"5212221234567"}]}',
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic ".$auth_basic,
    "Cache-Control: no-cache",
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

Pots consultar tots els paràmetres JSON disponibles, opcions de configuració, manuals i especificacions en la següent url: https://apidocs.labsmobile.com/?php#send-sms

Consulta de crèdits - REST API - JSON

Exemple de codi en PHP per a la consulta del saldo d'un compte. El resultat sempre s'obté en crèdits interns de la plataforma LabsMobile.

            
<?php

$auth_basic = base64_encode("myusername:mypassword");

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.labsmobile.com/json/balance",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic ".$auth_basic,
    "Cache-Control: no-cache",
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

Enviar missatges - HTTP/GET

Exemple d'enviament per a la versió GET de la SMS API de LabsMobile. Aquest és un mètode bàsic i simple d'enviar missatges SMS des d'una aplicació o programari creada en PHP codificant tots els paràmetres en la mateixa url.

És important codificar tots els valors com URL (amb la funció urlencode() per exemple).

Pots veure i descarregar el manual de l'API GET de LabsMobile en la següent url: https://www.labsmobile.com/ca/api-sms/versions-api/http-get

                
<?php
    $message = '';
    if (isset($_POST['message'])) {

        if (empty($_POST['msisdn']) || empty($_POST['message'])) {
            $message = 'All fields need to be filled in';
        } else {
            $url = 'http://api.labsmobile.com/get/send.php?';
            $url .= 'username=acct01@demo.com&';
            $url .= 'password=acct01pwd&';
            $url .= 'msisdn=' . $_POST['msisdn'] . '&';
            $url .= 'message=' . $_POST['message'] . '&';

            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
            $result = curl_exec($ch);
            curl_close($ch);

            $message = htmlentities('Message has been sent.<br />Details:' . "<br />" . $result);
        }
    }
?>
<html>
    <head>
        <title>SMS Example</title>
    </head>
    <body>
        <p><?php echo $message ?></p>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
            <p>MSISDN: <input type="text" value="" name="msisdn" /></p>
            <p>Message: <input type="text" value="" maxlength="160" name="message" /></p>
            <p><input type="submit" value="Send SMS" name="send" /></p>
        </form>
    </body>
</html>

Consulta de crèdits - HTTP/GET

                
<?php
    if (isset($_POST['send'])) {
        $url = 'http://api.labsmobile.com/get/balance.php?username=acct01&password=acct01pwd';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        $result = curl_exec($ch); curl_close($ch);
        $message = htmlentities('Message has been sent.<br />Details:' . "<br />" . $result);
     }
?>
<html>
    <head>
        <title>SMS Example credit query</title>
    </head>
    <body>
        <p><?php echo $message ?></p>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
            <p><input type="submit" value="Check credit" name="send" /></p>
        </form>
</body>

Enviar missatges - HTTP/POST XML

                
<?php
    $message = '';
    if (isset($_POST['send'])) {
        if (empty($_POST['msisdn']) || empty($_POST['message'])) {
            $message = 'All fields need to be filled in';
        } else {
            $url = 'http://api.labsmobile.com/clients/';
            $username = 'acct01';
            $password = 'acct01pwd';
            $sms = '<?xml version="1.0" encoding="UTF-8"?>
                <sms>
                <recipient>
                    <msisdn>:MSISDN</msisdn>
                </recipient>
                <message><![CDATA[:MESSAGE]]></message>
                <acklevel>handset</acklevel>
                <ackurl>http://clientserver.com/motest.php</ackurl>
                </sms>';
            $sms = utf8_encode(str_replace(array(':MSISDN', ':MESSAGE'), array($_POST['msisdn'], $_POST['message']), $sms));

            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, 'XmlData='.$sms);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
            $result = curl_exec($ch); curl_close($ch);
            $message = htmlentities('Message has been sent.<br />Details:' . "<br />" . $result);
        }
    }
?>
<html>
    <head>
        <title>SMS Example</title>
    </head>
    <body>
        <p><?php echo $message ?></p>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
            <p>MSISDN: <input type="text" value="" name="msisdn" /></p>
            <p>Message: <input type="text" value="" maxlength="160" name="message" /></p>
            <p><input type="submit" value="Send SMS" name="send" /></p>
        </form>
    </body>

Consulta de crèdits - HTTP/POST

                
<?php
    if (isset($_POST['send'])) {
        $url = 'http://api.labsmobile.com/balance.php';
        $username = 'acct01';
        $password = 'acct01pwd';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        $result = curl_exec($ch); curl_close($ch);

        $message = htmlentities('Message has been sent.<br />Details:' . "<br />" . $result);
    }
?>
<html>
    <head>
        <title>SMS Example credit query</title>
    </head>
    <body>
        <p><?php echo $message ?></p>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
            <p><input type="submit" value="Check credit" name="send" /></p>
        </form>
</body>

Confirmació de recepció ACK

                
<?php
    $acklevel = $_GET['acklevel'];
    $msisdn = $_GET['msisdn'];
    $status = $_GET['status'];
    $subid = isset($_GET['subid']) ? $_GET['subid'] : '';
    $timestamp = $_GET['timestamp'];

    $string = "At $timestamp we recieved a";
    if ($status == 'ok') {
        $string .= ' positive ';
    } else {
        $string .= ' negative ';
    }
    $string .= "$acklevel ack with $msisdn as the receiver\n";

    file_put_contents('ack.txt', $string, FILE_APPEND);
?>

Enviar missatges - WebService

                
<?php
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    require_once('../lib/nusoap.php');
    $proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
    $proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
    $proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
    $proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';

    $client = new nusoap_client('http://api.labsmobile.com/ws/services/LabsMobileWsdl.php?WSDL', false, $proxypassword);
    $err = $client->getError();
    if ($err) {
        echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
    }
    $client->soap_defencoding = 'UTF-8';

    $funciones = array();
    $params = array();
    $result = $client->call('SendSMS', array('client' => "priv001", 'username' => "acct01@demo.com", 'password' => "acct01pwd", 'xmldata' => "
            <?xml version="1.0" encoding="UTF-8"?><sms>
            <recipient>
                <msisdn>34609542312</msisdn> </recipient>
                <message><![CDATA[Test message number 1]]></message>
                <tpoa><![CDATA[Sender name]]></tpoa> </sms>"), '', '', false, true);

    if ($client->fault) {
        echo '<h2>Fault</h2><pre>';
        print_r($result);
        echo '</pre>';
    } else {
        $err = $client->getError();
        if ($err) {
            echo '<h2>Error</h2><pre>' . $err . '</pre>';
        } else {
            echo '<h2>Result</h2><pre>';
            print_r($result);
            echo '</pre>';
        }
    }
    echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
    echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
    echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
?>
  • contact form support

    Registra't!

    Crea un compte d'usuari i envia missatges SMS en segons. Tindràs totes les funcionalitats i prestacions a una mateixa plataforma.

    Envia des de l'API i gestiona el teu compte amb la nostra aplicació online WebSMS.

    Crea un compte
  • Qids, L'app de comunicació per a pares recomana LabsMobile

    Validació d'usuaris a l'app i enviament d'invitacions per a la descàrrega de l'aplicació als contactes dels usuaris.

    Veure més opinions
  • dashboard aplicación online

    La màxima fiabilitat al millor preu

    A LabsMobile només oferim rutes directes de màxima fiabilitat i qualitat. Gaudeix de la nostra plataforma i de totes nostres serveis pel preu d'un SMS.

    Paga NOMÉS pels missatges enviats.

    Consulta les nostres tarifes
  • dashboard aplicación online

    Més info? Contacta amb nosaltres!

    El nostre departament tècnic compta amb professionals amb anys d'experiència i hem realitzat múltiples integracions.

    Et guiem i ajudem en tot el procés.

    Sol·licita suport tècnic
  • Integra la teva aplicació amb la nostra API

    Aquest tutorial explica com iniciar la integració de qualsevol aplicació o programari amb la plataforma de comunicació SMS de LabsMobile.

    Ir al tutorial