How to setup Paypal IPN using PHP

Instant Payment Notification allows you to integrate your PayPal payments with your website's backend operations, so you get immediate notification and authentication of the PayPal payments you receive. Its easy to do this.

Requirement:
  • Paypal seller account (Live or Sandbox). How to  create sandbox account. Click Here
  • Basic Knowledge of PHP and Mysql
  • A running website for example (www.s2ptech.com)
  •  Make a folder on web server, for example paypal.(www.s2ptech.com/paypal)
  • Free Time: 10 Minutes
Lets Start. Follow these steps:

Front End Page:

This is a page where you can do any payment.
Index.php
<title>Paypal IPN Payment Gateway</title>

<form action="paypalverified.php" method="post" name="frmfunds">
<select class="ns_quarter-1" name="currency_id" id="currency_id">
    <option selected="selected" value="USD">USD</option>
</select>

<input type="text" id="fund_ammount" name="fund_ammount" class="ns_quarter-1"/>
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="item_name" value="Item Name">
<input type="hidden" name="item_number" value="123">
<input type="hidden" name="currency_code" value="USD"/>
<input type="submit" name="DepositMoney" class="submit3" value="Deposit Money" />
</form>
 Copy this script in any text editor and save as "index.php". Where "index" can be any word.
 Paste this page in paypal folder. Your page url will be www.s2ptech.com/paypal/index.php. Copy this url in address box of any browser and run.

Oh! this page is redirecting to www.s2ptech.com/paypal/paypalverified.php. No page Found error comes. Actually you have not created paypalverified.php page.

Next Create a paypalverified.php  page and save to paypal folder.

paypalverified.php

<?php
session_start();
    if($_POST['DepositMoney'])
    {
        $paypal_email = 'Enter Your Paypal Email ID';
        $paypal_url='https://www.sandbox.paypal.com/cgi-bin/webscr';
       $return_url = 'YOUR URL/paypal/payment-successful.php';             
        $cancel_url = 'YOUR URL/paypal/payment-cancel.php';
        $notify_url = 'YOUR URL/paypal/notify_url.php';
        $item_name = $_POST['item_name'];
        $item_amount = $_SESSION['fund_amt'];
        $querystring .= "?business=".urlencode($paypal_email)."&";   
        $querystring .= "USER=".urlencode("")."&";
        $querystring .= "PWD=".urlencode("")."&";
        $querystring .= "SIGNATURE=".urlencode("")."&";
        $querystring .= "identity_token=".urlencode("")."&";
        $querystring .= "item_name=".urlencode($item_name)."&";
        $querystring .= "amount=".urlencode($_POST['fund_ammount'])."&";
        foreach($_POST as $key => $value)
        {
            $value = urlencode(stripslashes($value));
            $querystring .= "$key=$value&";
        }
        $querystring .= "return=".urlencode(stripslashes($return_url))."&";
        $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
        $querystring .= "notify_url=".urlencode($notify_url);
        @header('location:https://www.sandbox.paypal.com/cgi-bin/webscr'.$querystring);                       
    }
?>

Replace colored text with your live or Sandbox email Id

Replace colored text with "https://www.paypal.com/cgi-bin/webscr" If  you use Live Paypal id 

Replace colored "YOUR URL" with "http://www.s2ptech.com" for return_url, cancel_url and notify_url.

There is a question for you.

Q. What is Return url, Cancel url and Notify url?

Don't go anywhere to search.

Return Url: When a payment is complete from paypal sandbox successfully. You will redirect to your website automatically. You can select that page by return url.

Cancel Url: When a payment failed due to any reason. You will redirect to your website on cancel url page.

Notify Url: When a customer makes a payment to you or a payment is reversed or refunded, PayPal will post a notification to your server at the URL you specified. Included in this notification will be all your customer’s payment information (e.g. customer name, payment amount) as well as a piece of encrypted code. When your server receives a notification, it will then post the information, including the encrypted code, back to a secure PayPal URL. PayPal will authenticate the transaction and send confirmation of its validity back to your server.



notify_url.php

<?php
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value)
{
    $value = urlencode(stripslashes($value));
    $req .= "&$key=$value";
}

// post back to PayPal system to validate

$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";

// If testing on Sandbox use:
$header .= "Host: www.sandbox.paypal.com:443\r\n";
//$header .= "Host: www.paypal.com:443\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

// If testing on Sandbox use:

$fp =fsockopen('ssl://www.sandbox.paypal.com',443,$err_num,$err_str,30);
          //$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
echo('<br>'.$req);
// assign posted variables to local variables



$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];



if (!$fp)
{
    echo(' HTTP ERROR');
}
else
{
    fputs ($fp, $header . $req);
    while (!feof($fp))
    {
        $res = fgets ($fp, 1024);
        echo('<br> res is '.$res);
    if (strcmp ($res, "VERIFIED") == 0)
    {
        // check the payment_status is Completed
        // check that txn_id has not been previously processed
        // check that receiver_email is your Primary PayPal email
        // check that payment_amount/payment_currency are correct
        // process payment
                 /*Above data transfer to this page. When a payment complete successfully.
                    VERIFIED means payment completed successfully.
                    You can do anything with this data. For example,Store data into database, Email to Clients.

*/
         $mail_From = "From: YOUR EMAIL ID";
        $mail_To = $_POST['payer_email'];
        $mail_Subject = "VERIFIED IPN";
        $mail_Body = $req;
        foreach ($_SESSION as $key => $value)
        {
            $emailtext .= $key . " = " .$value ."\n\n";
        }
        mail($mail_To, $mail_Subject, $emailtext . "\n\n" . $mail_Body, $mail_From);
      
      
        mysql_connect('HOST NAME', 'USER NAME', 'PASSWORD') or exit(0);
        mysql_select_db('DATABASE NAME') or exit(0);
        $payer_email = mysql_real_escape_string($_POST['payer_email']);
        $mc_gross = mysql_real_escape_string($_POST['mc_gross']);
        $sql = "INSERT INTO orders VALUES (NULL, '$txn_id', '$payer_email', $mc_gross)";
      
        if (!mysql_query($sql)) {
        error_log(mysql_error());
        exit(0);
        }
      
      
        $fh = fopen('result.txt', 'w');
        fwrite($fh, $mail_Subject.' -- '.$req);
        fclose($fh);
            }
    else if (strcmp ($res, "INVALID") == 0)
    {
        // log for manual investigation
        $mail_From = "From: mubarik.galaxyweb@gmail.com";
        $mail_To = "mukeshdas1985@gmail.com";
        $mail_Subject = "INVALID IPN";
        $mail_Body = $req;
        foreach ($_SESSION as $key => $value)
        {
            $emailtext .= $key . " = " .$value ."\n\n";
        }
        mail($mail_To, $mail_Subject, $emailtext . "\n\n" . $mail_Body, $mail_From);
        $fh = fopen('result.txt', 'w');
        fwrite($fh, $mail_Subject.' -- '.$req);
        fclose($fh);
    }
}
fclose ($fp);
}

?>

payment-successful.php


<div id="signup">
<div><h2 style="color:#144D98;">Congratulation ! Fund Transfered Into Your  Account.</h2></div>
<div><h3>Your have successfully Addedd Fund into Your  Acount.</h3></div>
<div>Your Deposited Funds <strong>:</strong> $<?php echo $_GET['amt'];?></div>
<div class="clear"></div>
</div>
payment-cancel.php
<div id="signup">
<div><h2 style="color:#144D98;">Sorry ! You canceled the Payment.</h2></div>
<div class="clear"></div>
</div>

Scripting section completd. But some major things remains. Click Here To go into next section.

Read More

How to make Paypal Sandbox account

It's easy to setup Paypal Sandbox account for developer to test the working Paypal code.
Follow these steps:

Step 1
Create a Paypal Sandbox account at

Paypal Sandbox Login

https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_account&nav=0.0





Step 2
Now create test accounts for payment system.Click Sign Up to make a new Account.

  

Step 3
You can create  Personal and Business account now.
 

Read More

Run Fragments on Older version of Android

First generate android code by the wizard for API level 11. But it uses the support library already – so shouldn’t it run on older versions as well?

The heavy lifting already has been done. The wizard created both activities as subclasses of FragmentActivity. This is a class of the support library that allows you to access an FragmentManager using getSupportFragmentManager().

Two changes are needed to make it run on older versions.

First the generated class ItemListFragment contains a layout constant that has been introduced in API level 11: simple_list_item_activated_1. This specific layout highlights activated list items. Which is useful, if you have a multi-pane layout, because it shows the user which list item is selected and displayed in the details pane.

I ignore the highlighting for now and just try to get the code to run:

int layout = android.R.layout.simple_list_item_1;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
   layout = android.R.layout.simple_list_item_activated_1;
}
setListAdapter(new ArrayAdapter<DummyContent.DummyItem>(
      getActivity(),
      layout,
      android.R.id.text1,
      DummyContent.ITEMS));

The second problem is the ActionBar, which is not available on older devices without adding an additional library. Since this is the topic of my next post, I simply ignore the ActionBar on older devices for now. Change the line with getActionBar() to this in the ItemDetailActivity:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
       getActionBar().setDisplayHomeAsUpEnabled(true);
    }


Now you get a Lint warning. That the call requires API level 11 but that your manifest file states API level 7 as a minimum. Add an annotation to suppress the new API warnings for the onCreate() method:

@SuppressLint("NewApi")
Now change your AndroidManifest.xml file to support API level 7:

    <uses-sdk
       android:minSdkVersion="7"
       android:targetSdkVersion="16" />
 With these changes, you can now run the project on older devices.
Read More

Use Windows 8 as a Wi-Fi Hotspot

Creating Wi-Fi HotSpot in Windows 8 – Share Laptop Internet Connection

In windows seven there was an option to create the Wi-Fi hotspot but it’s not the case with the Windows 8. In Windows 8 you will need cmd to create a hotspot.

Requirement:

    A Working Internet Connection (Either Dial Up Connection or Else Lan Internet Connection)
    A Built In or External Wifi adapter which supports the sharing ability for internet connection
    A laptop.

Step:


  • Open up CMD in the administrator mode.
  • Write the following command and look for the thing mentioned in the screen shot that whether it’s written yes or no. It it’s yes then you can go on “It means that you can enable the hotspot and can share your internet connection.”

         Command to Check Sharing Compatibility of wifi network for windows 8:

          netsh wlan show drivers




Creating The Wi-Fi Hotspot:

Don’t close the cmd as you are going to use cmd again. Following is the command line to create the hotspot, set the password and name it as you want too.

    netsh wlan set hostednetwork mode=allow ssid=nameOfwifiHotspot key=yourpassword

The above is the command to create the hotspot. Replace “nameOfwifiHotspot” with the desired network name and replace “yourpassword” with the desired password which will be used by the others to connect to the hotspot.

  • Press the enter and hotspot will be created.
  • Starting the Wi-Fi Created Hotspot in Windows 8:

Now you need to start the hotspot, again you are going to need the cmd and the cmd must run in the administrator mode. Write the following command in the cmd to start the above created hotspot.

    netsh wlan start hostednetwork


Press enter and the hotspot will be created and will be discoverable by the other devices as well.
Sharing the working internet connection with the windows 8 Wi-Fi hotspot:

All Right, everything has been done and now you only need to give your laptop’s internet connection’s access to the created hotspot, so that any user connected to the hotspot will have the internet access also. For this reason you will need to open the windows networking and sharing center.


Windows 8 searching the network and sharing center

Open up the network and sharing center, and then go to “Change adapter settings” on the top left pane. Click that to open. Here you will see your created hotspot connection plus the connection which you want to be shared with the hotspot for the internet sharing. The created hotspot connection has the star with the name. You need to open the properties of the connection which you want to be shared with the hotspot.



Right click and open the properties of the connection which has the internet access and is the original internet connection of the laptop, whether it’s a dialup, local area network or anything like that. Go to the sharing tab in the properties and then tick the “Allow other network users to connect through this pc internet connection” and in the drop down below, select the hotspot connection which is “Local Area connection *21” in my case and then hit ok. Re-dial the connection or else reconnect the internet connection if needed.


That was it and you are done, the password to connect with the hotspot is the same which you used while setting up hotspot in the cmd. If you can’t still share the internet then reason are that firewall or an antivirus is causing the problem, try disabling the firewall if you trust the person with whom you are sharing the hotspot or else try adding an exception int he firewall or antivirus.
Read More

How to create autoincrement id in oracle with full example



Here i am telling you How to create autoincrement id in oracle with full example
  • First of all you need to open your oracle database and login with your given username and password.
  •  And then click on Object Browser and create a table (name which you want) here i use s2ptech.
  • Here in s2ptech table i use two field id and name.
  • Click on next button and then select not populated option in radio button.
  • Select primary key (id which you want to autoincrement) and click next->next->finish->create.
  • Now your table is created.
  • Now click on Sequence and fill the sequence name(seq_s2ptech).

  • And click on next, click on create and now your sequence is created
  • Now click on Trigger and fill the table name(s2ptech) and click on next.
  • Now do the action as shown in below image.
  • And click on next and finish.
  • At last you'll get trigger detail where if object status is valid and trigger status is enable will be shown then all works are done good.
And Yahooooooooo !!!!!
its time to insert your data in your table with auto-increment id in oracle

Read More

How to calculate date and time difference in java

Converts Date in milliseconds (ms) and calculate the differences between two dates, with following rules :

1000 milliseconds = 1 second
60 seconds = 1 minute
60 minutes = 1 hour
24 hours = 1 day
DateDifferentExample.java
package com.blogspot.s2ptech.date;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDifferentExample {

public static void main(String[] args) {

String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/15/2012 10:31:48";

//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

Date d1 = null;
Date d2 = null;

try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);

//in milliseconds
long diff = d2.getTime() - d1.getTime();

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);

System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");

} catch (Exception e) {
e.printStackTrace();
}

}

}
Result

1 days, 1 hours, 1 minutes, 50 seconds.
Read More

How to get current date and time in Java

Sometimes java developers need to find current date and time in their program.
In Java, you can get the current date time via following two classes – Date and Calendar. And, later use SimpleDateFormat class to convert the date into user friendly format.

1. Date() + SimpleDateFormat()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
2. Calender() + SimpleDateFormat()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
Full example
Here is the full source code to show you the use of Date() and Calender() class to get and display the current date time.
package com.blogspot.s2ptech;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class GetCurrentDateTime {
  public static void main(String[] args) {

  DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  //get current date time with Date()
  Date date = new Date();
  System.out.println(dateFormat.format(date));

  //get current date time with Calendar()
  Calendar cal = Calendar.getInstance();
  System.out.println(dateFormat.format(cal.getTime()));

  }
}
Read More