Completed

Integrar Api

Published on the September 12, 2015 in IT & Programming

About this project

Open

Trabajo con whmcs y un addon que se llama sms notifier, (como se imaginan, envia las notificaciones por sms). Viene con ciertos gateways pre-configurados, pero yo quiero uno en argentina que se llama SMSC

Tengo la api key del smsc y  el SMS notifier me da un archivo "ejemplo" para que yo ingrese mi nuevo gateway .

Necesito alguien que sepa como configurar y vincular.
Voy a dejar en este texto el demo del sms notifier, y el demo que me da smsc.

Quien pueda configurarlo que me diga cuanto demora y cuanto es, por lo que tengo entendido es algo rapido y sencillo, pero para quein realmente entiende.
Lo necesito lo antes posible.

Muchas graicas


---- sms notifier (el addon que utilizo) ----
<?php
defined( '_smsnotify' ) or die( 'restricted access' );
//--------------------------example.com API v3.x-----------------------------------------
function mygateway_gatewaydetails(){
    $details=array();
    $details["name"]="Gateway Default Name";
    $details["country"]="Coverage - Country";
    $details["site"]="http://www.sitepage.com";
    $details["pricelist"]="http://www.sitapage.com/pricing-page.php";
    $details["developer"]="Your name | your@e-mail.com";
    $details["schedulesms"]=false; /*set true if gateway supports sms scheduling*/
    $details["unicodesupport"]=false; /*set true if gateway supports Unicode sms*/
    $details["params"]["customsender"]=array("type"=>"text","value"=>"","name"=>"Custom SenderID","description"=>"If you leave it empty it will get the global SenderID value from <<Settings>>");

    #Custom Parameters types - (Delete the following examples)
    //Text Box
    $details["params"]["customparam"]=array("type"=>"text","value"=>"","name"=>"Custom Param","description"=>".....");
    //SelectBox
    $details["params"]["region"]=array("type"=>"selectbox","options"=>"International,UK,South Africa,Spain,USA,Germany","name"=>"Region:","description"=>"Select Region that your account is created to.");
    //Radio Box
    $details["params"]["upper"]=array("type"=>"yesno","value"=>"no","name"=>"UPPERCASE","description"=>"Covert chars to uppercace");

    return $details;
}

function mygateway_sendsms($params){
    $params["senderid"]=(!empty($params["customsender"]))?trim($params["customsender"]):trim($params["senderid"]);
    $params["to"]=urlencode($params["to"]); //Phone(s) seperated by commas
    
    /*DEBUG*/
    $paramsString=print_r($params,true);
    #echo $paramsString; //Debug via print to screen
    #mail('my@email.com','SMS Notify Debug',$paramsString); //Debug via e-mail
    
    //If your gateway supports SMS Scheduling EXAMPLE
    $schedule="";
    if($params["schedule_time"]!='' && $params["schedule_date"]!=''){
        $datetime=date('Y-m-d H:i', strtotime($params["schedule_date"].' '.$Params["schedule_time"])); // change date format
        $schedule="&scheduled_time=".$Datetime; // add param
    }
    if($params["longsms"]!='yes') $params["message"]=smscut($params["message"],160); //short sms
    if($params["unicode"]=="yes") $params["message"]=unicode($params["message"]); //unicode() converts ascci text to unicode data
    
    #EXAMPLE
    $url = "http://mysite/post-url/send.php?user=".urlencode($params["username"])."&Password=".urlencode($params["password"]).'&Msg='.urlencode($params["message"]);
    $url.="&To=".$Params["to"]."&From=".$Params["senderid"];
    if(!empty($schedule)) $url.=$Schedule; //if supported
    if($params["unicode"]=="yes") $url.='&Unicode=1'; //if supported
    
    $data=getRemoteData($url); // Send request
    /*Returns
      $data["response"]; =>The response
      $data["error"]; =>Connections errors (rare)
    */
    
    //Communications with gateway api server error check
    if(!empty($data['error']) || empty($data["response"])) return array('error'=>$data['error'],'smsid'=>time()); //stop because of communication error
    
    //example $data["response"]="ok,id12121212,20-08-2013"; or $data["response"]="error:005";
    
    $values=array();
    $parts=explode(',',$data["response"]);
    if($parts[0]=='ok'){
        $values["smsid"]=$parts[1]; //// required to able to get the status mygateway_getsmsstatus()
    }else{
        $parts=explode(':',$data["response"]);
        if($parts[0]=='error'){
            $values['error']=mygateway_errorcodes($parts[1]);
        }else{
            $values['error']=$data["response"]; //unknown reason-response
        }
    }
    logger('send.mygateway',$url,$data,array_merge($values,$params),array($params["username"],$params["password"])); //ModuleLogging

    /*  Multiply IDs/Errors Support
        $values["smsid"] and $values['error'] can contain array. Example:
        $ids[0]='123456';
        $errors[0]=null;
        $ids[1]='err'.time();
        $errors[1]='Invalid Sender ID';
        $values['error']=$errors;
        $values['smsid']=$ids;
    */
    return $values;
}

function mygateway_getSmsBalance($params){
    $url ="http://mysite/post-url/getbalance?&user=". Urlencode($params["username"])."
&Password=".urlencode($params["password"]);
    $data=getRemoteData($url);
    
    //Communications with gateway API server error check
    if(!empty($data['error'])) return array('error'=>$data['error'],'credits'=0); //stop because of communication error
    
    //example $data["response"]="Credit:1200";
    $values=array();
    $send = explode(":",$data["response"]);
    if ($send[0] == "Credit") {
        $values["credits"]=$send[1];
    } else {
        $values["error"]=$data["response"];
        $values["credits"]=0;
    }
    return $values;
}

function mygateway_getsmsstatus($params){
    $url = "http://mysite/post-url/getDLR?user=".urlencode($params["username"])."&Password=".urlencode($params["password"])."&Msgid=".$Params["smsid"];
    $data=getRemoteData($url);
    
    //$data["response"]; =>The response
    //$data["error"]; =>Connections errors (rare)
    
    //Communications with gateway API server error check
    if(!empty($data['error'])) return array('status'=2,'cost'=>0); //stop because of communication error,we don't pass the error because may it's temporary so we set it as Pending (status=2)    
    
    //example $data["response"]="003,id12121212,2c,20-08-2013";
    $parts=explode(',',$data["response"]);

    /* ====== $error_code vars ====== */
    # 0 Not Delivered Failed/ Error (Permanent)
    # 1 Delivered Succesfully (Permanent)
    # 2 Sent but Pending (Not Permanent) *
    # 3 Unknown (Not Permanent) *
        
    switch($parts[0]){
        case '001':
            $error_code=3; // Unknown
            break;
        case '002':
        case '008':
        case '011':
            $error_code=2; //Pending
            break;
        case '003':    
        case '004':
            $error_code=1; //Susccess
            break;
        case '005':
        case '006':
        case '007':
        case '009':
        case '010':
        case '012':
            $error_code=0; // Failed
            break;
        default:
            $error_code=3;
    }
    
    $values=array();
    $values["status"]=$error_code;
    if($error_code==0) $values['error']=mygateway_errorcodes($parts[0]);
    $values["cost"]=str_replace('c','',$parts[1]); // if cost is available pass the value here as number
    return $values;
}
//Helper Function!
function mygateway_errorcodes($code){
    $error=''
    if($code=='005'){
        $error='No credits';
    }elseif($code=='006'){
        $error='Invalid destination';
    }
    //etc
    return $error;    
}





------------------------  el ejemplo del gateway que quiero smsc -----------



<?php
/**
* smsc api
*
* @author pablo gabriel reyes
* @link https://smsc.com.ar/ Smsc
* @link https://github.com/smsc/smsc-api-php Smsc on GitHub
* @version 1.0.0
*/

class Smsc
{
    /**
     * @var string ApiKey de SMSC
     */
    private $apikey = '';

    /**
     * @var string Alias de SMSC
     */
    private $alias = '';

    private $mensaje = '';

    private $return = '';

    public function  __construct($alias = null, $apikey = null) {
        if ($alias !== null)
            $this->setAlias ($alias);
        if ($apikey !== null)
            $this->setApikey ($apikey);

    }

    public function getApikey()
    {
     return $this->apikey;
    }
    public function setApikey($apikey)
    {
     $this->apikey = $apikey;
    }

    public function getAlias()
    {
     return $this->alias;
    }
    public function setAlias($alias)
    {
     $this->alias = $alias;
    }


    public function getData()
    {
        return $this->return['data'];
    }

    public function getStatusCode()
    {
        return $this->return['code'];
    }

    public function getStatusMessage()
    {
        return $this->return['message'];
    }

    public function exec($cmd = null, $extradata = null)
    {
        $this->return = null;

        // construyo la URL de consulta
        $url = 'https://www.smsc.com.ar/api/0.2/?alias='.$This->alias.'&Apikey='.$This->apikey;
        $url2 = '';
        if ($cmd !== null)
            $url2 .= '&Cmd='.$Cmd;
        if ($extradata !== null)
            $url2 .= $Extradata;

        // hago la consulta
        $data = @file_get_contents($url.$Url2);
        if ($data === false)
        {
            throw new Exception('No se pudo conectar al servidor.', 1);
            return false;
        }
        $ret = json_decode($data, true);
        if (!is_array($ret))
        {
            throw new Exception('Datos recibidos, pero no han podido ser reconocidos ("'.$Data.'") (Url2='.$Url2.').', 2);
            return false;
        }
        $this->return = $ret;
        return true;
    }


    /**
     * Estado del sistema SMSC.
     * @Return bool Devuelve true si no hay demoras en la entrega.
     */
    Public function getEstado()
    {
        $ret = $this->exec('estado');
        if (!$ret)
            return false;
        if ($this->getStatusCode() != 200)
        {
             throw new Exception($this->getStatusMessage(), $this->getStatusCode());
             return false;
        } else {
            $ret = $this->getData();
            return $ret['estado'];
        }
    }


    /**
     * Validar número
     * @return bool Devuelve true si es un número válido.
     */
    Public function evalNumero($prefijo, $fijo = null)
    {
        $ret = $this->exec('evalnumero', '&num='.$Prefijo.($Fijo === null?'':'-'.$Fijo));
        if (!$ret)
            return false;
        if ($this->getStatusCode() != 200)
        {
             throw new Exception($this->getStatusMessage(), $this->getStatusCode());
             return false;
        } else {
            $ret = $this->getData();
            return $ret['estado'];
        }
    }


    /**
     *
     * @return array
     */
    public function getSaldo()
    {
        $ret = $this->exec('saldo');
        if (!$ret)
            return false;
        if ($this->getStatusCode() != 200)
        {
            throw new Exception($this->getStatusMessage(), $this->getStatusCode());
            return false;
        } else {
            $ret = $this->getData();
            return $ret['mensajes'];
        }
    }


    /**
     *
     * @param int $prioridad 0:todos 1:baja 2:media 3:alta
     * @return array
     */
    public function getEncolados($prioridad = 0)
    {
        $ret = $this->exec('encolados', '&prioridad='.intval($prioridad));
        if (!$ret)
            return false;
        if ($this->getStatusCode() != 200)
        {
            throw new Exception($this->getStatusMessage(), $this->getStatusCode());
            return false;
        } else {
            $ret = $this->getData();
            return $ret['mensajes'];
        }
    }


    /**
     * *******************************************
     * *******  Metodos para enviar SMS  *******
     * *******************************************
     */

    /**
     * @param integer $prefijo    Prefijo del área, sin 0
     *                    Ej: 2627 ó 2627530000
     * @param integer $fijo Número luego del 15, sin 15
     *                    Si sólo especifica prefijo, se tomará como número completo (no recomendado).
     *                    Ej: 530000
     */
    public function addNumero($prefijo, $fijo = null)
    {
        if ($fijo === null)
            $this->numeros[] = $prefijo;
        else
            $this->numeros[] = $prefijo.'-'.$Fijo;
    }

    public function getMensaje()
    {
        return $this->mensaje;
    }
    public function setMensaje($mensaje)
    {
        $this->mensaje = $mensaje;
    }

    public function enviar()
    {
        $ret = $this->exec('enviar', '&num='.implode(',', $this->numeros).'&Msj='.urlencode($this->mensaje));
        if (!$ret)
            return false;
        if ($this->getStatusCode() != 200)
        {
             throw new Exception($this->getStatusMessage(), $this->getStatusCode());
             return false;
        } else {
            return $this->getData();
        }
    }


    /**
     * ***********************************************
     * *******  Metodos para hacer consultas  *******
     * ***********************************************
     */

    /**
     * Devuelve los últimos 30 SMSC recibidos.
     *
     * Lo óptimo es usar esta función cuando se recibe la notificación, que puede
     * especificar en https://www.smsc.com.ar/usuario/api/
     *
     * @param int $ultimoid si se especifica, el sistema sólo devuelve los SMS
     *                        más nuevos al sms con id especificado (acelera la
     *                        consulta y permite un chequeo rápido de nuevos mensajes)
     */
    public function getRecibidos($ultimoid = 0)
    {
        $ret = $this->exec('recibidos', '&ultimoid='.(int)$ultimoid);
        if (!$ret)
            return false;
        if ($this->getStatusCode() != 200)
        {
             throw new Exception($this->getStatusMessage(), $this->getStatusCode());
             return false;
        } else {
            return $this->getData();
        }
    }

}





Aguardo presupuestos y tiempos de implementacion

Category IT & Programming
Subcategory Web development
Is this a project or a position? Project
I currently have I have specifications
Required availability As needed
Experience in this type of projects No (I haven’t managed this kind of project before)
API Integrations Other (Other APIs)
Roles needed Developer

Delivery term: September 14, 2015

Skills needed