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.

16 comments:

  1. Hey there. I don't know much coding but I want to implement the Nexmo API in my Wordpress-based website and I am stuck, really stuck. Your blog really brings me close, but I am unable to create and execute the php part of your article. Can you tell me how can I implement his code in Wordpress. I really would appreciate your help. Thanks.

    ReplyDelete
    Replies
    1. Actually i don't have wordpress experience that much. Don't you able to create and execute php part of my article? what error do you receive and in which step? please let me know.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. hi, i'm getting this error "Fatal error: Call to private method NexmoMessage::sendRequest() from context '' in /send-sms.php on line 21"
    Please help

    ReplyDelete
    Replies
    1. So you use NexmoMessage class as static. so far i remember, static class works with PHP version 5 or higher. Is your PHP version higher or equal to 5?
      Would you please paste here few more lines of code. specially sendRequest function inside NexmoMessage class.

      Delete
    2. Hi,

      Am Using PHP version 5.3 , But same error is coming , can you give quick reply

      Delete
  4. is it work locally ?? i mean on xampp ???

    ReplyDelete
    Replies
    1. yes it also works in local environment. in that case, please make sure curl is on in php settings.

      Delete
  5. got this Error!
    Error in SMS sending. Please check detail.
    Array
    (
    [to] => 923158463969
    [status] => 6
    [errortext] => Unroutable message - rejected
    )

    ReplyDelete
  6. Receiver phone number is supported by Nexmo as recipient. You Can find detail athttps://nexmo.zendesk.com/entries/22136611-What-does-Error-11-Unroutable-mean-

    From my past experience I found nexmo token response is perfect. They are really good in support.

    ReplyDelete
  7. Hi Guys ,

    I will use the above code, But i have Fatal error: Call to private method NexmoMessage::sendRequest() from context '' in E:\xampp\htdocs\Nexmo\send-sms.php on line 45.

    Any one can give solution for this

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Great article, an excellent start for anyone to use Nexmo SMS

    Free Your Way

    ReplyDelete
  10. Nice post it is very useful for all. It is Quite Simple to Integrate Bulk SMS API in PHP, all you need to do . As it is instant delivery users can get the respective codes from API panel within a fraction of seconds.

    ReplyDelete
  11. Thanks for sharing. A Bulk SMS API provider makes it possible for companies to be available and visible to their prospective customers by sending them detailed and promotional messages about their products and services.

    ReplyDelete
  12. Bulk SMS messaging is that businesses and organizations can make use of one or more solutions to send and receive SMS messages, namely; a mobile phone application, a software program, a web interface, or integrate an Bulk SMS API with their website or system.

    ReplyDelete