Randeep
Randeep

Reputation: 543

creating custom sms provider for vtiger

I'm trying to modify MyProvider.php which comes with vtiger crm for my sms provider. My sms provider url s as follows http://sms.valueleaf.com/sms/user/urlsms.php?username=abc&pass=xyz&senderid=12345&message=hi how are you&dest_mobileno=91988000000&response=Y

But the program I wrote is not working. As i'm not a php developer i'm struggling. can anyone please have a look and help me.

I have edited as below,But I think there are some syntax errors are also there.

#vim ValueLeaf.php
include_once dirname(__FILE__) . '/../ISMSProvider.php';
include_once 'vtlib/Vtiger/Net/Client.php';

class ValueLeaf implements ISMSProvider {

private $_username;
private $_password;
private $_parameters = array();

const SERVICE_URI = 'sms.valueleaf.com';

**//I added senderid and response to array to include in the url.**
private static $REQUIRED_PARAMETERS = array('senderid','response');

function __construct() {
}

public function setAuthParameters($username, $password) {
$this->_username = $username;
$this->_password = $password;
}

public function setParameter($key, $value) {
$this->_parameters[$key] = $value;
}

public function getParameter($key, $defvalue = false) {
if(isset($this->_parameters[$key])) {
return $this->_parameters[$key];
}
return $defvalue;
}
public function getRequiredParams() {
return self::$REQUIRED_PARAMETERS;
}

public function getServiceURL($type = false) {
if($type) {
switch(strtoupper($type)) {

**//As I dont use authentication i commented it.**
case self::SERVICE_AUTH: return self::SERVICE_URI; // . '/http/auth';
case self::SERVICE_SEND: return self::SERVICE_URI . '/sms/user/urllongsms.php';
case self::SERVICE_QUERY: return self::SERVICE_URI . '/sms/user/responce.php';

}
}
return false;
}

protected function prepareParameters() {
**//extended to get and set the additional parameters**
$params = array('username' => $this->_username, 'pass' => $this->_password, 'senderid' => $this->senderid,'response'=> $this->response);
//$params = array();
foreach (self::$REQUIRED_PARAMETERS as $key) {
$params[$key] = $this->getParameter($key);
}
return $params;
}

**//Here I'm little confused.Actually in the actual file its $tonumbers. But in the http api its like dest_mobileno=91988000000. I dont know where to change it.**
public function send($message, $tonumbers) {
if(!is_array($tonumbers)) {
$tonumbers = array($tonumbers);
}

$params = $this->prepareParameters();
$params['text'] = $message;
$params['to'] = implode(',', $tonumbers);

$serviceURL = $this->getServiceURL(self::SERVICE_SEND);
$httpClient = new Vtiger_Net_Client($serviceURL);
$response = $httpClient->doPost($params);

$responseLines = split("\n", $response);

$results = array();
foreach($responseLines as $responseLine) {

$responseLine = trim($responseLine);
if(empty($responseLine)) continue;

$result = array( 'error' => false, 'statusmessage' => '' );
if(preg_match("/ERR:(.*)/", trim($responseLine), $matches)) {
$result['error'] = true;
$result['to'] = $tonumbers[$i++];
$result['statusmessage'] = $matches[0]; // Complete error message
} else if(preg_match("/ID: ([^ ]+)TO:(.*)/", $responseLine, $matches)) {
$result['id'] = trim($matches[1]);
$result['to'] = trim($matches[2]);
$result['status'] = self::MSG_STATUS_PROCESSING;

} else if(preg_match("/ID: (.*)/", $responseLine, $matches)) {
$result['id'] = trim($matches[1]);
$result['to'] = $tonumbers[0];
$result['status'] = self::MSG_STATUS_PROCESSING;
}
$results[] = $result;
}
return $results;
}

**//I'm not checking the query fucntion now. First thing is to send and recieve.**
public function query($messageid) {

//$params = $this->prepareParameters();
$params['workingkey'] = $REQUIRED_PARAMETERS('workingkey');
$params['messageid'] = $messageid;

$serviceURL = $this->getServiceURL(self::SERVICE_QUERY);
$httpClient = new Vtiger_Net_Client($serviceURL);
$response = $httpClient->doPost($params);

$response = trim($response);

$result = array( 'error' => false, 'needlookup' => 1 );

if(preg_match("/ERR: (.*)/", $response, $matches)) {
$result['error'] = true;
$result['needlookup'] = 0;
$result['statusmessage'] = $matches[0];

} else if(preg_match("/ID: ([^ ]+) Status: ([^ ]+)/", $response, $matches)) {
$result['id'] = trim($matches[1]);
$status = trim($matches[2]);

// Capture the status code as message by default.
$result['statusmessage'] = "CODE: $status";

if($status === '1') {
$result['status'] = self::MSG_STATUS_PROCESSING;
} else if($status === '2') {
$result['status'] = self::MSG_STATUS_DISPATCHED;
$result['needlookup'] = 0;
}
}

return $result;
}
}
?>

I was editing the code and checking. Still I'm not able to get any result. I have given the printf to get the final url which goes to the sms provider. But not getting. Any idea where I have to give the right printf to get the final details?

Updated code: 1. sms.php

<?php
/*+**********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 ************************************************************************************/
include_once dirname(__FILE__) . '/../ISMSProvider.php';
include_once 'vtlib/Vtiger/Net/Client.php';

class sms implements ISMSProvider {

    private $_username;
    private $_password;
    private $_parameters = array();

    const SERVICE_URI = 'http://sms.valueleaf.com';
    private static $REQUIRED_PARAMETERS = array('senderid','response');
    function __construct() {        
    }

    public function setAuthParameters($username, $password) {
        $this->_username = $username;
        $this->_password = $password;
    }

    public function setParameter($key, $value) {
        $this->_parameters[$key] = $value;
    }

    public function getParameter($key, $defvalue = false)  {
        if(isset($this->_parameters[$key])) {
            return $this->_parameters[$key];
        }
        return $defvalue;
    }

    public function getRequiredParams() {
        return self::$REQUIRED_PARAMETERS;
    }

    public function getServiceURL($type = false) {      
        if($type) {
            switch(strtoupper($type)) {

                case self::SERVICE_AUTH: return  self::SERVICE_URI; // . '/http/auth';
                case self::SERVICE_SEND: return  self::SERVICE_URI . '/sms/user/urllongsms.php?';
                case self::SERVICE_QUERY: return self::SERVICE_URI . '/sms/user/responce.php?';

            }
        }
        return false;
    }

    protected function prepareParameters() {
        $params = array('username' => $this->_username, 'pass' => $this->_password);
        //$params = array();
        foreach (self::$REQUIRED_PARAMETERS as $key) {
            $params[$key] = $this->getParameter($key);
        }
        return $params;
    }

        //$file0 = fopen("test0.txt","w");
                //echo fprintf($file0,"came before send");
    public function send($message, $tonumbers) {
        if(!is_array($tonumbers)) {
            $tonumbers = array($tonumbers);
        }

        $params = $this->prepareParameters();
        //$params['text'] = $message;
        $params['message'] = $message;
        //$params['to'] = implode(',', $tonumbers);
        $params['dest_mobileno'] = implode(',', $tonumbers);

        $serviceURL = $this->getServiceURL(self::SERVICE_SEND);     
        $file = fopen("test.txt","w");
        echo fprintf($file,"url is %s.",$serviceURL);
        $httpClient = new Vtiger_Net_Client($serviceURL);
        $file1 = fopen("test1.txt","w");
        $response = $httpClient->doPost($params);       

        foreach (self::$REQUIRED_PARAMETERS as $key) {
            echo fprintf($file1,"String %s value is %s.",$key,$params[$key]);
        }
        echo fprintf($file1,"Message is: %s",$message);
        echo fprintf($file1,"dest_mobileno is: %s",$tonumbers[0]);
        echo fprintf($file1,"Response is %s.",$response);
        $responseLines = split("\n", $response);        

        $results = array();
        foreach($responseLines as $responseLine) {

            $responseLine = trim($responseLine);            
            if(empty($responseLine)) continue;

            $result = array( 'error' => false, 'statusmessage' => '' );
            if(preg_match("/ERR:(.*)/", trim($responseLine), $matches)) {
                $result['error'] = true; 
                $result['to'] = $tonumbers[$i++];
                $result['statusmessage'] = $matches[0]; // Complete error message
            } else if(preg_match("/ID: ([^ ]+)TO:(.*)/", $responseLine, $matches)) {
                $result['id'] = trim($matches[1]);
                $result['to'] = trim($matches[2]);
                $result['status'] = self::MSG_STATUS_PROCESSING;

            } else if(preg_match("/ID: (.*)/", $responseLine, $matches)) {
                $result['id'] = trim($matches[1]);
                $result['to'] = $tonumbers[0];
                $result['status'] = self::MSG_STATUS_PROCESSING;
            }
            $results[] = $result;
        }       
        return $results;
    }


    public function query($messageid) {

        //$params = $this->prepareParameters();
//      $params['workingkey'] = $REQUIRED_PARAMETERS('workingkey');
        $params['messageid'] = $messageid;

        $serviceURL = $this->getServiceURL(self::SERVICE_QUERY);
        $httpClient = new Vtiger_Net_Client($serviceURL);
        $response = $httpClient->doPost($params);

        $response = trim($response);

        $result = array( 'error' => false, 'needlookup' => 1 );

        if(preg_match("/ERR: (.*)/", $response, $matches)) {
            $result['error'] = true;
            $result['needlookup'] = 0;
            $result['statusmessage'] = $matches[0];

        } else if(preg_match("/ID: ([^ ]+) Status: ([^ ]+)/", $response, $matches)) {
            $result['id'] = trim($matches[1]);
            $status = trim($matches[2]);

            // Capture the status code as message by default.
            $result['statusmessage'] = "CODE: $status";

            if($status === '1') {
                $result['status'] = self::MSG_STATUS_PROCESSING;
            } else if($status === '2') {
                $result['status'] = self::MSG_STATUS_DISPATCHED;
                $result['needlookup'] = 0;
            }
        } 

        return $result;
    } 
}

?>
  1. ISMSProvider.php

    /+***********************************************

    • The contents of this file are subject to the vtiger CRM Public License Version 1.0
    • ("License"); You may not use this file except in compliance with the License
    • The Original Code is: vtiger CRM Open Source
    • The Initial Developer of the Original Code is vtiger.
    • Portions created by vtiger are Copyright (C) vtiger.
    • All Rights Reserved. ************************************************/ interface ISMSProvider {

      const MSG_STATUS_DISPATCHED = "Dispatched"; const MSG_STATUS_PROCESSING = "Processing"; const MSG_STATUS_DELIVERED = "Delivered"; const MSG_STATUS_FAILED = "Failed"; const MSG_STATUS_ERROR = "ERR: ";

      const SERVICE_SEND = "SEND"; const SERVICE_QUERY= "QUERY"; const SERVICE_PING = "PING"; const SERVICE_AUTH = "AUTH";

      /**

      • Get required parameters other than (username, password) */ public function getRequiredParams();

      /**

      • Get service URL to use for a given type *
      • @param String $type like SEND, PING, QUERY */ public function getServiceURL($type = false);

      /**

      • Set authentication parameters *
      • @param String $username
      • @param String $password */ public function setAuthParameters($username, $password);

      /**

      • Set non-auth parameter. *
      • @param String $key
      • @param String $value */ public function setParameter($key, $value);

      /**

      • Handle SMS Send operation *
      • @param String $message
      • @param mixed $tonumbers One or Array of numbers */ public function send($message, $tonumbers);

      /**

      • Query for status using messgae id *
      • @param String $messageid */ public function query($messageid);

    }

  2. Client.php

    /+************************************************

    • The contents of this file are subject to the vtiger CRM Public License Version 1.0
    • ("License"); You may not use this file except in compliance with the License
    • The Original Code is: vtiger CRM Open Source
    • The Initial Developer of the Original Code is vtiger.
    • Portions created by vtiger are Copyright (C) vtiger.
    • All Rights Reserved. *************************************************/ include 'vtlib/thirdparty/network/Request.php';

    /**

    • Provides API to work with HTTP Connection.
    • @package vtlib */ class Vtiger_Net_Client { var $client; var $url; var $response;

      /**

      • Constructor
      • @param String URL of the site
      • Example:
      • $client = new Vtiger_New_Client('http://www.vtiger.com'); */ function __construct($url) { $this->setURL($url); }

      /**

      • Set another url for this instance
      • @param String URL to use go forward */ function setURL($url) { $this->url = $url; $this->client = new HTTP_Request(); $this->response = false; }

      /**

      • Set custom HTTP Headers
      • @param Map HTTP Header and Value Pairs */ function setHeaders($values) { foreach($values as $key=>$value) { $this->client->addHeader($key, $value); } }

      /**

      • Perform a GET request
      • @param Map key-value pair or false
      • @param Integer timeout value */ function doGet($params=false, $timeout=null) { if($timeout) $this->client->_timeout = $timeout; $this->client->setURL($this->url); $this->client->setMethod(HTTP_REQUEST_METHOD_GET);

        if($params) { foreach($params as $key=>$value) $this->client->addQueryString($key, $value); } $this->response = $this->client->sendRequest();

        $content = false; if(!$this->wasError()) { $content = $this->client->getResponseBody(); } $this->disconnect(); return $content; }

      /**

      • Perform a POST request
      • @param Map key-value pair or false
      • @param Integer timeout value */ function doPost($params=false, $timeout=null) { if($timeout) $this->client->_timeout = $timeout; $this->client->setURL($this->url); $this->client->setMethod(HTTP_REQUEST_METHOD_POST);

        if($params) { if(is_string($params)) $this->client->addRawPostData($params); else { foreach($params as $key=>$value) $this->client->addPostData($key, $value); } } $this->response = $this->client->sendRequest();

        $content = false; if(!$this->wasError()) { $content = $this->client->getResponseBody(); } $this->disconnect();

        return $content; }

      /**

      • Did last request resulted in error? */ function wasError() { return PEAR::isError($this->response); }

      /**

      • Disconnect this instance */ function disconnect() { $this->client->disconnect(); } }

Can anyone guild me with this. SMS is not at all going. Outputs in test printfs:

[root@ providers]# cat /var/www/html/vtigercrm/test.txt
url is http://sms.valueleaf.com/sms/user/urllongsms.php?.

[root@ providers]# cat /var/www/html/vtigercrm/test1.txt
String senderid value is 066645.String response value is Y.Message is: Vtiger test on 8.57dest_mobileno is: ArrayResponse is
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html>

<head>
  <title>sms.valueleaf.com</title>

</head>
<frameset rows="100%,*" border="0">
  <frame src="http://203.129.203.254/sms/user/urllongsms.php" frameborder="0" />
  <frame frameborder="0" noresize />
</frameset>

<!-- pageok -->
<!-- 04 -->
<!-- -->
</html>.

Any kind of help will be appreciated. :(

Upvotes: 0

Views: 2853

Answers (1)

BSB
BSB

Reputation: 2468

There is no syntax error in your code. Here is a working script, you can just modify according to your sms provider and configure it.

    private $username;
    private $password;
    private $parameters = array();

    const SERVICE_URI = 'https://trans.springedge.com/api/';

    private static $REQUIRED_PARAMETERS = array(
        array('name' => 'apikey', 'label' => 'API Key', 'type' => 'text'),
        array('name' => 'sender', 'label' => 'Sender ID', 'type' => 'text'),
        array('name' => 'unicode', 'label' => 'Character Set', 'type' => 'picklist', 'picklistvalues' => array('1' => 'Unicode', '0' => 'GSM', 'auto' => 'Auto Detect'))
    );

    public function getName() {
        return 'SpringEdge';
    }

    public function setAuthParameters($username, $password) {
        $this->username = $username;
        $this->password = $password;
    }

    public function setParameter($key, $value) {
        $this->parameters[$key] = $value;
    }

    public function getParameter($key, $defaultvalue = false) {
        if (isset($this->parameters[$key])) {
            return $this->parameters[$key];
        }
        return $defaultvalue;
    }

    public function getRequiredParams() {
        return self::$REQUIRED_PARAMETERS;
    }

    public function getServiceURL($type = false) {
        if ($type) {
            switch (strtoupper($type)) {
                case self::SERVICE_SEND : return self::SERVICE_URI . '/web/send/';
                case self::SERVICE_QUERY : return self::SERVICE_URI . '/status/message/';
            }
        }
        return false;
    }

    protected function prepareParameters() {
        foreach (self::$REQUIRED_PARAMETERS as $requiredParam) {
            $paramName = $requiredParam['name'];
            $params[$paramName] = $this->getParameter($paramName);
        }
        $params['format'] = 'json';
        return $params;
    }

    public function send($message, $tonumbers) {
        if (!is_array($tonumbers)) {
            $tonumbers = array($tonumbers);
        }
        foreach ($tonumbers as $i => $tonumber) {
            $tonumbers[$i] = str_replace(array('(', ')', ' ', '-'), '', $tonumber);
        }

        $params = $this->prepareParameters();
        $params['message'] = $message;
        $params['to'] = implode(',', $tonumbers);

        $serviceURL = $this->getServiceURL(self::SERVICE_SEND);
        $httpClient = new Vtiger_Net_Client($serviceURL);
        $response = $httpClient->doGet($params);
        $rows = json_decode($response, true);

        $numbers = explode(',', $params['to']);
        $results = array();
        $i = 0;

        if ($rows['status'] != 'OK') {
            foreach ($numbers as $number) {
                $result = array();
                $result['to'] = $number;
                $result['error'] = true;
                $result['statusmessage'] = $rows['message'];
                $result['id'] = $rows['data'][$i++]['id'];
                $result['status'] = self::MSG_STATUS_ERROR;
                $results[] = $result;
            }
        }else{
            foreach ($rows['data'] as $value) {
                if (is_array($value)) {
                    $result = array();
                    $result['error'] = false;
                    $result['to'] = $value['mobile'];
                    $result['id'] = $value['id'];
                    $result['statusmessage'] = $rows['message'];
                    $result['status'] = $this->checkstatus($value['status']);
                    $results[] = $result;
                }
            }
        }
        return $results;
    }

    public function checkstatus($status) {
        if ($status == 'AWAITED-DLR') {
            $result = self::MSG_STATUS_PROCESSING;
        } elseif ($status == 'DELIVRD') {
            $result = self::MSG_STATUS_DELIVERED;
        } else {
            $result = self::MSG_STATUS_FAILED;
        }
        return $result;
    }

    public function query($messageid) {
        $params = $this->prepareParameters();
        $params['messageid'] = $messageid;
        $serviceURL = $this->getServiceURL(self::SERVICE_QUERY);
        $httpClient = new Vtiger_Net_Client($serviceURL);
        $response = $httpClient->doGet($params);
        $rows = json_decode($response, true);
        $result = array();
        if ($rows['status'] != 'OK') {
            $result['error'] = true;
            $result['status'] = self::MSG_STATUS_ERROR;
            $result['needlookup'] = 1;
            $result['statusmessage'] = $rows['message'];
        } else {
            $result['error'] = false;
            $result['status'] = $this->checkstatus($rows['data']['0']['status']);
            $result['needlookup'] = 0;
            $result['statusmessage'] = $rows['message'];
        }
        return $result;
    }

    function getProviderEditFieldTemplateName() {
        return 'BaseProviderEditFields.tpl';
    }
}

Save above code as sms_provider_name.php in /modules/SMSNotifier/providers to use.

Upvotes: 1

Related Questions