Integrate API

Integrate API - Header

Friday, July 10, 2015

How to integrate Simple Captcha

Captcha is one of powerful technique to prevent automated data submission in a form. All developers must agree that, it's the best and useful technique where user data input need to allow. for example in a signup form or login or even user comments. Although for some visitors it's annoying but no alternative at all. So the best practice is to use a simple captcha. Most popular captcha is re-captcha which is extremely complicated and not user friendly at all. So here i am going to show you how you can integrate a very simple captcha in few minutes.

A simple and good one will be if we are able to create a captcha using php GD library. Almost all recent linux hosted servers have PHP GD2 library support, so we don't need to rethink about it.

in your signup/login/other form:

<?php
session_start();
include("simple-php-captcha.php");
if(isset($_POST['submit']))
{
  if($_POST['captcha_text']==$_SESSION['captcha']['code'])
    echo "Correct";
  else
    echo "Incorrect";
}
$_SESSION['captcha'] = simple_php_captcha();
?>
download simple-php-captcha.php file from here.

Here is your sample form:
<form action="" method="post" enctype="multipart/form-data">
 Username: <input type="text" name="username" /><br />
 Password: <input type="password" name="password" /><br />
 <img src="<?php echo  $_SESSION['captcha']['image_src'];?>" /><br />
 Captcha: <input type="text" name="captcha_text" />
 <input type="submit" value="Submit" name="submit" />
</form>

Make sure backgrounds and fonts folders are in same path to simple-php-captcha.php file.

Happy Captcha !!!

Tuesday, January 6, 2015

How to integrate Twilio.com API in php

You can integrate twilio call and SMS api with your application. Let me start with Twilio SMS API.

I am sure you are planning to send marketing/quiz/service offering or any other SMS to thousands of numbers. Before dive in to coding let me make clear couple of very important considerations for you. Two basic understanding is very important to understand twilio API.
Twilio Number: it's an US number you can purchase from twilio. you can use it as your sender id while sending SMS. Its also said long code because it's 10 digit long.
Alternatively, Short code means 5-6 digit long number which also available to purchase at twilio.

Keep in mind, You can send only 1(one) message per second per Twilio number. However, if you're sending same sms(usually marketing offers) to a list of numbers, they are said bulk SMS, which long code numbers are not designed for.

Carriers often block high volumes of SMS with same content/text sent out from one long code phone number(twilio number) as a precaution. In order to reduce the chance of happening, below are some useful suggestions you may follow.

- Vary/Change the content of your messages.
- Don't send all SMS in one shoot. instead sending it out over time. Using scheduler is a great idea undoubtedly.
- Use more Twilio/Long numbers.
- Try not to use marketing links or phrases.
- In worst case, replace non-working sending numbers or consider one/multiple short code  for more detail of short code click here.

All right!!! Say, i am owner of a laundry shop and i offer 15% discount for winter seasons. So how would i send this discount offer to my clients using twilio? The best points keep in mind:

  1. Using 1 twilio number send maximum 10 sms per minute.
now calculate how many sms you need and how much time you plan to spent for sending all SMS. i am sure you are good in divide calculation and purchase twilio number as much as you need. this is the best way i ever found. keep in mind everything depends on carriers filtering mechanisms which changes very frequently. So use as much twilio number as you affort.

Well, lets focus on how to send a SMS using twilio API. In order to do that, you need to find out two credentials SID and TOKEN. Log in twilio.com and from dashboard you will get both sid and token.
In short let me show you how easy to use twilio API for sending SMS. here is the php code.

<?php
require_once('../twilio-php/Services/Twilio.php'); // Loads the Twilio SMS API library
$twilio_sid="AC6xxx2e0dcbd341cff1xxxxfc73181xxx";
$twilio_token="exxxx34a4532xxxxaa0129d97xxxx0e0";
$sender_id="1234567890";
$recipient_no="9876543210";
$sms_text="Hello guys";
$client = new Services_Twilio($twilio_sid, $twilio_token);
$client->account->messages->sendMessage($sender_id, $recipient_no, $sms_text);
?>

Thats it. Enjoy!!!

Tips:
In order to check non-interested recipient please check incoming sms text. if it contain STOP, STOPALL, END, QUIT, CANCEL or UNSUBSCRIBE text then mark this recipient number as non-interested and never send SMS to this number. Twilio keeps track of these type of recipient against your virtual number(sender no)so that you can't bother them again. So, it's good practice to either delete those number from your database or mark them specially so that in future you never send them SMS from this number.

Sunday, August 24, 2014

how to use google distance matrix api

you need to calculate distance between couple of points/address? you need to set a shortest path route of your travelling? you need to deliver your goods to customer as soon as possible with lowest cost? google distance matrix api is a good solution for you. here i am going to show how to use google distance matrix api for any of your above purpose.
first of all you need to enable distance matrix in google. as your know, in order to use google service you must need a valid gmail id. let me consider you already have one.

  1. now open to https://code.google.com/apis/console and log in your gmail account. 
  2. from the left menu click service link and activate Distance Matrix API
  3. Once you have activated, your API key is available from the API Access page, section: Simple API Access . And Distance Matrix API applications use the "Key for server apps" for me it looks like: 

 Key for server apps (with IP locking)
API key:
AIzaSyCDB-C_sJ4fIENo0ku_ZM6-9despwBHvvo
IPs:
Any IP allowed
Activated on: Dec 15, 2013 6:39 AM
  • mode — when calculating directions which mode of transport will consider? . Valid values are:
    • driving (default) indicates standard driving directions using the road network.
    • walking 
    • bicycling only available in the US and some cities in Canadia
  • You can receive two different types of output of distance:
    1. JSON Output
    2. XML Output
    All parameters are remain same except json/xml in request url.

    A simple distance matrix example(JSON Output): 
    https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&key=AIzaSyCDB-C_sJ4fIENo0ku_ZM6-9despwBHvvo

    https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=driving&language=fr-EN&key=AIzaSyCDB-C_sJ4fIENo0ku_ZM6-9despwBHvvo

    A simple distance matrix example(XML Output): 
    https://maps.googleapis.com/maps/api/distancematrix/xml?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=driving&language=fr-EN&key=AIzaSyCDB-C_sJ4fIENo0ku_ZM6-9despwBHvvo

    You can also get direction request:
    https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=AIzaSyCDB-C_sJ4fIENo0ku_ZM6-9despwBHvvo&avoid=highways&mode=bicycling

    More documentation of Google Distance Matrix API is here.
    Similar to Google Matrix API mapquest documentation is here.

    Saturday, August 2, 2014

    How to integrate stripe payment gateway in php

    Download all working example created by me: download

    Here are the way of use stripe serves quickly.

    An overview of how stripe coding works can be found at here

    All from A-Z technical with good details  is here

    Download couple of the best examples/souse code from here

    Step 01:
    Create developer Sendbox account in stripe.com https://manage.stripe.com/register

    Step 02:
    Stripe.com will send you a link to verify your email address and once your email address is verified you are ready to use stripe.com. Log in https://dashboard.stripe.com/login. after successful log in you will be redirected to an url like: https://dashboard.stripe.com/test/dashboard. right under the logo you will get a switching button to switch from Text to Live and vice versa. we will later discuss about it.

    Step 03:
    From left menu. General->Payments. Click "Create your first payment". In test mode, you can't enter any credit card number you wish. instead you have to use credit cards mentioned https://stripe.com/docs/testing. (For example, 4242424242424242 is a VISA Card)You can put blank CVC field and card expiration date can be any future date.

    Step 04:
    From left menu. General->Customer, Transfer, Recipient. you can create these from here.

    Step 05:
    From top right corner, beside your picture click on the down arrow. Click "Account Settings" click API Keys and collect secret and publishable keys from here.

    Step 06:
    Now download php library from https://github.com/stripe/stripe-php

    Step 07:
    Download very good 07 examples from https://github.com/stripe/wilde-things. i really appreciate their effort.

    Recurring Payment:
    Subscription -> Plans -> Create New Plan. Enter the following details:
    ID: DAILY_PLAN_ID_420
    Name: DAILY PAY ONE DOLLER
    Amount: 1
    Currency: USD
    Interval: daily (daily/monthly/yearly/etc...)
    Trial period days: 0
    Statement Description: DAILY PAYMENT 1 USD

    Download all working example created by me: download

    Error & Solution:
    Error: failed to call pay.php to process the transaction.
    Solution: when i upload all files in server i don't get this error message.

    Pause/Cancel Subscription Code:
      Stripe::setApiKey("sk_test_LteiEDqVirhMuUt3IzzxUHkU");
      //Create Customer
      try {
            $customer_id=$_POST['customer_id'];
            $customer_info = Stripe_Customer::retrieve($customer_id);
            //print_r($customer_info);
            echo $subscription_id=$customer_info->subscriptions->data[0]['id'];
            if($customer_info->subscriptions->retrieve($subscription_id)->cancel())
              echo "Subscription canceled successfully.";
            else
              echo "Error while cancel subscription";
      }
      catch (Exception $e) {
        $error = $e->getMessage();
      }
     
    Subscription for an Existing Customer(using customer id):
      Stripe::setApiKey("sk_test_LteiEDqVirhMuUt3IzzxUHkU");
      //Create Customer
      try {
            $customer_id=$_POST['customer_id'];
            $plan_id="DAILY_PLAN_ID_420";
            $customer_info = Stripe_Customer::retrieve($customer_id);
            //print_r($customer_info);
           
            if($customer_info->subscriptions->create(array("plan" => $plan_id)))
              echo "Subscription to $plan_id for customer id $customer_id is successfully.";
            else
              echo "Error while subscribe for customer id $customer_id.";
      }
      catch (Exception $e) {
        $error = $e->getMessage();

      }

    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.