Integrate API

Integrate API - Header

Sunday, December 15, 2013

How to get oAuth credentials from cloud.google.com

You will need oAuth credentials for many different applications. In order to use/inegrate google service like Google Calendar, Invite Gmail Contact Friends and ton others you need oAuth credentials like Client ID & Secret, Web Origin & Redirect URI. Here i show in very short how do you get oAuth 2.0 credentials in less then 5 minutes.

  1. Go to https://cloud.google.com/
  2. Click "Get Started"
  3. Enter a Project Name here(any name), copy and save your project id
  4. you are now entered into your project. in left menu < your-project means you are inside your project.
  5. In left menu click API & Auth->APIs. Turn ON(right side of page) Calendar API
  6. In left menu Click API & Auth->Registered Apps. Enter a name here(anything). Platform: Web Application. Click Register. Click "OAuth 2.0 Client ID". Enter http://www.only-domain.com as Web Origin and http://www.only-domain.com/testoAuth/path-to-dir/test-oauth.php as redirect URI. Click "Generate". You will get here Client ID and Secret. Click Download JSON to get all info at once.
  7. (Optional)in left menu click "Consent Screen". Enter information you wish to use.

Tuesday, October 8, 2013

How to integrate Paypal Express Checkout in php

Paypal is first choice for any developer and customer for online transaction. For php developer i am going to write some helpful tips which might help them in Paypal integration in php. I know developer have many questions in their mind and face lot of trouble while integrate. Here i start discussion of few topics with their solution.

If you do not have basic understanding of pyapal express checkout please have a look.
How to take off all shipping info from paypal express checkout
=> Do NOT use the following parameter in your $nvpstr.
&L_SHIPPINGOPTIONAMOUNT1=8.00&L_SHIPPINGOPTIONlABEL1=UPS Next Day Air&L_SHIPPINGOPTIONNAME1=UPS Air&L_SHIPPINGOPTIONISDEFAULT1=true&L_SHIPPINGOPTIONAMOUNT0=3.00&L_SHIPPINGOPTIONLABEL0=UPS Ground 7 Days&L_SHIPPINGOPTIONNAME0=Ground&L_SHIPPINGOPTIONISDEFAULT0=false
&INSURANCEAMT=1.00&INSURANCEOPTIONOFFERED=true&CALLBACK=https://www.ppcallback.com/callback.pl
&SHIPPINGAMT=8.00&SHIPDISCAMT=-3.00&TAXAMT=2.00
And make sure your total amount is exactly equal to item amount
$nvpstr.="&MAXAMT=".(string)$maxamt."&AMT=".(string)$amt."&ITEMAMT=".(string)$itemamt;

I want to show shipping info in pypal but do not want to charge for shipping in paypal
=> Not prompt payers for shipping address in paypal. Accepted values:
0 – prompt for an address, but doesn't require one
1 – do not prompt for an address
2 – prompt for an address, and require one(set as necessary field)

I want to show shipping address and charge in paypal and want to charge for shipping in paypal
=> Use &SHIPPINGAMT=## parameter in $nvpstr and &NOSHIPPING=0. Make sure your total amount is equal to sum of item amount and shipping charge.

How to Add my Logo in paypal page during payment
=> Add &LOGOIMG=https://www.../YourLogo.gif in $nvpstr variable.

Where from i know Key Pair value parameter detail?
=> Click here to to get detail of all parameter used in Express Checkout

What is DoExpressCheckoutPayment and SetExpressCheckout
=> In order to use Express Checkout, you would call SetExpressCheckout API. where you specify the details of the products, amounts, and the RETURNURL.
Once the buyer agreed to your purchase, he/she is redirected back to the RETURNURL URL you specified.
Now you show the order confirmation, and call the GetExpressCheckoutDetails API
When calling GetExpressCheckoutDetails, supply the token. In the GetExpressCheckoutDetails API response you'll find a PayerID.
Now you're ready to call DoExpressCheckoutPayment, and charge the buyer. Remember to include both the token and the payerID when calling DoExpressCheckoutPayment.

Security header is not valid
=> Check your API_ENDPOINT and PAYPAL_URL variable string. For Live transaction there should not be ".sandbox" in both string.

More about Paypal Error & Solutions are here.

Friday, August 30, 2013

How to integrate CM.NL SMS API

http://www.cmtelecom.com is one of the largest worldwide SMS provider company who provide two different services named BUSINESS and ELITE. Depending upon your SMS volume choose right package for you. Here is how those two services you will integrate with your own application.

From another view, CM.NL provide two different types of Test Account(may be same for Live)
1. SMPP: http://docs.cm.nl/SMPP.pdf
2. HTTP: http://docs.cm.nl/http_MT.pdf
3. CM Direct: http://docs.cm.nl/Technische-Documentatie-CMDirect.pdf (Detail)

CM Direct:
First of all go to: here and create an account with your email address, company name and phone number. Once you have successfully create your account they will send you a verification email link. after verify your email(they use mobile number verification as well) please log in to system using email address and phone number. every time when you attempt to log in they will send you a verification code to your phone number you have used during registration. After log in, you can see your current credit middle top right corner like Current credit: 74 Messages (Updated to Fri 30 Aug 02:03). Usually cmtelecom provide 100 free SMS credit for test.
Now here is the straight forward and easy PHP coding to integrate CM.NL with your application.
<?php 
class CMSMS 

  function CreateMessage($ProductToken, $Sender, $Recipient, $Tariff, $Body) 
  { 
$XMLSMS = new SimpleXMLElement('<MESSAGES/>'); 
$XMLSMS->addChild('AUTHENTICATION'); 
$XMLSMS->AUTHENTICATION->addChild('PRODUCTTOKEN', $ProductToken); 
$XMLSMS->addChild('TARIFF'); 
$XMLSMS->TARIFF = $Tariff; 
$XMLSMS->addChild('MSG'); 
$XMLSMS->MSG->addChild('FROM'); 
$XMLSMS->MSG->FROM = $Sender; 
$XMLSMS->MSG->addChild('BODY'); 
$XMLSMS->MSG->BODY = $Body; 
$XMLSMS->MSG->addChild('TO'); 
$XMLSMS->MSG->TO = $Recipient; 
return $XMLSMS->asXML(); 
  }
  function SendMessage($URL, $Message) 
  { 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $URL); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml', 'Content-length: ' . strlen($Message))); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $Message); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$return = curl_exec($ch); 
curl_close($ch);
return $return; 
  } 

//Send SMS
$SMS = new CMSMS; 
$ProductToken=$_POST['product_token'];//token you get in email
$Tariff=0; $Sender="123456789"; //your no
$Recipient="123456789"; $Body="Test SMS using CM.NL direct";
$XMLtoSend = $SMS->CreateMessage($ProductToken, $Sender, $Recipient, $Tariff, $Body); 
$return=$SMS->SendMessage('http://gateway.cmdirect.nl/cmdirect/gateway.ashx', $XMLtoSend); 
echo $return;
?>


HTTP:
send-sms-start.php:-
<form method="post" action="send_sms.php"> You can use BUSINESS or ELITE Credential to Send SMS.<br /> Customer ID: <input name="customer_id" type="text" value="1000"><br/> Username: <input name="username" type="text" value="your-user-id"><br/> Password: <input name="password" type="text" value="pass"><br/> <br /> Sender No: <input name="sender_no" type="text" value=""><br/> Recipient No: <input type="text" name="recipient_no" value=""> <br/> SMS Text: <input type="text" name="sms_body"> <input type="submit" value="Send SMS"> </form>

send_sms.php
// Report all PHP errors (see changelog) error_reporting(E_ALL); include("cmSMS.php"); //Create SMS Object $SMS = new CMSMS; $CustomerID=$_POST['customer_id']; $Login=$_POST['username']; $Password=$_POST['password']; $Tariff=0; $SenderName=$_POST['sender_no']; $Body=$_POST['sms_body']; $MSISDN=$_POST['recipient_no']; //Prepare SMS $Reference="member_id=420&Time=".time(); //Any custom Reference/Text. Helpful to identify SMS $XMLtoSend = $SMS->CreateMessage($CustomerID, $Login, $Password, $Tariff, $SenderName, $Body, $MSISDN, $Reference); //Send SMS $respnose=$SMS->SendMessage('http://smsgateway02.cm.nl/cm/gateway.ashx',$XMLtoSend); if($respnose=="") echo "SMS Sent Successfully"; else echo $respnose;

cmSMS.php: 
class CMSMS 

  function CreateMessage($CustomerID, $Login, $Password, $Tariff, $SenderName, $Body, $MSISDN, $Reference="")
  {  
    $MSISDN=str_replace("+","",$MSISDN);//remove begining plus sign
    if(substr($MSISDN,0,2)!="00")
    $MSISDN="00".$MSISDN;
    $XMLSMS = new SimpleXMLElement('<MESSAGES/>'); 
    $XMLSMS->addAttribute('PID',25); 
     
    $XMLSMS->addChild('CUSTOMER'); 
    $XMLSMS->CUSTOMER->addAttribute('ID',$CustomerID); 
     
    $XMLSMS->addChild('USER'); 
    $XMLSMS->USER->addAttribute('LOGIN',$Login); 
    $XMLSMS->USER->addAttribute('PASSWORD',$Password); 

//Helpful for assign cusotm SMS ID
if($Reference!="")
{
      $XMLSMS->addChild('REFERENCE');
      $XMLSMS->REFERENCE = $Reference;
}
     
    $XMLSMS->addChild('TARIFF'); 
    $XMLSMS->TARIFF = $Tariff; 
     
    $XMLSMS->addChild('MSG'); 
     
    $XMLSMS->MSG->addChild('FROM'); 
    $XMLSMS->MSG->FROM = $SenderName; 
     
    $XMLSMS->MSG->addChild('BODY'); 
    $XMLSMS->MSG->BODY = $Body; 
     
    $XMLSMS->MSG->addChild('TO'); 
    $XMLSMS->MSG->TO = $MSISDN; 

//Multipart SMS.Recipient will get more then 160 char at once
$no_of_sms_credit_required=ceil(strlen($Body)/160.00);
if($no_of_sms_credit_required>1)
    {
      $XMLSMS->MSG->addChild('MINIMUMNUMBEROFMESSAGEPARTS');
      $XMLSMS->MSG->MINIMUMNUMBEROFMESSAGEPARTS = 1;

      $XMLSMS->MSG->addChild('MAXIMUMNUMBEROFMESSAGEPARTS'); 
      $XMLSMS->MSG->MAXIMUMNUMBEROFMESSAGEPARTS = $no_of_sms_credit_required;

      $XMLSMS->MSG->addChild('TARIFFPERMESSAGEPART');
      $XMLSMS->MSG->TARIFFPERMESSAGEPART = $Tariff;
}

    return $XMLSMS->asXML(); 
  } 
   
  function SendMessage($URL, $Message) 
  { 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $URL); 
    #curL_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml', 'Content-length: '.strlen($Message))); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $Message); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    $return = curl_exec($ch); 
    curl_close($ch);     
    return $return; 
  } 
}

Concatenated SMS:
A single SMS contain maximum 160 character but sometimes your SMS might longer then that and your recipient love to receive whole SMS at once(in a single SMS). In order to do it, you have to use additional parameter MINIMUMNUMBEROFMESSAGEPARTS,  MAXIMUMNUMBEROFMESSAGEPARTS & TARIFFPERMESSAGEPART in SMS XML preparation.

FAQ:
Where from shall i get ProductToken of CM Direct?
=> You will receive a Product Token by mail after creating an account.

For HTTP method where from  shall i get Customer ID, username and password?
=> CM.NL will create these for you.

What response do i receive for HTTP?
=> Every request will get an HTTP response with status 200 (OK), even if the request is malformed. If the request was correct, the response will be empty. If the request was malformed, the response will start with “ERROR”. So it's easy for you to check a SMS sent or not by $response=="" (success)

How to pass a custom text(specially needed for SMS ID) which will back to me while Delivery Receipt?
=> You can pass custom text using REFERENCE field.

For any further enquiry please feel free to post your comments.

Monday, August 12, 2013

Integrate Plivo.com SMS API

Plivo.com have little bit more restriction and a bit complex to integrate rather then other similar sites. Moreover, PHP PEAR library must be installed on your server. Once everything is ready you need to download plivo.php file from their site(http://plivo.com/docs/helpers/php/). Now in short and quick example, use the following code to send SMS.

<?php
require_once 'HTTP/Request2.php';
require_once 'plivo.php';

$params = array(
'src' => 1202123456', //sender id, which must bought from plivo.com
'dst' => '190909090',
'text' => 'test SMS from plivo',
'type' => 'sms',
);
$response = $p->send_message($params);
print_r($response);
echo "Script End";
?>

Most important factor here is, you need to 

For developer documentation here is the link: http://plivo.com/blog/get-started-with-your-free-developer-account/

Thursday, August 1, 2013

How to integrate Paypal API in your site

Paypal have changed their site features in recent days. They have now more usable online payment solutions. As though their outlook and functionality have been changed, i am going to write a short summery of  how to integrate paypal in your site.

First of all you need a paypal developer account(for test transaction) and live account(for real transaction).
  1. Go to http://developer.paypal.com and register here.
  2. Now log in developer.paypal.com
  3. After log in click "Dashboard" tab. Here you will get 02 options (Test and Live).
  4. Click Test->REST API transactions. you get "Test REST API transactions and responses". Click on this link "Create your first PayPal app and receive API credentials."
  5. You are now at "My appsREST API apps where from you can Create, edit and manage multiple PayPal apps. In each app, select the specific PayPal capabilities you want to offer to your customers. Every app gets a unique set of live and test API credentials. 
  6. You get there a button labeled "Create Application" click on it. Give Application name and select integration type(web/mobile app). Finally click "Create Application"
  7. Your application is immediately approved and ready for Accepts PayPal payments. From this page you can get application credentials by clicking "REST API CREDENTIALS". You get credentials like: 
Test credentials
Test account: yourname-facilitator@gmail.com
Endpoint: api.sandbox.paypal.com
Client ID: AWXUjxAgAxTmMjjv9yhNXZERa_zAxz4kWlB1CRMgTWUYtaVop5pQyi9uCy
Secret: EK9ZzRD2ciHJhk_GBLdaR7BP7PVSEX-tU0nyaVMJxIGDeylvVjP0uRamDvyp
Live credentials
Endpoint: api.paypal.com
Client ID: Aey2xBfKiEZWrk8Fgahd6Cw4KXL0Mu7eEsC6Pdxj45oaNhOPsbFLMSFo_tu
Secret: ENE0iBCsfgeWaUCK2ghzUCeK7afuIslW1XoGVi93gn6pjSsx-UUoCmqEwTWD
 
After create "My Application" successfully you get "Sandbox accounts" in left menu under Applications. Click on "Sandbox accounts". Here you get your business account. 
Click on "Profile" link under your account title. "Account Details" popup window will appear. From there "API Credential" tab you have to collect 3 things
API Username: yourname-facilitator_api1.gmail.com
Password: 1375222646
Signature: AFcWxV21CxE7Ev3bYYYRCpSSRl31AeHPKoPJmkyNgPh36GMZEZxToxth

Well, we have created merchant(seller) account successfully. Now we need to create some buyer account so that we can test buyer experience.
After log in developer.paypal.com click "Application" main tab on the top.
Click "Applications"->Sandbox accounts. Click "Create account" button (right middle corner).
Provide Account Detail information. For example:
Country: United States
Account Type: Personal(buyer account) or Business(seller account). i select here Personal
Email address: your-fake-email@something.com
Password: anypass
Payment Methods: Paypal balance Put here any amount say 5000USD
Bank verified account:  Yes
Select payment card: Discover
Credit card type: American Express
Lastly click "Create Account" button.

So you have created a buyer account for you. Now you can check your Applications and Sandbox Accounts by click on "Application" link on header after log in developer.paypal.com

How to activate your credit card?
=> After log in developer.paypal.com click "Application" -> "Sendbox accounts" -> Profile(under test account) -> Funding tab -> 'Paypal Payment Card' section - Card Status. Click here to activate your credit card.

How do i check whether i receive a payment from a buyer to my business account?
=> After log in developer.paypal.com click "Application" -> "Sendbox accounts" -> Click "Notifications" (under business account)-> You get 'Notification of Payment Received" with date. click on it to show detail of this transaction.

Shall i need to log in developer.paypal.com during test transactions?
=> No you don't need that. Before last upgrade of paypal it was mandatory.

How to change my Store Name in Sandbox/Test account?
=> log in sandbox.paypal.com using merchant account detail created at developer.paypal.com. Click "My Account" tab(first tab) of header menu. Click "Profile" tab which is right most tab appear in sub menu. Now Click "My Business Info" in left menu. First item her is name and click "Change" link (appear right to name). Select "Change Business Name" and press next. Enter here new business name and click "Continue". You are done.

What is developer.paypal.com?
=> Developer.paypal.com is a place where from you will be able to create test accounts(buyer & seller), get account API details, view their summery transactions. Moreover, you can create New Test Applications from here. In addition, you can even change buyer & sellers account password.

What is sandbox.paypal.com?
=> sandbox.paypal.com is purely a Test Platform where from you will be able to log in using account details(email and password) created at developer.paypal.com. Moreover, you can get detail transaction history of buyer/seller account.

Where from i get Paypal Live account API Credentials(Username, Password & Signature)?
=> Go to https://www.paypal.com/us/cgi-bin/webscr?cmd=_login-api-run and log in using your Live account userid and password. Immediately after you logged in, will get API username, Password and Signature.

Error Message: Could not resolve host: api-3t.paypal.com; Host not found
=> Check correctness of your Live account API Credentials(username, password & signature). In order to get correct credential follow former error & solution.

How to create a test account in Sandbox?
=> After login developer.paypal.com click Application. In left menu under Applications you will find out Sandbox accounts(click on it). Now click "Create Account" button on the right. Provide detail information here and click "Create Account". Keep in mind, in order to test buyer experience you have to set Account Type to Personal.

Where from i can check my Buyer Account Transactions & Payments?
=> Go to sandbox.paypal.com which is purely a Test Platform and from here you will be able to log in using test account details(email and password) created at developer.paypal.com. Moreover, you can get detail transaction as well as test account information(like first & last name, country etc) history of buyer/seller account.

What is Guest Checkout?
=> There are two ways of payment receive in paypal. First payment is not possible without having any paypal account and Second, pay using Credit Card (no need any paypal account). Guest checkout means second one.

How to enable Guest Checkout in Paypal Checkout
=> In your NVPSTR set &SOLUTIONTYPE=Sole to enable Guest Checkout. And optionally specify LANDINGPAGE=Billing for the billing page to be forced. If guest checkout is enabled then visitors will be able to pay using only their credit card (without having paypal account).
Moreover, in order to enable Guest Checkout you need to setup few parameter in your paypal merchant account as well. You must have 'PayPal Account Optional' set to 'On' with 'Website Preferences' section of PayPal account.
Profile > My selling tools (or: My selling preferences) > Website Preferences > Update > PayPal Account Optional: On.

How to turn off Paypal Shipping Address in Checkout
=> For sale digital goods and local pickup we don't need any shipping address. so we need not to display shipping address in paypal. In NVPSTR:
NOSHIPPING=1 leads buyer not asked for a shipping address in paypal.
Error & Solution:
The totals of the cart item amounts do not match order amounts
=> Please check your total amount(AMT) should be equal to sum of all item/product total amount (ITEMAMT) and Tax amount(TAXAMT) and shipping amount(SHIPPINGAMT) and subtract by shipping discount amount(SHIPDISCAMT).

Security header is not valid
=>Check your API_ENDPOINT. For sandbox it should be https://api-3t.sandbox.paypal.com/nvp and for live https://api-3t.paypal.com/nvp

Error Message: Unknown SSL protocol error in connection to api-3t.paypal.com:443
=> This error comes in localhost because of SSL not supported in localhost. In server you will not get this error.

This transaction has expired. Please return to the recipient's website to complete your transaction using their regular checkout flow.
=> Check your PAYPAL_URL. For Sandbox it's https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token= and for Live it's https://www.paypal.com/webscr&cmd=_express-checkout&token=
     If you still getting problem please check API_ENDPOINT as well. For sandbox it should be https://api-3t.sandbox.paypal.com/nvp and for live https://api-3t.paypal.com/nvp


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.