Integrate API

Integrate API - Header

Tuesday, July 23, 2013

How to integrate Nexmo SMS API in php

Nexmo.com is world top ranked SMS API provider in recent days. Customers choose to use because of cheap price, efficient and reliable SMS delivery and easily trackable services detail. In addition they have very fast customer service response of customer/developer enquiry.

Integration of Nexmo SMS API is very easy. Firstly go to http://www.nexmo.com and register. You will get some free SMS credit(currently its 10 credit) by which you can test SMS sending for integration with your application. Moreover, they have sample codes in open source language-PHP. They have ready made classes for you which are downloadable from here[amin]. Here i have created a small sample script for easy integration of you.

First i have created a page named send-sms-start.php with the following line of codes.
<form method="post" action="send-sms.php">
  Reciepent Phone No: <input type="text" name="phone_no"><br/>
  SMS Text: <input type="text" name="sms_body">
  <input type="submit" value="Send SMS">
</form>
i have taken two input fields named phone_no and sms_body. along with a submit button for next page. in addition, i have used a form all around which method is post with action send-sms.php. When you run this page you get this form. Now enter reciepent mobile number, SMS text and press "Send SMS" button. This form will post data into send-sms.php page.

Now i create another page named send-sms.php(using old API)
<?php
include ( "NexmoMessage.php" ); //Downloaded class from nexmo website.

/*
  This function will prepare sms sending status and return
  Call this function after send sms as $info = $nexmo_sms->sendRequestCustomByAmin( $data );
  @input:
    $info ($info = $nexmo_sms->sendRequestCustomByAmin( $data );)
  @output:
    $sms_status= Array([to]=>2343239, [errortext]=>Unroutable message - rejected, [status]=>6,
                      [clientref]=>71, [network]=>NG-FIXED); //For Failed SMS
    $sms_status= Array([to]=>8801771240022, [messageprice]=>0.007, [custom-field]=>33,
                      [messageid]=>0200000009D29829, [remainingbalance]=>11.20, [network]=>47001); //For Successful SMS
    More Response codes are: https://www.nexmo.com/documentation/#response
)
*/
function prepare_sms_send_status($info)
{
  $sms_status=array();
  foreach($info as $key=>$val):
    if($key=="messages")
 $sms_data=$val[0];
  endforeach;
  foreach($sms_data as $key3=>$val3):
    $sms_status[$key3]=$val3;  
  endforeach;
  return $sms_status;
}

// Step 1: Declare new NexmoMessage.
$api_key="your-key";  //api key from TEST/Live ACCOUNT created at Nexmo.com
$api_secret="your-secret";  //api secret from TEST/Live ACCOUNT created at Nexmo.com
$sender_name="Amin"; //you can set any name here(11 character maximum)

$nexmo_sms = new NexmoMessage("$api_key", "$api_secret"); //Create class object

// Step 2: Use sendRequest method to send a message. 
//key value pair SMS Parameters: https://www.nexmo.com/documentation/#how
$data['from']=$sender_no;//"Member's mobile no"; //Required. Sender address could be alphanumeric (Ex: from=MyCompany20), restrictions may apply depending on the destination see our FAQs.
$data['to']=$sms_receipent_no;//Required. Mobile number in international format and one recipient per request. Ex: to=447525856424 or to=00447525856424 when sending to UK
$data['type']="text"; //Optional. This can be omitted text (default), unless sending a Binary (binary), WAP Push (wappush), Unicode message (unicode), vcal (vcal) or vcard (vcard).
$data['text']= urlencode($sms_body); //Required when type='text'. Body of the text message (with a maximum length of 3200 characters), UTF-8 and URL encoded value. Ex: "Déjà vu" content will be "D%c3%a9j%c3%a0+vu"
$data['status-report-req']="1"; //Optional. Set to 1 if you want to receive a delivery report (DLR) for this request. Make sure to configure your "Callback URL" in your "API Settings"
$data['client-ref']="$sms_history_table_id"; //Optional. Include any reference string for your reference. Useful for your internal reports (40 characters max).
$info = $nexmo_sms->sendRequest( $data );

// Step 3: Display an overview of the message
$sms_status=prepare_sms_send_status($info);
if($sms_status["status"]==0)
  echo "SMS Send Successfully";
else
  echo "Error in SMS sending. Please check detail.";
  
echo "<pre>";
print_r($sms_status);
echo "</pre>";

/*
  this function will prepare and return sms status 
  @input:
    $info ($info = $nexmo_sms->sendRequest( $data );)
  @output:
    $sms_status= Array([to]=>2343239, [errortext]=>Unroutable message - rejected, [status]=>6,
                      [clientref]=>71, [network]=>NG-FIXED); //For Failed SMS
    $sms_status= Array([to]=>8801771240022, [messageprice]=>0.007, [custom-field]=>33,
                      [messageid]=>0200000009D29829, [remainingbalance]=>11.20, [network]=>47001); //For Successful SM
More Response codes are: https://www.nexmo.com/documentation/#response
)
*/
function prepare_sms_send_status($info)
{
  if($_SERVER["SERVER_NAME"]=="localhost") //for local development.
    return array('status'=>'0', 'messageid'=>time());
  $sms_status=array();
  foreach($info as $key=>$val):
    if($key=="messages")
 $sms_data=$val[0];
  endforeach;
  foreach($sms_data as $key3=>$val3):
    $sms_status[$key3]=$val3;  
  endforeach;
  return $sms_status;

}

?>
Please note that, prepare_sms_send_status() function is created by me and not available in nexmo.com class(NexmoMessage.php). You can use it for more specific SMS status information.

Now i create another page named send-sms.php(using old API)
<?php
$url = 'https://rest.nexmo.com/sms/json?' . http_build_query([
        'api_key' => $_POST['api_key'],
        'api_secret' => $_POST['api_secret'],
        'to' => $_POST['sms_to'],
        'from' => $_POST['sender_id'],
        'text' => $_POST['sms_body']
    ]);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$response_arr = json_decode($response,true);
$sms_info=$response_arr['messages'][0];    //print_r($sms_info);

if($sms_info['status']==0)
{
  echo "SMS Sent to $_POST[sms_to] successfully.<br />";
  echo "SMS ID: ".$sms_info['message-id']."<br />";
  echo "Client Ref: ".$sms_info['client-ref']."<br />";
  echo "Remaining Balance: ".$sms_info['remaining-balance']."<br />";
  echo "SMS Cost: ".$sms_info['message-price']."<br />";
  echo "Network: ".$sms_info['network']."<br />";
}
else
{
  echo "Error while sending sms";
  echo "SMS Status: ".$sms_info['status']."<br />";
  echo "Error: ".$sms_info['error-text']."<br />";
}


Error & Solution:
Error: "Illegal Sender Address - rejected" while sending SMS to any inbound number (USA/Canada)
Solution: you are no longer allowed to send SMS to inbound number purchased for USA or Canada since late 2013. SMS only allowed from US/Canada phone number. here are some details. Instead, if you need to accept SMS from any country then you have to use AU or Sweden international number.

Error: Invalid sender id. Sometimes you get different sender id then you set while sending SMS.
Error description: There are tons of operator all around the world. Moreover, you can't guarantee your sender id will be 100% accurate for all operator all time(specially for non-alpha numeric number, i.e phone/mobile number). You might get for same operator it works fine last week but now it shows different sender id.
Solution: There are no easy concrete solution for such cases. First of all open a ticket in nexmo.com and report them like "last week it was fine but now shows different sender id for same recipient number". nexmo guys are superb in communication but if they failed to provide you solution and shows you some reason which can't make you happier. Test with another api key and secret of another account. if you get correct sender id for same recipient inform them(mention you have tested with another api key and secret and get good luck) and they will fix it. In contrast, if still sender id is incorrect, you have to test with another SMS API provider. i have tested infobip and cm.nl SMS API to send same SMS to same recipient and receive correct sender id. Inform nexmo support guys instantly, you have tested with other system and works accurately. Nexmo support guys will forward your complain to technical guys and your problem will be solved soon.

Monday, July 22, 2013

How to integrate infobip SMS API in PHP

Now a days infobip.com SMS API becomes popular due to their supurb service. You can integrate their SMS service with your website using their API. You can get detail instructions here.

php code is here for your reference:

infoBipSMS.php Class:
<?php
class infoBipSMS {
/*************** http://www.infobip.com/messaging/connectivity/apis ************************/
// InfoBip account credentials
private $infobip_username = '';
private $infobip_password = '';

/**
* @var string InfoBip server URI
*
*/
var $nx_uri = 'http://api.infobip.com/api/v3/sendsms/xml';

function infoBipSMS ($infobip_username, $infobip_password) {
$this->infobip_username = $infobip_username;
$this->infobip_password = $infobip_password;
}

/**
* @return: 
Status Vale Description
AUTH_FAILED - 1 Invalid username or password
XML_ERROR - 2 Incorrect XML format
NOT_ENOUGH_CREDITS - 3 Not enough credits in user account
NO_RECIPIENTS - 4 No good recipients
GENERAL_ERROR - 5 Error in processing your request
SEND_OK > 0 Number of recipients to which message was sent
*
*/
function send_sms_infobip($sender_no_with_plus, $recipient_no_with_plus, $sms_body, $msg_id="")
{
if(substr($sender_no_with_plus,0,1)!="+")
 $sender_no_with_plus="+".$sender_no_with_plus;
if(substr($recipient_no_with_plus,0,1)!="+")
 $recipient_no_with_plus="+".$recipient_no_with_plus;
$msg_id=($msg_id=="")?time():$msg_id;
//  BUSYBEE's POST URL 
//$postUrl  = "http://193.105.74.59/api/sendsms/xml";
$postUrl  = "http://api.infobip.com/api/v3/sendsms/xml";

//  XML-formatted data
$infobip_username=$this->infobip_username;
$infobip_password=$this->infobip_password;
$no_of_sms_will_send=ceil(strlen($sms_body)/160);
for($i=0;$i<$no_of_sms_will_send;$i++)
{
$sms_part=substr($sms_body,0,160);
if(strlen($sms_body)>160)
   $sms_body=substr($sms_body,160);
$xmlString = "
<SMS> 
 <authentification> 
<username>$infobip_username</username> 
<password>$infobip_password</password> 
 </authentification> 
 <message> 
<sender>$sender_no_with_plus</sender> 
<text>$sms_part</text> 
<flash></flash>
<type></type> 
<wapurl></wapurl> 
<binary></binary> 
<datacoding></datacoding> 
<esmclass></esmclass> 
<srcton></srcton> 
<srcnpi></srcnpi> 
<destton></destton> 
<destnpi></destnpi> 
<ValidityPeriod>23:59</ValidityPeriod> 
 </message> 
 <recipients> 
<gsm messageId=\"$msg_id\">$recipient_no_with_plus</gsm> 
 </recipients> 
</SMS> ";

//echo $xmlString;
 
//  previously formatted XML data becomes value of "XML" POST variable 
$fields  = "XML=" . urlencode($xmlString); 
 
//  in this example, POST request was made using PHP's CURL 
$ch  = curl_init(); 
curl_setopt($ch,  CURLOPT_URL, $postUrl); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS,  $fields); 
 
//  response of the POST request 
$response  = curl_exec($ch);
curl_close($ch); 
}

//  write out the response 
return $response;

}

}

And here is send_sms_start.php file:
<form method="post" action="send_sms.php">
  Infobip Username: <input name="username" type="text" value="user-name"><br/>
  Infobip Password: <input name="password" type="text" value="password"><br/><br /><br />

  Sender No: <input name="sender_no" type="text" value="+my-sender-no"><br/>
  Recipient No: <input type="text" name="recipient_no" value="+recipient-no"><br/>
  SMS Text: <input type="text" name="sms_body">
  <input type="submit" value="Send SMS">

</form>


Really simple and easy. right? Lets concentrate how to customize for different cases:

1. How to send Same SMS to multiple recipient?
=> in xml portion add as much recipient no as you need in new line <gsm>987654321</gsm> here i use 2 recipient number but you can add as much as you need.

2. Can i send more then 160 character long SMS?
=> Infobip currently don't support SMS with more then 160 character. But using this class (code written earlier of this page) code you will be able to send any length SMS. I actually used a very simple technique (chunk SMS text by 160 character and send separately)

All variables are self explanatory. so you can easily customize those. if you have any further question please feel free to ask by post comment here.

Error and solution:
Error: For a long SMS around 400 character long why i receive only last chunk(divide sms character into 160 character chunk) of this SMS?
Solution: I found that, i have used & in that long 400 character SMS. when i remove & from SMS it works accurately. instead of use & now i use &amp; and works fine. So before send sms text to infobip treat SMS text by htmlspecialchars() function.