Paypal IPN subscription (php) - php

I am trying to set up a subscription using Paypal and their IPN system for days now.
I could not understand most tutorials and finally found one that made sense to me.
With help of Sean on here I have changed the code slightly but still no luck.
To create the subscription button, I use the following code:
<form action="https://sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick-subscriptions">
<input type="hidden" name="business" value="info#mydomain.com">
<input type="hidden" name="lc" value="NL">
<input type="hidden" name="item_name" value="Mydomain.com Abonnement">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="no_shipping" value="2">
<input type="hidden" name="notify_url" value="http://www.mydomain.com/pp-ipn-handler.php">
<input type="hidden" name="return" value="http://www.mydomain.com/ppsuccess.php">
<input type="hidden" name="src" value="1">
<input type="hidden" name="currency_code" value="EUR">
<input type="hidden" name="bn" value="PP-SubscriptionsBF:btn_subscribeCC_LG.gif:NonHosted">
<input type="hidden" name="custom" value="'. $username .'">
<table>
<tr><td><input type="hidden" name="on0" value="Betaalperiode"><strong>Kies uw betaalperiode:</strong></td></tr><tr><td><select name="os0">
<option value="Per maand">Per maand : €25.00 EUR</option>
<option value="Per jaar">Per jaar : €240.00 EUR</option>
</select> </td></tr>
</table>
<input type="hidden" name="currency_code" value="EUR">
<input type="hidden" name="option_select0" value="Per maand">
<input type="hidden" name="option_amount0" value="25.00">
<input type="hidden" name="option_period0" value="M">
<input type="hidden" name="option_frequency0" value="1">
<input type="hidden" name="option_select1" value="Per jaar">
<input type="hidden" name="option_amount1" value="240.00">
<input type="hidden" name="option_period1" value="Y">
<input type="hidden" name="option_frequency1" value="1">
<input type="hidden" name="option_index" value="0">
<input type="image" src="https://www.paypalobjects.com/nl_NL/NL/i/btn/btn_subscribe_LG.gif" border="0" name="submit" alt="PayPal, de veilige en complete manier van online betalen.">
</form>
To handle the ipn response I have a file named pp-ipn-handler.php with the following code:
<?php
// read the post from PayPal system and add 'cmd'
$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";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
// assign posted variables to local variables
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
// $payment_currency = $_POST['mc_currency'];
$payment_currency = 'EUR';
$ppusername = $_POST['custom'];
$fp = fsockopen ('sandbox.paypal.com', 80, $errno, $errstr, 30);
if (!$fp)
{
}
else
{
fputs ($fp, $header . $req);
while (!feof($fp))
{
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0)
{
// When a payment has gone trough
//When payment is 25EUR make it a month validity
if ($ppusername&&($payment_currency=='EUR')&&($payment_amount=='25'))
{
$period = '+1 month';
}
//When payment is 240EUR make it a year validity
else if ($ppusername&&($payment_currency=='EUR')&&($payment_amount=='25'))
{
$period = '+1 year';
}
//There is incorrect information in this payment
else
{
}
//Lets first get the date in mysql format
$date = date('m/d/Y h:i:s', time());
$date = date('m/d/Y h:i:s', strtotime("$date -7 hours"));
//Now lets update the subscription records
require_once('core/dbconnect.php');
$subscriptionrecordexists = mysql_query("SELECT * FROM subscriptions WHERE username='$ppusername'");
if (mysql_num_rows($subscriptionrecordexists))
{
//User has purchase before. Adjust his subscription record and ad an invoice.
require_once('core/dbconnect.php');
$subscriptionrecord = mysql_query("SELECT * FROM subscriptions WHERE username='$ppusername'");
$row = mysql_fetch_array($subscriptionrecord);
//Update subscription record
$currentvalidity = $row['validity'];
if ($currentvalidity >= $date)
{
//Add period if subscription is still valid
$newvalidity = date('m/d/Y h:i:s', strtotime("$currentvalidity $period"));
require_once('core/dbconnect.php');
mysql_query("UPDATE subscriptions SET validity='$newvalidity' WHERE username='$ppusername'");
//Add invoice to user
if ($period == '+1 month')
{$product = 'NLTVMee.com voor 1 maand';}
if ($period == '+1 year')
{$product = 'NLTVMee.com voor 1 jaar';}
$paymentmethode = 'Paypal';
$oldvalid = $currentvalidity;
$newvalid = $newvalidity;
require_once('core/dbconnect.php');
mysql_query("INSERT INTO invoices VALUES ('','$date','$ppusername','$product','$paymentmethode','$payment_currency','$payment_amount','$oldvalid','$newvalid')");
}
else
{
//Add period from current date if validity is not valid anymore
$newvalidity = date('m/d/Y h:i:s', strtotime("$date $period"));
require_once('core/dbconnect.php');
mysql_query("UPDATE subscriptions SET validity='$newvalidity' WHERE username='$ppusername'");
//Ad invoice to user
if ($period == '+1 month')
{$product = 'NLTVMee.com voor 1 maand';}
if ($period == '+1 year')
{$product = 'NLTVMee.com voor 1 jaar';}
$paymentmethode = 'Paypal';
$newvalid = $newvalidity;
require_once('core/dbconnect.php');
mysql_query("INSERT INTO invoices VALUES ('','$date','$ppusername','$product','$paymentmethode','$payment_currency','$payment_amount','','$newvalid')");
}
}
else
{
//User has never purchased before. Make new subscription record and add invoice.
//Add period from current date if validity is not valid anymore
$newvalidity = date('m/d/Y h:i:s', strtotime("$date $period"));
require_once('core/dbconnect.php');
mysql_query("INSERT INTO subscriptions VALUES ('','$ppusername','$newvalidity')");
//Ad invoice to user
if ($period == '+1 month')
{$product = 'NLTVMee.com voor 1 maand';}
if ($period == '+1 year')
{$product = 'NLTVMee.com voor 1 jaar';}
$paymentmethode = 'Paypal';
$newvalid = $newvalidity;
require_once('core/dbconnect.php');
mysql_query("INSERT INTO invoices VALUES ('','$date','$ppusername','$product','$paymentmethode','$payment_currency','$payment_amount','','$newvalid')");
}
}
//End
else if (strcmp ($res, "INVALID") == 0)
{
}
}
fclose ($fp);
}
?>
As you can see it is now configured with the Paypal sandbox urls to try it out, but when I do and make the payment nothing is changed in the db and as you can see the IPN handler page should change things.

It is a blank page because you have your ipn listener as your return value, which is where you are sent after completion, but no info is sent. The postback to Paypal will have no values and your code will fail.
(from the docs - The URL to which PayPal redirects buyers' browser after they complete their payments. For example, specify a URL on your site that displays a "Thank you for your payment" page.)
<input type="hidden" name="return" value="http://www.mydomain.com/pp-ipn-handler.php">
You need to use notify_url
(from the docs - The URL to which PayPal posts information about the payment, in the form of Instant Payment Notification messages.)
<input type="hidden" name="notify_url" value="http://www.mydomain.com/pp-ipn-handler.php">
<input type="hidden" name="return" value="http://www.mydomain.com/payment_complete_thank_message.php">
Edit
I see 3 additional errors in the code
Your query on line #65 is $subscriptionrecord, but on line #66 you are using $userinfo
$subscriptionrecord = mysql_query("SELECT * FROM subscriptions WHERE username='$ppusername'");
$row = mysql_fetch_array($userinfo);
Correction
these below are not true as enclosing them in quotes "$currentvalidity $period" is the same as $currentvalidity.$period
On line #72 you need to concat $currentvalidity & $period inside strtotime() - $currentvalidity.$period
$newvalidity = date('m/d/Y h:i:s', strtotime("$currentvalidity $period"));
On line #91 & #111 you need to concat $date & $period inside strtotime() - $date.$period
$newvalidity = date('m/d/Y h:i:s', strtotime("$date $period"));

Related

Payment with PayPal hangs inside the notify_url page

I have this page to pay with paypal, and receive the notification in "notify_url". The purchase goes well but fails to receive the notification. Everything is fine until it reaches these two lines: $valid_txnid = check_txnid ($data ['txn_id']);$valid_price = check_price ($data ['payment_amount'], $data ['item_number']);
where the program hangs. (I know it because I have sent emails from various points of the program until I get there that I do not receive anything).
And also I don't know where the check_txnid () and check_price () functions come from, which I don't see defined anywhere. The code is taken from this other post: How to get transaction details in notify_url page in paypal
index.php
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" style="padding: 0; margin: 0;">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="business" value="sb-pwrdu1932120#business.example.com" />
<input type="hidden" name="quantity" value="1" />
<input type="hidden" name="item_name" value="MiArticulo" />
<input type="hidden" name="item_number" value="1" />
<input type="hidden" name="amount" value="1" />
<input type="hidden" value="19" name="invoice">
<input type="hidden" name="notify_url" value="http://infrangible-discoun.000webhostapp.com/pruebaPaypal/notifyUrl.php">
<input type="hidden" name="currency_code" value="EUR" />
<input type="hidden" name="rm" value="2" >
<input type="hidden" name="return" value="http://infrangible-discoun.000webhostapp.com/paypal4/newfile1.php">
<input type="image" border="0" name="paypal" src="images/btn_paypal_nl.gif" onClick=""/>
</form>
notifyUrl.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require("conexion.php");
require 'phpmailer/Exception.php';
require 'phpmailer/PHPMailer.php';
require 'phpmailer/SMTP.php';
// Response from Paypal
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
//$value = urlencode($value);
$value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}',$value);// IPN fix
$req .= "&$key=$value";
}
// assign posted variables to local variables
$data['item_name'] = $_POST['item_name'];
$data['item_number'] = $_POST['item_number'];
$data['payment_status'] = $_POST['payment_status'];
$data['payment_amount'] = $_POST['mc_gross'];
$data['payment_currency'] = $_POST['mc_currency'];
$data['txn_id'] = $_POST['txn_id'];
$data['receiver_email'] = $_POST['receiver_email'];
$data['payer_email'] = $_POST['payer_email'];
$data['custom'] = $_POST['custom'];
$data['invoice'] = $_POST['invoice'];
$data['paypallog'] = $req;
// post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
////mail('atiftariq80#gmail.com','Step 9','Step 9');
$res = fgets ($fp, 1024);
if (true || strcmp($res, "VERIFIED") == 0) {
////mail('atiftariq80#gmail.com','PAYMENT VALID','PAYMENT VALID');
// Validate payment (Check unique txnid & correct price)
$valid_txnid = check_txnid($data['txn_id']);
$valid_price = check_price($data['payment_amount'], $data['item_number']);
// PAYMENT VALIDATED & VERIFIED!
if($valid_txnid && $valid_price){ //doesn't pass this if.
//----------------- INSERT RECORDS TO DATABASE-------------------------------------
$name=$_POST['item_name'];
mysqli_query($db,"insert into ventas value(0,'$name')");
if ($data['invoice']=='basic') {
$price = 39;
} else {
$price = 159;
}
$this->user_model->update_user(
array(
'id' => $data['custom'],
'user_status' => 1,
'payment_date' => date("Y-m-d H:i:s",time()),
'next_payment_date' => date('Y-m-d', strtotime('+32 days')),
'user_package' => $data['invoice'],
'package_price' => $price
)
);
$data2 = array('id' => '',
'txn_id' => $data['txn_id'],
'amount' => $data['payment_amount'],
'mode ' => $data['payment_status'],
'paypal_log' => $data['paypallog'],
'user_id' => $data['custom'],
'created_at' => date('Y-m-d H:i:s',time())
);
$this->db->insert('tbl_paypal_log', $data2);
//----------------- INSERT RECORDS TO DATABASE-------------------------------------
}else{
// Payment made but data has been changed
// E-mail admin or alert user
}
} elseif ($res=='INVALID') {
// PAYMENT INVALID & INVESTIGATE MANUALY!
// E-mail admin or alert user
////mail('atiftariq80#gmail.com','PAYMENT INVALID AND INVESTIGATE MANUALY','PAYMENT INVALID AND INVESTIGATE MANUALY');
}
}
fclose ($fp);
}
?>
I don't know where the check_txnid () and check_price () functions come from, which I don't see defined anywhere.
That seems to be your problem. Don't call functions that don't exist.
If you want to to check the transaction ID and the price are unique and valid for what you are offering, create actual functions that actually do this.
You could for example use 'custom' or 'invoice' to match against an existing order record in your database and validate the price corresponds, if you provided such a unique number to PayPal as part of the transaction.

Struggling with paypal notify url

I have been at this for ages, reading countless tutorials, guides etc from here and paypal with no luck!
I have set up a paypal purchase button on my website. Having tested this with Paypal's sandbox, the payment part works. However on returning to the website it doesn't give the user what they purchased!
This is on the page where they can choose there purchase:
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="custom" value="<?=$person?>">
<input type="hidden" name="business" value="myemail#email.com">
<input type="hidden" name="item_name" value="5000 Credits for <?=$person?>">
<input type="hidden" name="item_number" value="5000 Credits">
<input type="hidden" name="amount" value="5.00">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="no_note" value="0">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="notify_url" value="<?=$site[location]?>ipn.php">
<input type="hidden" name="return" value="<?=$site[location]?>creditsdone.php">
<input type="hidden" name="cancel_return" value="<?=$site[location]?>">
<input src="images/buy_button.gif" height="22" type="image" width="156" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
</form>
The creditsdone.php simply says "Thank you for your purchase." This works as you are taken back to this after the purchase is successful.
The ipn.php page however does not work. As on return to the website, no credits are added to the players account.
The following is on the ipn.php page:
<?
include("funcs.php");
// read the post from PayPal system and add 'cmd'
$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";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= 'Content-Length: ' . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
// assign posted variables to local variables
// note: additional IPN variables also available -- see IPN documentation
/*$item_name = $_POST['item_name'];
$receiver_email = $_POST['receiver_email'];
$item_number = $_POST['item_number'];
$invoice = $_POST['invoice'];
$payment_status = $_POST['payment_status'];
$payment_gross = $_POST['payment_gross'];
$txn_id = $_POST['txn_id'];
$payer_email = $_POST['payer_email'];
*/
if (!$fp) {
// ERROR
echo "$errstr ($errno)";
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {
echo "<pre>";
print_r($_POST);
if($_POST[payment_status]=="Completed") {
if ((!fetch("SELECT tranid FROM $tab[paypal] WHERE tranid='$txn_id';")) && ($business == "myemail#email.com"))
{
$subexpire = time()+864000;
if($payment_gross == "5.00"){$turns="5000";}
elseif($payment_gross == "10.00"){$turns="7250";}
elseif($payment_gross == "25.00"){$turns="10000";}
elseif($payment_gross == "50.00"){$turns="12500";}
elseif($payment_gross == "100.00"){$turns="25000";}
elseif($payment_gross == "200.00"){$turns="57500";}
elseif($payment_gross == "300.00"){$turns="90000";}
elseif($payment_gross == "400.00"){$turns="132500";}
elseif($payment_gross == "500.00"){$turns="180000";}
elseif($payment_gross == "1000.00"){$turns="400000";}
elseif($payment_gross == "15000.00"){$turns="700000";}
else{$turns="0";}
$expires=$time+864000;//10 days
$total=$payment_gross-$payment_fee;
//update database to add turns to user in game they bought for
mysql_query("UPDATE $tab[user] SET status='supporter', statusexpire='$expires', credits=credits+$turns WHERE username='$custom'");
//insert into database paypal information
$buying_user = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE username = '". $custom ."'"));
$time = time();
$fetch_the_games = mysql_query("SELECT * FROM games WHERE starts < $time AND ends > $time");
while($credit_games = mysql_fetch_array($fetch_the_games))
{
mysql_query("UPDATE r$credit_games[round]_pimp SET status = '". supporter ."' WHERE code = '". $buying_user[code] ."'");
}
mysql_query("INSERT INTO $tab[paypal] (tranid,amount,fee,user,datebought) VALUES ('$txn_id','$payment_gross','$payment_fee','$custom','$time');");
//send email to admin about transaction from paypal--ADMIN-check database to make sure transaction went through to game
mail_2("$turns credits where bought!","\nDear Admin,\n\nYou just received a payment from $custom for $turns credits\n\nCost: $$payment_gross\nFee: $$payment_fee\n----------\nTotal: $$total","myemail#email.com");
}else{echo"Cannot refresh transaction!";}
}
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is an email address in your PayPal account
// process payment
}
else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
}
fclose ($fp);
}
?>
I understand this could seem pretty confusing, I'm very new to php and completely stuck so any help or tips would be greatly appreciated!!
Thank you!
The problem is here
mysql_query("UPDATE r$credit_games
Change to
mysql_query("UPDATE credit_games
Or to whatever your query name is.
it must be credit_games you have a $ giving error so please take a pause, sleep some hours and then keep working hehehe.

PayPal IPN not working anymore

Since yesterday the PayPal IPN was working fine, but today I can't receive any IPNs. I checked the MySQL, checkt the IPN Adresse and everything is fine. I was thinking PayPal did some changes on their IPN Server, that woman on the Phone told me no. Kind of weird.
So could someone check the ipn.php & the add.php?
add php
<?
define('BASEPATH', true);
require_once("../../config.php");
if(!$is_online){
redirect('../../../index.php');
exit;
}
$s_host = parse_url($site['site_url']);
if($_GET['cash'] != '' && is_numeric($_GET['cash'])){
$cash = ($_GET['cash'] < 1 ? 1 : $_GET['cash']);
$cash = number_format($cash, 2, '.', '');
}else{
redirect('../../../index.php');
exit;
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Redirecting...</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<style>body{background: #fff;font: 13px Trebuchet MS, Arial, Helvetica, Sans-Serif;color: #333;line-height: 160%;margin: 0;padding: 0;text-align: center;}h1{font-size: 200%;font-weight: normal}.centerdiv{position: absolute;top: 50%; left: 50%; width: 340px; height: 200px;margin-top: -100px; margin-left: -160px;}</style>
<script type="text/javascript">
setTimeout('document.paypalform.submit()',1000);
</script>
</head>
<body>
<div class="centerdiv"><h1>Connecting to Paypal <img src="<?=$site['site_url']?>/img/go_loader.gif" /></h1></div>
<form name="paypalform" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="<?=$site['paypal']?>">
<input type="hidden" name="item_name" value="<?='Add Funds - '.$data['login'].' - '.$s_host['host']?>">
<input type="hidden" name="custom" value="<?=($data['id'].'|'.$cash.'|'.VisitorIP())?>">
<input type="hidden" name="amount" value="<?=$cash?>">
<input type="hidden" name="currency_code" value="<?=($site['currency_code'] == '' ? 'USD' : $site['currency_code'])?>">
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="no_shipping" value="2">
<input type="hidden" name="rm" value="1">
<input type="hidden" name="return" value="<?=$site['site_url']?>/bank.php?success">
<input type="hidden" name="cancel_return" value="<?=$site['site_url']?>/bank.php?cancel">
<input type="hidden" name="notify_url" value="<?=$site['site_url']?>/system/payments/paypal/ipn.php">
</form>
</body>
</html>
ipn
<?php
define('BASEPATH', true);
require("../../config.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.1\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Host: www.paypal.com\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
// 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'];
$custom = $_POST['custom'];
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {
$get_data = explode('|', $custom);
if($site['paypal_auto'] == 1){
if($payment_status == 'Completed'){
$user = $db->QueryFetchArray("SELECT id,login FROM `users` WHERE `id`='".$get_data[0]."'");
$check = $db->QueryGetNumRows("SELECT id FROM `transactions` WHERE `gateway`='paypal' AND `trans_id`='".$txn_id."'");
if($check == 0){
$db->Query("INSERT INTO `transactions` (user, user_id, money, gateway, date, user_ip, trans_id) VALUES('".$user['login']."','".$user['id']."', '".$payment_amount."', 'paypal', NOW(), '".$get_data[2]."', '".$txn_id."')");
if($user['id'] > 0){
$db->Query("UPDATE `users` SET `account_balance`=`account_balance`+'".$payment_amount."' WHERE `id`='".$user['id']."'");
}
}
}
}else{
$user = $db->QueryFetchArray("SELECT id,login FROM `users` WHERE `id`='".$get_data[0]."'");
$check = $db->QueryGetNumRows("SELECT id FROM `transactions` WHERE `gateway`='paypal' AND `trans_id`='".$txn_id."'");
if($check == 0){
$db->Query("INSERT INTO `transactions` (user, user_id, money, gateway, date, paid, user_ip, trans_id) VALUES('".$user['login']."','".$user['id']."', '".$payment_amount."', 'paypal', NOW(), '0', '".$get_data[2]."', '".$txn_id."')");
}
}
}
}
fclose ($fp);
}
?>
I had the same problem. They started adding "\r\n" to the end of the response so I was comparing "VERIFIED" to "VERIFIED\r\n" and it was failing. You can do:
trim($res)
before testing for VERIFIED, or you can use strpos instead of strcmp:
if (strpos($res, "VERIFIED") === 0) (needs ===, not ==)
Finally, they also asked all customers a while back to start adding the Connection header:
$header .= "Connection: close\r\n";
To solving this problem, you need to edit Instant Payment Notification setting in your PayPal business account. This step by step instructions helps lot to enable IPN - PayPal IPN / Notify URL is not working on Sandbox Account

how to integrate paypal with codeigniter?

I'm trying to integrate PayPal payment with my codeigniter project. My project is about a dating site, in which two different users interact with each other. So I'm selling plans, on the based of which users will be provided access to send messages to to other for the that period of time. For that i have developed a very simple page containing radio buttons to choose from different plans.
These are the following plans
one month ($2)
Two month ($4)
Three month ($6)
Four month ($8)
Five month ($10)
and so on
Six month ($12)
So, user can choose anyone plan from the above and can then proceed further to pay the amount on PayPal. This page will be available to user who have accounts on our site.
so we can transfer all the details of current user to PayPal, such as -- name,email,etc..
I have tried reading many articles on how to integrate paypal but none of them helped me.
As I'm new to codeigniter.
I have also created Paypal and sandbox account on paypal. I downloaded php-toolkit from sourceforge.net and used it independently, then it runs properly. but when i try to implement in codeigniter, it does not take anywhere.
Please help me !!
EDIT :
<?php
//Configuration File
include_once APPPATH.'../php_paypal/includes/config.inc.php';
//Global Configuration File
include_once APPPATH.'../php_paypal/includes/global_config.inc.php';
?>
<?php echo form_open('https://www.sandbox.paypal.com/cgi-bin/webscr');?>
<input type="hidden" name="amount" value="9.95">
<input type="hidden" name="item_name" value="Test Payment">
</form>
This is what i'm simply trying to create. Earlier i tried to use "process.php" in the form action, but i was getting URL error in codeigniter. So i thought why not use this way. I know there are function responsible which are sending values to paypal. But through this action method. I'm being redirected to simple paypal page.
Here are the steps you can follow.
Step1 Create IPN Form. make sure to pass IPN URL (notify URL) to paypal.
For Form variables, you can refer https://developer.paypal.com/webapps/developer/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/
<form name="paypalFrm" id="paypalFrm" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_ext-enter">
<input type="hidden" name="redirect_cmd" value="_xclick-subscriptions">
<input type="hidden" name="return" value="<?php echo $return_url;?>">
<input type="hidden" name="cancel_return" value="<?php echo $cancel_return;?>">
<input type="hidden" name="notify_url" value="<?php echo $notify_url;?>">
<input type="hidden" name="custom" value="<?php echo $custom.",".$custom2;?>">
<input type="hidden" name="business" value="<?php echo $business_id;?>">
<input type="hidden" name="item_name" value="<?php echo $item_name;?>">
<input type="hidden" name="item_number" value="1">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="a3" value="<?php echo $plan_amount;?>">
<input type="hidden" name="p3" value="1">
<input type="hidden" name="t3" value="M">
<input type="hidden" name="src" value="1">
<input type="hidden" name="sra" value="1">
<input type="hidden" name="srt" value="12">
<input type="hidden" name="first_name" value="<?php echo $txtname;?>">
<input type="hidden" name="lc" value="<?php echo $merchant_country;?>">
<input type="hidden" name="email" value="<?php echo $txtemail;?>">
</form>
Step 2 Create IPN controller. For detailed understanding review https://developer.paypal.com/docs/classic/ipn/gs_IPN/
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) { $_POST[$key] = mysql_real_escape_string($value); }
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
$header = '';
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen('www.sandbox.paypal.com', 80, $errno, $errstr, 30);
// assign posted variables to local variables
$content['payment_status'] = $this->input->post('payment_status');
$content['payment_amount'] = $this->input->post('mc_gross');
$content['payment_currency'] = $this->input->post('mc_currency');
$content['txn_id'] = $this->input->post('txn_id');
$content['receiver_email'] = $this->input->post('receiver_email');
$content['payer_email'] = $this->input->post('payer_email');
$custom = explode(",",$this->input->post('custom'));
$content['payment_id'] = $custom[0];
$content['type'] = $custom[1];
$content['txn_type'] = $this->input->post('txn_type');
$content['paydate'] = date('Y-m-d H:i:s');
if (!$fp)
{
// HTTP ERROR
}
else
{
fputs ($fp, $header . $req);
if (!feof($fp))
{
$res = fgets ($fp, 1024);
if(strcasecmp($content['txn_type'], "subscr_payment") == 0)
{
//Action
}
else if(strcasecmp($content['payment_status'], "Completed") == 0)
{
//Action
}
else if(strcasecmp($content['txn_type'], "subscr_cancel") == 0)
{
//Action
}
}
fclose ($fp);
}
$orderide = $this->checkout_model->user_order($order_table);
$business='paypal#business.example.com';
$cancel_url="http://".$_SERVER['SERVER_NAME']."/checkout/cancel?orderide=".$orderide;
$success_url="http://".$_SERVER['SERVER_NAME']."/checkout/success?order_id=".$orderide;
$data['payment_url']="https://www.sandbox.paypal.com/cgi-bin/webscr?business=$business&cmd=_xclick&item_name=$title&item_number=$product_id&amount=$totalamount&currency_code=EUR&return=$success_url&cancel_return=$cancel_url";
redirect($data['payment_url']);
In return success URL you can able to get the user id and payment amount
Step 1: Download the CodeIgniter PayPal library from here: https://github.com/nrshoukhin/codeigniter-paypal-library.
Step 2: Drag and drop the entire "application" folder from the library to your codeigniter project. Make sure it's not conflict with your existing files.
Step 3: Load the library from your controller construtor:-
public function __construct(){
parent::__construct();
$this->load->library("paypal");
}
Step 4: Open the file from "application/config/paypal.php". And provide your client ID, client secret and currency.
Step 5: Create a controller method like below:-
public function subscribe(){
if ( !empty($_POST["plan_name"]) && !empty($_POST["plan_description"]) ) {
$this->paypal->set_api_context();
$this->paypal->set_plan( $_POST["plan_name"], $_POST["plan_description"], "INFINITE" );
$definition = "Regular Payments";
$type = "REGULAR";
$frequency = "MONTH";
$frequncy_interval = '1';
$cycles = 0;
$price = "49";
$this->paypal->set_billing_plan_definition( $definition, $type, $frequency, $frequncy_interval, $cycles, $price );
$returnurl = base_url()."payment/success";
$cancelurl = base_url()."payment/cancel";
$this->paypal->set_merchant_preferences( $returnurl, $cancelurl );
$line1 = "Street - 1, Sector - 1";
$city = "Dhaka";
$state = "Dhaka";
$postalcode = "12345";
$country = "AU";
$this->paypal->set_shipping_address( $line1, $city, $state, $postalcode, $country );
$agreement_name = "Payment Agreement Name";
$agreement_description = "Payment Agreement Description";
$this->paypal->create_and_activate_billing_plan( $agreement_name, $agreement_description );
}
}
Here, set the frequency as "MONTH" and set the frequency_interval according to your desired recurring period.

How to get transaction details in notify_url page in paypal

In paypal notify_url page I am not getting any values when I use cmd value as _cart.How can I get the transaction details in notify_url page
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="POST" name="_xclick" id="paypal_form">
<input type="hidden" name="upload" value="1" />
<input type="hidden" name="cmd" value="_xclick" />
<!-- The business email address, where you want to receive the payment -->
<!--<input type="hidden" name="business" value="yesidealpayment#gmail.com" />-->
<input type="hidden" name="business" value="arun_1260247381_per#galtechsupport.us" />
<!-- The customer email address -->
<input type="hidden" name="item_name_1" value="<?php echo ucfirst($couponname); ?>" />
<input type="hidden" name="amount_1" value="<?php echo $total_payable_amount; ?>" />
<!--<input type="hidden" name="currency_code" value="AUD" />-->
<input type="hidden" name="currency_code" value="USD" />
<input type="hidden" name="amount" value="25.58" />
<!-- Where you want to return after PayPal Payment -->
<input type="hidden" name="return" value="http://yes-i-deal.com.au/test/paypal_ipn.php" />
<!-- A back-end notification send to the specific page after successful payment -->
<!--<input type="hidden" name="notify_url" value="http://yes-i-deal.com.au/test/paypal.php" />-->
<input type="hidden" name="notify_url" value="http://yes-i-deal.com.au/test/paypal_ipn.php" />
<!-- Where you want to return after cancel the PayPal Payment -->
<input type="hidden" name="cancel_return" value="http://yes-i-deal.com.au/" />
<input type="hidden" name="custom" value="<?php echo $coupon_id."_".$userid;?>" />
<input type="image" name="submit" src="http://yes-i-deal.com.au/themes/green/images/Buy-Now-Button.png" />
</form>
In my notify_url page I am getting values as
session_start();
require("ipn_cls1.php");
$paypal_info = $_POST;
print_r($paypal_info);
$paypal_ipn = new paypal_ipn($paypal_info);
$payment_status = trim($paypal_info['payment_status']); // Si Completed : tout est OK echo
$payment_amount = trim($paypal_info['mc_gross']);
i have same problem with paypal adaptive payments in my current project. i have given my
notify_url as http://mysite.com/payment-success. In this page, i simply coded
$request = $_POST;
mail('myid#myaccount', $request);
and then i sent the transaction result to my mail to view.
Note, here in my mail i can able to see the transaction results and if i insert into database, it is inserting but i cant see the transaction results in my page. Try sending to your mail the transaction results.
Create paypal_ipn.php file and place php code in it.
// Response from Paypal
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}',$value);// IPN fix
$req .= "&$key=$value";
}
// assign posted variables to local variables
$data['item_name'] = $_POST['item_name'];
$data['item_number'] = $_POST['item_number'];
$data['payment_status'] = $_POST['payment_status'];
$data['payment_amount'] = $_POST['mc_gross'];
$data['payment_currency'] = $_POST['mc_currency'];
$data['txn_id'] = $_POST['txn_id'];
$data['receiver_email'] = $_POST['receiver_email'];
$data['payer_email'] = $_POST['payer_email'];
$data['custom'] = $_POST['custom'];
$data['invoice'] = $_POST['invoice'];
$data['paypallog'] = $req;
// post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
////mail('atiftariq80#gmail.com','Step 9','Step 9');
$res = fgets ($fp, 1024);
if (true || strcmp($res, "VERIFIED") == 0) {
////mail('atiftariq80#gmail.com','PAYMENT VALID','PAYMENT VALID');
// Validate payment (Check unique txnid & correct price)
$valid_txnid = check_txnid($data['txn_id']);
$valid_price = check_price($data['payment_amount'], $data['item_number']);
// PAYMENT VALIDATED & VERIFIED!
if($valid_txnid && $valid_price){
//----------------- INSERT RECORDS TO DATABASE-------------------------------------
if ($data['invoice']=='basic') {
$price = 39;
} else {
$price = 159;
}
$this->user_model->update_user(
array(
'id' => $data['custom'],
'user_status' => 1,
'payment_date' => date("Y-m-d H:i:s",time()),
'next_payment_date' => date('Y-m-d', strtotime('+32 days')),
'user_package' => $data['invoice'],
'package_price' => $price
)
);
$data2 = array('id' => '',
'txn_id' => $data['txn_id'],
'amount' => $data['payment_amount'],
'mode ' => $data['payment_status'],
'paypal_log' => $data['paypallog'],
'user_id' => $data['custom'],
'created_at' => date('Y-m-d H:i:s',time())
);
$this->db->insert('tbl_paypal_log', $data2);
//----------------- INSERT RECORDS TO DATABASE-------------------------------------
}else{
// Payment made but data has been changed
// E-mail admin or alert user
}
} elseif ($res=='INVALID') {
// PAYMENT INVALID & INVESTIGATE MANUALY!
// E-mail admin or alert user
////mail('atiftariq80#gmail.com','PAYMENT INVALID AND INVESTIGATE MANUALY','PAYMENT INVALID AND INVESTIGATE MANUALY');
}
}
fclose ($fp);
}
There is a really good guide to Instant Payment Notifications (IPN) and understanding how they work. This guide provides you the steps you need to have your notify_url working properly.
There are good code samples provided by Paypal that do the validation response for you, which is really nice. You can use these are the starting point for your own.

Categories