30 November, 2010

How to integrate Paypal Subscriptions using PHP

After lots of googling, i was on right track to integrate paypal subscriptions using php. So thought, this might be of some help to others as well. Here is how i integrated the paypal subscriptions in php.
Step 1: Create a paypal sandbox account from www.developer.paypal.com, if you dont have it else login to it.
Step 2: Create a test account (Preconfigured Account link) as a buyer.
Step 3: Verify the account if status says 'Unverified'.
Step 3: Create a test account (Preconfigured Account link) as a seller.
Step 4: Create a form for subscriptions payment in paypal as following code:
This is the form that is submitted to paypal (sandbox for test)


//cmd is _xclick-subscriptions for subscription





//amount is USD 300

//monthly; can use Y for annual subscription


//setting rm to 2 and using return will send the response as post values








You need not set any IPN path from your sandbox account, because adding "notify_url" to the form will override the account default settings.

Step 5: Now to the ipn.php page

$url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
$postdata = '';
foreach($_POST as $i => $v) {
$postdata .= $i.'='.urlencode($v).'&';
}
$postdata .= 'cmd=_notify-validate';
$web = parse_url($url);
if ($web['scheme'] == 'https') {
$web['port'] = 443;
$ssl = 'ssl://';
}
else {
$web['port'] = 80;
$ssl = '';
}
$fp = @fsockopen($ssl.$web['host'], $web['port'], $errnum, $errstr, 30);
if (!$fp) {
echo $errnum.': '.$errstr;
}
else {
fputs($fp, "POST ".$web['path']." HTTP/1.1\r\n");
fputs($fp, "Host: ".$web['host']."\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($postdata)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $postdata . "\r\n\r\n");

while(!feof($fp)) {
$info[] = @fgets($fp, 1024);
}
fclose($fp);
$info = implode(',', $info);
if (eregi('VERIFIED', $info)) {
if(isset($_REQUEST["txn_type"]) && (strtolower($_REQUEST["txn_type"]) == "subscr_payment") || (strtolower($_REQUEST["txn_type"]) == "subscr_signup")) {
//update database, send notification or do whatever here
}
else {
//the subscription type can be something else
}
}
else {
//this is not valid payment
//so log some error here
}
}

And success and cancel page can be done easily.
And thats it, hope this helps someone.

1 comment:

@bhu1st said...

thanks sudhir sir will try it :)