how to integrate paypal with codeigniter? - php

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.

Related

Fail to send variables back to return address while Paypal payment

I am unable to get variables in my return address while paying with Paypal.
My form is like below:
<form action="<?php echo $ps_paypal_url; ?>" method="post">
<input type="hidden" name="business" value="<?php echo $ps_paypal_merchant; ?>">
<input type="hidden" name="notify_url" value="<?php echo 'http://'.$_SERVER['SERVER_NAME'].CONF_WEBROOT_URL. 'paypal-ipn.php'; ?>">
<input type="hidden" name="item_name" value="<?php echo 'For Order ' . $_POST['ORDER']; ?>">
<input type="hidden" name="user_name" value="<?php echo $_SESSION['logged_user']['user_id']; ?>">
<input type="hidden" name="quantity" value="1">
<input type="hidden" name="item_number" value="<?php echo $_POST['ORDER']; ?>">
<input TYPE="hidden" name="cmd" value="_xclick">
<input type="hidden" name="amount" value="<?php echo round($total_payable, 2); ?>">
<?php if($_POST['wallet'] > 0){ ?>
<input type="hidden" name="discount_amount" value="<?php echo round($_POST['wallet'],2); ?>" />
<?php } ?>
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="custom" value="<?php echo $_SESSION['logged_user']['user_id']; ?>">
<?php
$success = 'http://' . $_SERVER['SERVER_NAME'] . CONF_WEBROOT_URL .'success/;
?>
<input type='hidden' name='rm' value='2'>
<input type="hidden" name="return" value="<?php echo $success ; ?>">
<input type="hidden" name="currency_code" value="<?php echo CONF_CURRENCY_CODE; ?>">
</form>
In my return address I am trying to read for example item_name or amount. But no success so far. I beleive paypal is disabled this function and variables are not allowed to be posted to return address. In my return file I am trying to read the variables like below:
<?php
$amount = $_GET['amount'];
$amountpost = $_POST['amount'];
echo $amount;
echo $amountpost ;
?>
The result is empty. There is not any problem with ipn file once it is verified I am able to get the result with ipn file but why it is needed for me is because I need to add pending orderd in users purchase history. So when user will be redirected to success.php I will add pending order to account and once it is completed I will check via ipn and will change the status to "paid".
Any help would be highly appreciated.
PS: I don't want to send parameters in URL as $_GET parameters. I just want to get parameters of form.
First, please enable IPN explicitly after logging in your Paypal account and set the IPN url (e.g. set as http://www.yoursite.com/payment1234A.php)
Second, please remove notify_url from your form (to avoid hacking)
Thirdly, please add return and cancel_return url as hidden fields. For example:
<input type="hidden" name="return" value="http://www.yoursite.com/success.php">
<input type="hidden" name="cancel_return" value="http://www.yoursite.com/cancelled.php">
So, if you want to collect USD1000 , then the form to be sent to paypal should be like the following form:
Note:
I have added a javascript autosubmit so that the user does not need to click a submit button);
I have used the "custom" field to send a unique data, it can be something like [customerserial-transactionserial] so that your IPN script can use it to do your db update.
The minimum requested fields to be submitted in the form are:
business, item_name, amount, currency_code. For further details please refer to Paypal's official documentation.
<form id=form1 action="https://www.paypal.com/cgi-bin/webscr" method="post">
<!-- Identify your business so that you can collect the payments. -->
<input type="hidden" name="business" value="yourpaypalemail#yoursite.com">
<!-- Specify a Buy Now button. -->
<input type="hidden" name="cmd" value="_xclick">
<!-- Specify details about the item that buyers will purchase. -->
<input type="hidden" name="item_name" value="Purchase">
<input type="hidden" name="amount" value="1000">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="custom" value="<?php echo $_SESSION["checkcode"]; ?>">
<input type="hidden" name="return" value="http://www.yoursite.com/success.php">
<input type="hidden" name="cancel_return" value="http://www.yoursite.com/cancelled.php">
</form>
<script>
document.getElementById('form1').submit();
</script>
Finally, use (and customize if necessary) the following standard paypal IPN php script in your IPN link (e.g.payment1234A.php). Please note that the amount you submitted will be returned as $_POST['mc_gross'] (not $_GET['amount'] nor $_POST['amount']) . But the custom field will be returned as $_POST['custom'].
The file below : payment1234A.php
<?php
// STEP 1: Read POST data
// reading posted data from directly from $_POST causes serialization
// issues with array data in POST
// reading raw POST data from input stream instead.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
if (1==2) {
// STEP 2: Post IPN data back to paypal to validate
// only works if your IPN url is https, otherwise remark this block as 1==2
$ch = curl_init('https://ipnpb.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below.
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
}
// STEP 3: Inspect IPN validation result and act accordingly
if (1==1) {
// check whether 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
// 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'];
$custom = $_POST['custom'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
// <---- HERE you can do your INSERT to the database
if ( trim($payment_status)=="Completed" ) {
/// do whatever you want for successful transaction
}
}
?>

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.

Paypal IPN subscription (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"));

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.

How can I get posted data passed along when the user is first redirected through Paypal?

I've been trying to tackle this for some time now. I have an order page where the customer must enter information like name, address, etc. and some more unique fields. I have set up IPN with Paypal and the customer is redirected to the page I specified. But the data does not come along with it. I hope I'm asking my question properly so that I don't get "closed." Here is the HTML in the Paypal submit button that redirects to their page.
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="NT2YC6LP7SWBE">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_paynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<input type="hidden" name="child_name" id="child_name" value ="<? echo $child_name; ?>" maxlength="20"/>
<input type="hidden" name="age" id="age" value ="<? echo $age; ?>" maxlength="4"/>
<input type="hidden" name="hometown" id="hometown" value ="<? echo $hometown; ?>" maxlength="32"/>
<input type="hidden" name="boy_girl" id="boy_girl" value ="<? echo $boy_girl; ?>" maxlength="4"/>
<input type="hidden" name="first_name" id="first_name" value ="<? echo $first_name; ?>" maxlength="32"/>
<input type="hidden" name="last_name" id="last_name" value ="<? echo $last_name; ?>" maxlength="32"/>
<input type="hidden" name="email" id="email" value ="<? echo $email; ?>" maxlength="64"/>
<input type="hidden" name="address1" id="address1" value ="<? echo $address1; ?>" maxlength="64"/>
<input type="hidden" name="address2" id="address2" value ="<? echo $address2; ?>" maxlength="32"/>
<input type="hidden" name="city" id="city" value ="<? echo $city; ?>" maxlength="32"/>
<input type="hidden" name="state" id="state" value ="<? echo $state; ?>" maxlength="20"/>
<input type="hidden" name="zip" id="zip" value ="<? echo $zip; ?>" maxlength="10"/>
<input type="hidden" name="country" id="country" value ="<? echo $country; ?>" maxlength="32"/>
<input type="hidden" name="payment_type" id="payment_type" value ="paypal" maxlength="6"/>
<input type="hidden" name="paid" id="paid" value ="yes" maxlength="3"/>
<input type="hidden" name="mailed" id="mailed" value ="no" maxlength="3"/>
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
It has been pointed out to me that some of the variables are not "Paypal variables" and I can fix that later, but none of my data is making it back to my specified page after visiting Paypal, even the variables that Paypal supports like "city." Here is the PHP that I have on the page that they get redirected to.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
if (strcmp ($res, "VERIFIED") == 0) {
$child_name = htmlentities($_POST['child_name']);
$age = $_POST['age'];
$hometown = $_POST['hometown'];
$boy_girl = $_POST['boy_girl'];
$email = $_POST['email'];
$first_name = htmlentities($_POST['first_name']);
$last_name = htmlentities($_POST['last_name']);
$address1 = htmlentities($_POST['address1']);
$address2 = htmlentities($_POST['address2']);
$city = htmlentities($_POST['city']);
$state = $_POST['state'];
$zip = htmlentities($_POST['zip']);
$country = htmlentities($_POST['country']);
$payment_type = $_POST['payment_type'];
$paid = $_POST['paid'];
$mailed = $_POST['mailed'];
} else if (strcmp ($res, "INVALID") == 0) {
}
$query = "INSERT INTO customer_list (
number, child_name, age, hometown, boy_girl, first_name, last_name, email,
address1, address2, city, state, zip, country, payment_type, paid, mailed)
VALUES ('',
'".mysql_real_escape_string($child_name)."',
'".mysql_real_escape_string($age)."',
'".mysql_real_escape_string($hometown)."',
'".mysql_real_escape_string($boy_girl)."',
'".mysql_real_escape_string($first_name)."',
'".mysql_real_escape_string($last_name)."',
'".mysql_real_escape_string($email)."',
'".mysql_real_escape_string($address1)."',
'".mysql_real_escape_string($address2)."',
'".mysql_real_escape_string($city)."',
'".mysql_real_escape_string($state)."',
'".mysql_real_escape_string($zip)."',
'".mysql_real_escape_string($country)."',
'".mysql_real_escape_string($payment_type)."',
'".mysql_real_escape_string($paid)."',
'".mysql_real_escape_string($mailed)."')";
if ($query_run = mysql_query($query)) {
$subject = "Thank You for Your Order";
$message = "Thank you for placing your order with My-Letter-From-Santa-Claus.com. \n\nYou can expect to receive your personalized letter soon. Please make note of your customer number. Your customer number is: ".mysql_insert_id().". \n\nPlease send all inquiries to : info#my-letter-from-santa-claus.com";
$from = "info#my-letter-from-santa-claus.com";
$headers = "From:" . $from;
mail($email, $subject, $message, $headers);
echo 'Thank you for your order.';
echo 'Letter For '.$child_name;
} else {
echo mysql_error();
}
I copied most of it directly from x.com except for changing to my own variables of course. Nothing is getting posted to the database but that's not the issue since I cannot even echo the data. A couple things are being entered into the database but it's not the data from my order page - it is the first name and last name that is entered as the credit card info on Paypal, and for payment_type it says "instan" (I maxed it at 6 characters) but as you can see from the hidden input field in the HTML, I wanted to post the value "paypal." How do I fix this?
are you using the Paypal Sandbox for testing? If not, I strongly recommend it: https://developer.paypal.com/, and the manual: https://cms.paypal.com/cms_content/US/en_US/files/developer/PP_Sandbox_UserGuide.pdf.
I don't see the field name="business" in you code. That is the field which Paypal uses to identify you seller account. But maybe it only has to do with the "cmd" parameter (I use _xclick).
Here is a set of fields which works at this time for me, maybe it helps you:
<form name="_xclick" action="https://www.paypal.com/de/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="seller_email_here">
<input type="hidden" name="notify_url" value="ipn_url_here">
<input type="hidden" name="return" value="redirect_url">
<input type="hidden" name="cancel_return" value="redirect_if_cancelled_url">
<input type="hidden" name="amount" value="number_of_items">
<input type="hidden" name="currency_code" value="EUR">
<input type="hidden" name="item_name" value="product_name">
<input type="hidden" name="item_number" value="product_number">
Your problem is that you're using a hosted button. You can't include custom stuff in the general HTML for those. The only custom fields that can be included have to be done in the PayPal button creation wizard.
You also need to make sure you're not confusing IPN and PDT. If you simply want data to come back to your return URL that the user is sent to after completing payment that would be PDT. It's not recommended that you handle post-order-processing with this, though, because there is no guarantee the user will make it there.
IPN can be used for that because it will be triggered no matter what, but again, that's totally separate from your checkout and PDT.
I would highly recommend using Express Checkout instead of standard buttons since you seem to be familiar with PHP, too. I've got a PHP class library for PayPal that makes this very simple for you, and I can provide 30 min of free training if you need it, which is generally more than enough to get people up-and-running as long as you understand PHP and how to work with array data.
You can do it with Standard, too, but you'd have to move away from using a hosted button #AndreiHardau is showing. That would allow you to include additional fields like address1, address2, address_overide, etc, and those fields would then be returned in IPN, PDT, and in GetTransactionDetails.

Categories