I need to send order confirmation SMS message to my users via my SMS gateway API in PrestaShop. Is that possible?
I am using the ValueFirst SMS gateway.
Here is my code:
<?php
$username="username";
$password="password";
$to="mobilenumber";
$sender="senderid";
$message="message";
if($username!='' && $password!='' && $to!='' && $sender!='' && $message!='')
{
class sendSms
{
var $serverURL = 'http://api.myvaluefirst.com/psms/servlet/psms.Eservice2';
var $gsmSender = 'MYGSMID';
function GetSenderID()
{
return $this->cdmaNumber;
}
function get_address($user_id,$to)
{
$address_info = sprintf('<ADDRESS FROM="%s" TO="%s" SEQ="%s" />',$user_id,$to,1);
return $address_info;
}
function postdata($url,$data)
{
$objURL = curl_init($url);
curl_setopt($objURL, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($objURL,CURLOPT_POST,1);
curl_setopt($objURL, CURLOPT_POSTFIELDS,$data);
$retval = trim(curl_exec($objURL));
curl_close($objURL);
return $retval;
}
function sendSmsToUser($prefix='',$contents='', $toAddr='',$sms_user_name='',$sms_password='',$sms_user_id='' )
{
$xmlstr ='<!DOCTYPE MESSAGE SYSTEM "http://127.0.0.1/psms/dtd/message.dtd"><MESSAGE><USER USERNAME="%s" PASSWORD="%s"/><SMS UDH=" 0 " CODING=" 1 " TEXT="%s" PROPERTY=" 0 " ID=" 2 ">%s</SMS></MESSAGE>';
$contents = stripslashes($prefix.$contents);
$contents = htmlentities($contents,ENT_COMPAT);
$username = stripslashes($sms_user_name);
$username = htmlentities($username,ENT_COMPAT);
$password = stripslashes($sms_password);
$password = htmlentities($password,ENT_COMPAT);
$user_id = stripslashes($sms_user_id);
$user_id = htmlentities($user_id,ENT_COMPAT);
$xmldata = sprintf($xmlstr,$username,$password,$contents,$this->get_address($user_id,$toAddr));
$data='data='. urlencode($xmldata);
$action='action=send';
$str_response = $this->postdata($this->serverURL,$action.'&'.$data);
$str_request = $this->serverURL.'?'.$action.'&'.$data;
}
}
$mclass = new sendSms();
$mclass->sendSmsToUser("Dear Guest,",$message,$to,$username,$password,$sender);
}
?>
This is my ValueFirst API script. I want to use this script into PrestaShop. How can I do that?
I think this is kinda duplicate with this one : How to integrate msg91 php api with Prestasms or Prestashop?
For instance, create a module at https://validator.prestashop.com/ then add Hooks (function triggered at a certain time automaticly, like on order update) with it.
Related
I'm using the Zillow API in order to get some data from user inputs. So far I've been able to correctly use the API to get the desired data from a single input.
The issue I'm running into is when I try and convert my simple block of code into a function that I can reuse multiple times with multiple inputs.Eventually, I want the user to be able to uploaded a CSV file or something and run this function through multiple inputs.
Below is my code that is functioning properly:
HTML
<form action="logic.php" method="post">
<p>Address: <input type="text" name="address"></p>
<p>City/State: <input type="text" name="csz"></p>
<input type="submit">
</form>
PHP
//API Key
$api_key = 'XXXxxXXX';
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
//Get Address ID From API
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=".$api_key."&address=".$address."&citystatezip=".$citystatezip;
$result = file_get_contents($url);
$data = simplexml_load_string($result);
$addressID = $data->response->results->result[0]->zpid;
//Get Estimate from API (using adressID)
$estimate_url = "http://www.zillow.com/webservice/GetZestimate.htm?zws-id=".$api_key."&zpid=".$addressID;
$estimate_result = file_get_contents($zurl);
$estimate_data = simplexml_load_string($zresult);
$estimate = $zdata->response->zestimate->amount;
echo $estimate;
Now the issue is when I try and wrap both of these up into two separate functions in order to use them for multiple inputs.
$api_key = 'XXXxxXXX';
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
function getAddressID($ad,$cs){
//Get Address ID From API
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=".$api_key."&address=".$ad."&citystatezip=".$cs;
$result = file_get_contents($url);
$data = simplexml_load_string($result);
$addressID = $data->response->results->result[0]->zpid;
return $addressID;
}
$addressID = getAddressID($address, $citystatezip);
function getEstimate($aID){
//Get Estimate from API (using adressID)
$estimate_url = "http://www.zillow.com/webservice/GetZestimate.htm?zws-id=".$api_key."&zpid=".$aID;
$estimate_result = file_get_contents($estimate_url);
$estimate_data = simplexml_load_string($estimate_result);
$estimate = $estimate_data->response->zestimate->amount;
return $estimate;
}
echo getEstimate($addressID); //Calling function doesn't return anything
If essentially I'm doing this same thing as the first PHP example. Why isn't this working from within a function? Did I overlook something?
Ant help on this would be greatly appreciated.
The problem is that you are using the $api_key variable inside both functions, and that variable is not available there. PHP works a bit different then other languages. You can read up on it here: http://php.net/manual/en/language.variables.scope.php
I suggest you extract a function for calling the api. This way you can declare the api key in that function. It also allows you to easier maintain your code (you could improve your api call by adding some error handling or switching to curl or something). The golden rule of a programmer, Don't Repeat Yourself.
The code could look something like this (untested):
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
function callZillow($endpoint, array $params)
{
$params['zws-id'] = 'XXX'; // this would be your api_key
$url = 'http://www.zillow.com/webservice/' . $endpoint . '.htm?' . http_build_query($params);
$result = file_get_contents($url);
return simplexml_load_string($result);
}
function getAddressID($ad, $cs)
{
//Get Address ID From API
$data = callZillow('GetSearchResults', ['address' => $ad, 'citystatezip' => $cs]);
$addressID = $data->response->results->result[0]->zpid;
return $addressID;
}
$addressID = getAddressID($address, $citystatezip);
function getEstimate($aID)
{
//Get Estimate from API (using adressID)
$estimate_data = callZillow('GetZestimate', ['zpid' => $aID]);
$estimate = $estimate_data->response->zestimate->amount;
return $estimate;
}
echo getEstimate($addressID);
This is really annoying me, the php script was working and returning the weather from open weather map but literally all of a sudden the php script takes forever to execute and the following error is produced:
Warning: file_get_contents(http://api.openweathermap.org/data/2.5/weather?lat=&lon=&units=metric&cnt=7&lang=en&key=f38a36af9e4965dd5192ba4282abe070) [function.file-get-contents]: failed to open stream: Connection timed out in /xxx/xxx/public_html/fullweather.php on line 15
Any help would be appreciated. The php script can be viewed below. Only the beginning is important (first 18 lines) but I have included the full thing.
<?php
$lat = $_POST["latitude"];
$lon = $_POST["longitude"];
$url="http://api.openweathermap.org/data/2.5/weather?lat=".$lat."&lon=".$lon."&units=metric&cnt=7&lang=en&key=f38a36af9e4965dd5192ba4282abe070";
// Make call with cURL
$session = curl_init($url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
$json=file_get_contents($url);
$data=json_decode($json,true);
class weatherdata
{
public $temp = "";
public $weather = "";
public $clouds = "";
public $area = "";
public $humidity = "";
public $humidpressure = "";
public $weatherdesc = "";
public $tempmin = "";
public $tempmax = "";
public $windspeed = "";
public $winddirec = "";
}
$data1 = $data['main']['temp'];
$data2 = $data['weather'][0]['main'];
$data3 = $data['clouds']['all'];
$data4 = $data['name'];
$data5 = $data['main']['humidity'];
$data6 = $data['main']['pressure'];
$data7 = $data['weather'][0]['description'];
$data8 = $data['main']['temp_min'];
$data9 = $data['main']['temp_max'];
$data10 = $data['wind']['speed'];
$data12 = $data['wind']['deg'];
$weatherdata = new weatherdata();
$weatherdata->temp = $data1;
$weatherdata->weather = $data2;
$weatherdata->clouds = $data3;
$weatherdata->area = $data4;
$weatherdata->humidity = $data5;
$weatherdata->humidpressure = $data6;
$weatherdata->weatherdesc = $data7;
$weatherdata->tempmin = $data8;
$weatherdata->tempmax = $data9;
$weatherdata->windspeed = $data10;
$weatherdata->winddirec = $data12;
$output[] = $weatherdata;
print(json_encode($output));
?>
I think the API was just down, cause the link is working for me right now.
Try one more time.
May be the API had change it's url by the time. Try to check the documentation for any updated information. I think that they could change it and your code couldnt find because this $url doesn't exist anymore.
i added https instead of http in url and it worked.
so maybe change http in url like this url.
$url="https://api.openweathermap.org/data/2.5/weather?lat=".$lat."&lon=".$lon."&units=metric&cnt=7&lang=en&key=f38a36af9e4965dd5192ba4282abe070";
Edit
Also you should not show your api key to anyone as some one can use it.
I am trying to get the xml rate soap feed from UPS working.
Currently I am getting the error "Wrong version" (__Soapcall Exeption) or "0FailureHard10002The XML document is well formed but the document is not valid1" (Respons from server or php).
I took the example provided in the developers toolkit. I tried everything =>
Change soap version to 1.2
Grab wsdl from remote url instead of on
the disk
I double checked the endpoint and userid, accesskey, pass,
...
Does anyone have a working script ?, or even better can someone correct my mistake :)
Code:
<?php
class UpsRate{
private $access,$userid,$passwd,$wsdl,$operation,$endpointurl;
public function __construct() {
$this->setConfig();
}
public function setConfig($is_test = true){
$this->access = sfConfig::get('app_shipping_ups_access');
$this->userid = sfConfig::get('app_shipping_ups_userid');
$this->passwd = sfConfig::get('app_shipping_ups_password');
$this->wsdl = sfConfig::get('sf_data_dir').'/wsdl/ups/RateWS.wsdl';
$this->operation = "ProcessRate";
$this->endpointurl = $is_test?'https://wwwcie.ups.com/ups.app/xml/Rate':'https://onlinetools.ups.com/ups.app/xml/Rate';
}
private function processRate(){
//create soap request
$option['RequestOption'] = 'Shop';
$request['Request'] = $option;
$pickuptype['Code'] = '01';
$pickuptype['Description'] = 'Daily Pickup';
$request['PickupType'] = $pickuptype;
$customerclassification['Code'] = '01';
$customerclassification['Description'] = 'Classfication';
$request['CustomerClassification'] = $customerclassification;
$shipper['Name'] = 'Trutec';
$shipper['ShipperNumber'] = 'Y5562A';
$address['AddressLine'] = array
(
'Ter rivierenlaan 176',
'',
''
);
$address['City'] = 'Antwerp';
//$address['StateProvinceCode'] = 'MD';
$address['PostalCode'] = '2100';
$address['CountryCode'] = 'BE';
$shipper['Address'] = $address;
$shipment['Shipper'] = $shipper;
$shipto['Name'] = 'Imani Imaginarium';
$addressTo['AddressLine'] = '21 ARGONAUT SUITE B';
$addressTo['City'] = 'ALISO VIEJO';
//$addressTo['StateProvinceCode'] = 'CA';
$addressTo['PostalCode'] = '92656';
$addressTo['CountryCode'] = 'US';
$addressTo['ResidentialAddressIndicator'] = '';
$shipto['Address'] = $addressTo;
$shipment['ShipTo'] = $shipto;
$shipfrom['Name'] = 'Trutec';
$addressFrom['AddressLine'] = array
(
'Ter rivierenlaan 176',
'',
''
);
$addressFrom['City'] = 'Deurne';
//$addressFrom['StateProvinceCode'] = 'MD';
$addressFrom['PostalCode'] = '2100';
$addressFrom['CountryCode'] = 'BE';
$shipfrom['Address'] = $addressFrom;
$shipment['ShipFrom'] = $shipfrom;
$service['Code'] = '03';
$service['Description'] = 'Service Code';
$shipment['Service'] = $service;
$packaging1['Code'] = '02';
$packaging1['Description'] = 'Rate';
$package1['PackagingType'] = $packaging1;
$dunit1['Code'] = 'IN';
$dunit1['Description'] = 'cm';
$dimensions1['Length'] = '5';
$dimensions1['Width'] = '4';
$dimensions1['Height'] = '10';
$dimensions1['UnitOfMeasurement'] = $dunit1;
$package1['Dimensions'] = $dimensions1;
$punit1['Code'] = 'KG';
$punit1['Description'] = 'KG';
$packageweight1['Weight'] = '4';
$packageweight1['UnitOfMeasurement'] = $punit1;
$package1['PackageWeight'] = $packageweight1;
$shipment['Package'] = array( $package1 );
$shipment['ShipmentServiceOptions'] = '';
$shipment['LargePackageIndicator'] = '';
$request['Shipment'] = $shipment;
return $request;
}
public function getRate(){
try {
//nitialize soap client
$client = new SoapClient($this->wsdl , array('soap_version' => 'SOAP_1_1','trace' => 1));
//set endpoint url
$client->__setLocation($this->endpointurl);
//create soap header
$usernameToken['Username'] = $this->userid;
$usernameToken['Password'] = $this->passwd;
$serviceAccessLicense['AccessLicenseNumber'] = $this->access;
$upss['UsernameToken'] = $usernameToken;
$upss['ServiceAccessToken'] = $serviceAccessLicense;
$header = new SoapHeader('http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0','UPSSecurity',$upss);
$client->__setSoapHeaders($header);
//get response
return $client->__soapCall($this->operation ,array($this->processRate()));
}
catch(Exception $ex)
{
echo '<pre>';
return print_r($client->__getLastResponse());
echo '</pre>';
}
}
}
?>
The error notifies that your XML is being correctly formatted but you have included one or more elements that are incompatible. Are you able to dump the XML sent ? This may be easier to determine where the error is being detected.
I wouldn't recommend depending on the examples in the UPS documentation to work, they are for illustrative purposes only and probably have not been updated since the first issue.
I had the same issue, and worked this out:
When I would make test calls, they would work. The endpoint I used for the test calls was
https://wwwcie.ups.com/webservices/Rate
However, when I would change to the live calls, then I would receive the wrong version error. That endpoint is:
https://onlinetools.ups.com/webservices
I reviewed the wsdl document, and found near the end a section that looks like this:
<wsdl:port name="RatePort" binding="tns:RateBinding">
<!-- Production URL -->
<!-- <soap:address location="https://onlinetools.ups.com/webservices/Rate"/> -->
<!-- CIE (Customer Integration Environment) URL -->
<soap:address location="https://wwwcie.ups.com/webservices/Rate"/>
</wsdl:port>
I noticed that the live version endpoint was commented out, so I changed the section as follows:
<wsdl:port name="RatePort" binding="tns:RateBinding">
<!-- Production URL -->
<soap:address location="https://onlinetools.ups.com/webservices/Rate"/>
<!-- CIE (Customer Integration Environment) URL -->
<!--<soap:address location="https://wwwcie.ups.com/webservices/Rate"/>-->
</wsdl:port>
I'm not sure this will help anyone else, but this ended up resolving my issues.
I'm trying to use PHP and SoapClient to utilize the UPS Ratings web service. I found a nice tool called WSDLInterpreter to create a starting point library for creating the service requests, but regardless what I try I keep getting the same (non-descriptive) error:
EXCEPTION=SoapFault::__set_state(array(
'message' => 'An exception has been raised as a result of client data.',
'string' => '',
'code' => 0,
Um ok, what the hell does this mean?
Unlike some of the other web service tools I have implemented, the UPS Soap wants a security block put into the header. I tried doing raw associative array data but I wasn't sure 100% if I was injecting the header part correctly.
Using the WSDLInterpreter, it pulls out a RateService class with a ProcessRate method that excepts it's own (instance) datastructure for the RateRequest and UPSSecurity portions, but all of the above generates that same error.
Here's a sample of the code that I'm using that calls classes defined by the interpreter:
require_once "Shipping/UPS/RateService.php"; // WSDLInterpreter class library
class Query
{
// constants removed for stackoverflow that define (proprietary) security items
private $_upss;
private $_shpr;
// use Interpreter code's RateRequest class to send with ProcessRate
public function soapRateRequest(RateRequest $req, UPSSecurity $upss = null)
{
$res = false;
if (!isset($upss)) {
$upss = $this->__getUPSS();
}
echo "SECURITY:\n" . var_export($upss, 1) . "\n";
$upsrs = new RateService(self::UPS_WSDL);
try {
$res = $upsrs->ProcessRate($req, $upss);
} catch (SoapFault $exception) {
echo 'EXCEPTION=' . var_export($exception, 1) . "\n";
}
return $res;
}
// create a soap data structure to send to web service from shipment
public function getRequestSoap(Shipment $shpmnt)
{
$qs = new RateRequest();
// pickup information
$qs->PickupType->Code = '01';
$qs->Shipment->Shipper = $this->__getAcctInfo();
// Ship To address
$qs->Shipment->ShipTo->Address->AddressLine = $this->__getAddressArray($shpmnt->destAddress->address1, $shpmnt->destAddress->address2);
$qs->Shipment->ShipTo->Address->City = $shpmnt->destAddress->city;
$qs->Shipment->ShipTo->Address->StateProvinceCode = $shpmnt->destAddress->state;
$qs->Shipment->ShipTo->Address->PostalCode = $shpmnt->destAddress->zip;
$qs->Shipment->ShipTo->Address->CountryCode = $shpmnt->destAddress->country;
$qs->Shipment->ShipTo->Name = $shpmnt->destAddress->name;
// Ship From address
$qs->Shipment->ShipFrom->Address->AddressLine = $this->__getAddressArray($shpmnt->origAddress->address1, $shpmnt->origAddress->address2);
$qs->Shipment->ShipFrom->Address->City = $shpmnt->origAddress->city;
$qs->Shipment->ShipFrom->Address->StateProvinceCode = $shpmnt->origAddress->state;
$qs->Shipment->ShipFrom->Address->PostalCode = $shpmnt->origAddress->zip;
$qs->Shipment->ShipFrom->Address->CountryCode = $shpmnt->origAddress->country;
$qs->Shipment->ShipFrom->Name = $shpmnt->origAddress->name;
// Service type
// TODO cycle through available services
$qs->Shipment->Service->Code = "03";
$qs->Shipment->Service->Description = "UPS Ground";
// Package information
$pkg = new PackageType();
$pkg->PackagingType->Code = "02";
$pkg->PackagingType->Description = "Package/customer supplied";
// dimensions
$pkg->Dimensions->UnitOfMeasurement->Code = $shpmnt->dimensions->dimensionsUnit;
$pkg->Dimensions->Length = $shpmnt->dimensions->length;
$pkg->Dimensions->Width = $shpmnt->dimensions->width;
$pkg->Dimensions->Height = $shpmnt->dimensions->height;
$pkg->PackageServiceOptions->DeclaredValue->CurrencyCode = "USD";
$pkg->PackageServiceOptions->DeclaredValue->MonetaryValue = $shpmnt->dimensions->value;
$pkg->PackageServiceOptions->DeclaredValue->CurrencyCode = "USD";
$pkg->PackageWeight->UnitOfMeasurement = $this->__getWeightUnit($shpmnt->dimensions->weightUnit);
$pkg->PackageWeight->Weight = $shpmnt->dimensions->weight;
$qs->Shipment->Package = $pkg;
$qs->CustomerClassification->Code = 123456;
$qs->CustomerClassification->Description = "test_rate_request";
return $qs;
}
// fill out and return a UPSSecurity data structure
private function __getUPSS()
{
if (!isset($this->_upss)) {
$unmt = new UsernameToken();
$unmt->Username = self::UPSS_USERNAME;
$unmt->Password = self::UPSS_PASSWORD;
$sat = new ServiceAccessToken();
$sat->AccessLicenseNumber = self::UPSS_ACCESS_LICENSE_NUMBER;
$upss = new UPSSecurity();
$upss->UsernameToken = $unmt;
$upss->ServiceAccessToken = $sat;
$this->_upss = $upss;
}
return $this->_upss;
}
// get our shipper/account info (some items blanked for stackoverflow)
private function __getAcctInfo()
{
if (!isset($this->_shpr)) {
$shpr = new ShipperType();
$shpr->Address->AddressLine = array(
"CONTACT",
"STREET ADDRESS"
);
$shpr->Address->City = "CITY";
$shpr->Address->StateProvinceCode = "MI";
$shpr->Address->PostalCode = "ZIPCODE";
$shpr->Address->CountryCode = "US";
$shpr = new ShipperType();
$shpr->Name = "COMPANY NAME";
$shpr->ShipperNumber = self::UPS_ACCOUNT_NUMBER;
$shpr->Address = $addr;
$this->_shpr = $shpr;
}
return $this->_shpr;
}
private function __getAddressArray($adr1, $adr2 = null)
{
if (isset($adr2) && $adr2 !== '') {
return array($adr1, $adr2);
} else {
return array($adr1);
}
}
}
It doesn't even seem to be getting to the point of sending anything over the Soap so I am assuming it is dying as a result of something not matching the WSDL info. (keep in mind, I've tried sending just a properly seeded array of key/value details to a manually created SoapClient using the same WSDL file with the same error resulting)
It would just be nice to get an error to let me know what about the 'client data' is a problem. This PHP soap implementation isn't impressing me!
I know this answer is probably way too late, but I'll provide some feedback anyway. In order to make a custom SOAP Header you'll have to override the SoapHeader class.
/*
* Auth Class to extend SOAP Header for WSSE Security
* Usage:
* $header = new upsAuthHeader($user, $password);
* $client = new SoapClient('{...}', array("trace" => 1, "exception" => 0));
* $client->__setSoapHeaders(array($header));
*/
class upsAuthHeader extends SoapHeader
{
...
function __construct($user, $password)
{
// Using SoapVar to set the attributes has proven nearly impossible; no WSDL.
// It might be accomplished with a combined SoapVar and stdClass() approach.
// Security Header - as a combined XSD_ANYXML SoapVar
// This method is much easier to define all of the custom SoapVars with attributes.
$security = '<ns2:Security xmlns:ns2="'.$this->wsse.'">'. // soapenv:mustUnderstand="1"
'<ns2:UsernameToken ns3:Id="UsernameToken-49" xmlns:ns3="'.$this->wsu.'">'.
'<ns2:Username>'.$user.'</ns2:Username>'.
'<ns2:Password Type="'.$this->password_type.'">'.htmlspecialchars($password).'</ns2:Password>'.
'</ns2:UsernameToken>'.
'</ns2:Security>';
$security_sv = new SoapVar($security, XSD_ANYXML);
parent::__construct($this->wsse, 'Security', $security_sv, false);
}
}
Then call the upsAuthHeader() before the soap call.
$client = new SoapClient($this->your_ups_wsdl,
array('trace' => true,
'exceptions' => true,
'soap_version' => SOAP_1_1
)
);
// Auth Header - Security Header
$header = new upsAuthHeader($user, $password);
// Set Header
$client->__setSoapHeaders(array($header));
I can now send an SMS via kannel. However this is done via headers eg:
header("Location:http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");
I want to send an sms via a php function and I got the code below online but it doesn't work. (Kannel smsbox log shows no request):
function sendSmsMessage($in_number, $in_msg)
{
$url = '/cgi-bin/sendsms?username=' . CONFIG_KANNEL_USER_NAME
. '&password=' . CONFIG_KANNEL_PASSWORD
. '&charset=UCS-2&coding=2'
. "&to={$in_number}"
. '&text=' . urlencode(iconv('utf-8', 'ucs-2', $in_msg));
$results = file('http://'
. CONFIG_KANNEL_HOST . ':'
. CONFIG_KANNEL_PORT . $url);
}
Is there something wrong? I tried replacing the CONFIG_KANNEL_USER_NAME and the rest with the actual values but it still doesn't work. Open to suggestions.
I used cURL and it works 100% okay. file_get_contents does not work for me because I want to pass variables to the kannel url and file_get_contents does not process variables coz it insists on using single quotes(php treats it as a string value) instead of double quotes(php will parse the string checking for variables etc).
Here is what i am currently doing assuming you already have your variables initialized somewhere:
$textmsg="Hello Stackoverflow Users!";
$cellphone_number = "+254xxxxxxx"
$encmsg=urlencode($textmsg);
$ch= curl_init();
curl_setopt($ch, "http://localhost:13013/cgi-bin/sendsms?username=xxxxx&password=xxxxx&to=$cellphone_number&text=$encmsg");
curl_exec($ch);
curl_close($ch);
This will work for the simple task of telling kannel to send an sms to a number. Took me a while to realize curl does not recognize spaces and special characters :-).
My friend and I from Ndola, Zambia are using ubuntu 11.04 to run kannel_1.4.3. It works perfectly way in sending and receiving sms. The code below had to be edited for it to send more that 70 characters. My friend and I struggled to figure out that there was a small error in the line '&charset=UCS-2&coding=2'. The correct line should be '&charset=UCS-2&encoding=2'. So the code should appear as below:
function sendSmsMessage($in_number, $in_msg)
{
$url = '/cgi-bin/sendsms?username=' . CONFIG_KANNEL_USER_NAME
. '&password=' . CONFIG_KANNEL_PASSWORD
. '&charset=UCS-2&encoding=2'
. "&to={$in_number}"
. '&text=' . urlencode(iconv('utf-8', 'ucs-2', $in_msg));
Using curl:
curl_init("http://$gw_host:$gw_port/cgi-bin/sendsms?username=$gw_user&password=$gw_pass&to=$to&from=$shortcode&smsc=$smsc&dlr-mask=$dlrmask&binfo=$shortcode&text=$message");
Replace the various variables/parameters with your values such as:
$gw_host=127.0.0.1
$gw_port=13xx3
etc.
If you're attempting to trigger a URL loading in the background (rather than by re-directing the user to the URL), you need to use something like cURL or perhaps even file_get_contents.
For example, if your set up has fopen URL wrappers enabled, you could simply use:
$response = file_get_contents("http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");
Irrespective, it's hard to know why the function you found won't work without some additional debug information. (If CONFIG_KANNEL_HOST is defined as "localhost" and CONFIG_KANNEL_PORT is defined as 13013 then it's effectively doing the same thing, albeit with additional character set operations.)
Not to ressucitate an ancient question, but for posteriority and others searching for the same thing:
[root#sat2 tools]# cat kannel-send.php
<?php
function send_sms($msgid, $numto, $msgtext, $smsc = "smsc-default", $dlrmask = 63)
{
$sendsmsurl_prefix = "http://localhost:13013/cgi-bin/sendsms";
$dlrurl_prefix = "http://localhost/tools/kannel-receive.php";
$username = "user";
$password = "pass";
# fix number to what carriers expect
$numto = preg_replace('/^0/', '', $numto);
$numto = preg_replace('/^\+55/', '', $numto);
$numto = "0" . $numto;
if (!$msgid) $dlrmask = 0;
$dlrurl_params = array(
"type" => "dlr",
"timesent" => "%t",
"smsc" => "%i",
"uuid" => "%I",
"fid" => "%F",
"dlr-cod" => "%d",
"reply" => "%A",
"msgid" => $msgid,
"text" => "%a",
"to" => "%P",
"from" => "%p",
"origsmsc" => "%f",
);
$dlrurl = $dlrurl_prefix . "?" . urldecode(http_build_query($dlrurl_params));
$sendsmsurl_params = array(
"username" => $username,
"password" => $password,
"to" => $numto,
"dlr-mask" => $dlrmask,
"dlr-url" => $dlrurl,
"smsc"=> $smsc,
"text" => $msgtext,
);
$sendsmsurl = $sendsmsurl_prefix . "?" . http_build_query($sendsmsurl_params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $sendsmsurl);
$bogus = curl_exec($ch);
$ret = curl_error($ch);
curl_close($ch);
return $ret == "";
}
?>
And you could have this other one to receive sms and store it to mysql:
[root#sat2 tools]# cat kannel-receive.php
<?php
$debug = false;
$link = null;
function dbconnect()
{
global $link, $debug;
if ($link && mysql_ping($link))
return;
if ($debug) echo "Conectando ao banco de dados\n";
// TODO: criar um usuario de banco especifico pra isso
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'dbname';
$link = mysql_connect($host, $user, $pass, true);
if (!$link){
if ($debug) echo "Can't connect to mysql: " . mysql_error() . "\n";
} else {
mysql_select_db($db, $link);
}
return;
}
function esc($str)
{
global $link;
return mysql_real_escape_string($str, $link);
}
if ($debug) {
echo "<br>Kannel inbound sms event:<br>\n";
var_dump($_GET);
}
dbconnect();
if ($_GET['type'] == "inbsms") {
$_GET['from'] = preg_replace('/^(\+55|0)/', '', $_GET['from']);
$sql = "INSERT INTO notificacao (tipo, endereco, mensagem, device,
dataEvento, situacao)
VALUES ('%s', '%s','%s','%s','%s','%s')";
$sql = sprintf($sql, 'sms', esc($_GET['from']), esc($_GET['text']),
esc($_GET['smsc']), esc($_GET['timesent']), "received");
} elseif ($_GET['type'] == "dlr") {
switch (esc($_GET['dlr-cod'])) {
case "1":
$sql = "UPDATE notificacao SET
situacao = 'confirmed',
dataConfirmacao = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
case "8":
$sql = "UPDATE notificacao SET
situacao = 'sent',
device = '{$_GET['smsc']}',
dataEvento = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
case "16":
$sql = "UPDATE notificacao SET
situacao = 'failed',
device = '{$_GET['smsc']}',
razaofalha = '{$_GET['reply']}',
dataEvento = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
}
}
if ($debug) echo "sql: $sql\n";
$result = mysql_query($sql, $link);
if (!$result) {
if ($debug) echo "Erro sql: " . mysql_error() . "\n";
}
?>
This one doubles as a SMS receiver and a SMS-Delivery-Notification receiver (in that case it updates a record on the database that was put there when sending the sms, to confirm it was received).
It's used for DLR because I send the URL for that when sending the SMS (and set the DLR mask asking for confirmation), but for inbound SMS you have to configure your kannel.conf to use it (you can have many sms-service, this is just an example of a catch-all one:
[...]
group = sms-service
keyword = default
get-url = "http://localhost/tools/kannel-receive.php?type=inbsms&text=%a×ent=%t&from=%p&to=%P&smsc=%i&uuid=%I&delivery=%d&service=%n&encoding=%c&class=%m&mwi=%M&charset=%C&udh=%u&dcs=%O&origsmsc=%f"
catch-all = yes
max-messages = 0
accept-x-kannel-headers = true
concatenation = yes
omit-empty = yes
[...]
Sorry for some texts in portuguese, but you can get the picture.
//php code file name is test2.php.before that,you must install php5-curl on ubuntu14