Paypal ipn sent successfully but not insert into database - paypal

The previous day I tested paypal subscription with ipn. My button code is like this :
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_xclick-subscriptions">
<input type="hidden" name="business" value="yann#gmail.com">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="item_name" value="Small Plan">
<input type="hidden" name="item_number" value="1">
<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="http://192.168.0.144:90/Ecatalogue/plan/payment-successful.php">
<input type="hidden" name="cancel_return" value="http://192.168.0.144:90/Ecatalogue/plan/payment-cancelled.php">
<input type="hidden" name="src" value="1">
<input type="hidden" name="a3" value="22.00">
<input type="hidden" name="p3" value="1">
<input type="hidden" name="t3" value="M">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="bn" value="PP-SubscriptionsBF:btn_subscribe_LG.gif:NonHosted">
<input type="hidden" name="notify_url" value="http://192.168.0.144:90/Ecatalogue/ipn.php">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_subscribe_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
My ipn code is :
<?php
include("config.php");
global $DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME,$SERVER_PATH;
$con = mysql_connect($DB_HOST, $DB_USER, $DB_PASSWORD);
mysql_select_db($DB_NAME, $con);
// 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";
}
// STEP 2: Post IPN data back to paypal to validate
$ch = curl_init('https://www.sandbox.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 (strcmp ($res, "VERIFIED") == 0) {
// 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'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
mysql_query("INSERT INTO transactions (tran_plan) VALUES ('$item_name')");
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
?>
When I test on ipn simulator on paypal developer site, I got "IPN Sent Successfully ". But this not insert in database. In IPN history , the ipn status is "sent". If you have any solutions, please answer me as soon as possible.

Maybe you should use mysqli_query() ??
At least you can try ;)
Doc: http://www.php.net/manual/en/mysqli.query.php

Related

Which PAYPAL service is better for online transaction for website?

I am working on a website where users will have to pay to use some services. So I know that PayPal is the service I can use. User can pay with debit card, credit card, PayPal account etc. I know that PayPal button can be used for it. But in my website, I want to give user an option to add amount of their choice. User can pay $5 or $50,000 or anything they want. I don't know if I can use PayPal button or not for this.
In short user will enter amount in form. After submitting the form, it will redirect user to PayPal site where they can pay the amount. In return, I wanna make sure how much they have paid, and transaction was successful or not etc from PayPal so I can store details in database and if transaction was successful, user will get the amount balance in account.
So all I want to know is which service will be better for me from PayPal?
Like PayPal button or PayPal gateway or PayPal flow gateway?
I've done exactly this on my site. I'll post some code for it. Basically you create an input form that's not hidden, call it amount, so they user can enter the amount, then pass it to paypal. Paypal sites say it doesnt' work, but it does.
I used low end Paypal standard, not any of their fancier interfaces. I have the user add to cart then pay for the cart. But you can do the same for buy now buttons. It doesn't matter which paypal service you use. If it can be done with the basic paypal standard, you can do it with any of them...!
You can also get from paypal after the transaction, various aspects of what the user paid for. So there's a variable available for total amount, and individual amounts, and so on.
This is the key to setting up a donation amount for the user to input:
<input type="hidden" name="button_subtype" value="services">
and of course:
<b>Amount $: (Example: nnn.nn)</b>
<input type="text" name="amount">
I'm not as familar with the variables comign back from paypal. For what you want paypal standard should work from what I've read definitely. Here are the two ways to do it, and both work with paypal standard, so will work with any paypal:
This link Contains the two that follow below and also gives a brief overview.:
https://developer.paypal.com/webapps/developer/docs/classic/paypal-payments-standard/integration-guide/wp_standard_overview/
1)
https://developer.paypal.com/webapps/developer/docs/classic/paypal-payments-standard/integration-guide/paymentdatatransfer/
2)
https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNIntro/
Here's a body of code for the form.
<form target="_blank" action="https://www.paypal.com/cgi-bin/webscr" method="post">
value="https://www.yourwebsite.com/logo.jpg"> -->
<b>Amount $: (Example: nnn.nn)</b>
<input type="text" name="amount">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn /btn_cart_SM.gif" border="0" name="submit">
<input type="hidden" name="add" value="1">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="business" value="yours">
<input type="hidden" name="item_name" value="donation">
<input type="hidden" name="no_shipping" value="0">
<input type="hidden" name="shipping" value="0.00">
<input type="hidden" name="tax" value="0.00">
<!-- Replace value with the web page you want the customer to return to -->
<input type="hidden" name="shopping_url" value="http://www.yours">
<!-- services seems to be the trick -->
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="country" value="US">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="bn" value="PP-ShopCartBF:btn_paynowCC_LG.gif:NonHosted">
</form>
I recommended use a paypal express checkout. Here one simple (PHP) example:
// Parameters for SetExpressCheckout, which will be sent to PayPal
$padata['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Product description';
$padata['L_BILLINGAGREEMENTDESCRIPTION0'] = $padata['L_BILLINGAGREEMENTDESCRIPTION0'] .
' $'.$product->price.'/month';
$padata['L_PAYMENTREQUEST_0_DESC0'] = $padata['L_BILLINGAGREEMENTDESCRIPTION0'] .
' $'.$product->price.'/month';$padata['PAYMENTREQUEST_0_NOTIFYURL'] = 'http://site_url/paypal/ipn';
$padata['PAYMENTREQUEST_0_DESC'] = $product->name;
$padata['RETURNURL'] = 'http://site_url/paypal/returnurl';
$padata['CANCELURL'] = 'http://site_url/paypal/cancelurl';
$padata['PAYMENTREQUEST_0_CURRENCYCODE'] = 'USD';
$padata['PAYMENTREQUEST_0_PAYMENTACTION'] = 'SALE';
$padata['PAYMENTREQUEST_0_ITEMAMT'] = $product->price;$padata['PAYMENTREQUEST_0_AMT'] = $product->price;$padata['L_BILLINGTYPE0'] = 'RecurringPayments';$padata['L_PAYMENTREQUEST_0_NAME0'] = $product->name;$padata['L_PAYMENTREQUEST_0_NUMBER0']= '322';$padata['L_PAYMENTREQUEST_0_QTY0'] = '1';$padata['L_PAYMENTREQUEST_0_AMT0'] = $product->price;
$paypal_data = http_build_query($padata);
$httpParsedResponseAr = $this->PPHttpPost('SetExpressCheckout', $paypal_data);
//Respond according to message we receive from Paypal
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])){
//Redirect user to PayPal store with Token received.
$paypalurl ='https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token='.$httpParsedResponseAr["TOKEN"].'';
header('Location: '.$paypalurl);
}else{
echo 'Error : '.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'';
}
Page returnurl:
$hosteddata['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Description';$hosteddata['L_BILLINGAGREEMENTDESCRIPTION0'] = $hosteddata['L_BILLINGAGREEMENTDESCRIPTION0'] . ' $'.$pr->price.'/month';$hosteddata['L_PAYMENTREQUEST_0_NAME0'] = $pr->name;$hosteddata['PROFILEREFERENCE'] = $GetExpressCheckoutDetails['L_PAYMENTREQUEST_0_NUMBER0'];$hosteddata['PROFILESTARTDATE'] = date('Y-m-d') . 'T' . date('H:i:s').'Z';$hosteddata['SUBSCRIBERNAME'] = $GetExpressCheckoutDetails['FIRSTNAME'] . ' ' . $GetExpressCheckoutDetails['LASTNAME'];$hosteddata['TOKEN'] = urlencode($_POST['token']);$hosteddata['DESC'] = $hosteddata['L_BILLINGAGREEMENTDESCRIPTION0'];$hosteddata['AMT'] = $pr->price;$hosteddata['BILLINGPERIOD'] = 'Month';$hosteddata['BILLINGFREQUENCY'] = '1';$hosteddata['TOTALBILLINGCYCLES'] = '12';$hosteddata['REGULARTOTALBILLINGCYCLES'] = '1';$hosteddata['VERSION'] = '74.0';$hosteddata['MAXFAILEDPAYMENTS'] = '1';$hosteddata['L_PAYMENTREQUEST_0_QTY0'] = '1';$hosteddata['L_BILLINGTYPE0'] = 'RecurringPayments';$hosteddata['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Digital';$hosteddata['L_PAYMENTREQUEST_0_AMT0'] = $pr->price;$hosteddata['INITAMT'] = $pr->price;$hosteddata['L_PAYMENTREQUEST_0_NUMBER0'] = $pr->id;$hosteddata['PAYMENTREQUEST_0_NOTIFYURL'] = 'http://site_url/paypal/ipn';
$paypal_data = http_build_query($hosteddata);
$hosted_saas_response = $this->PPHttpPost('CreateRecurringPaymentsProfile', $paypal_data);
I used a separate method to post parameters to paypal
private function PPHttpPost( $methodName_, $nvpStr_ ) {
$api_username = 'yourpaypal#email.com';
$api_password = 'QWEQWEWQEQWEQEQWE';$api_signature = 'WQEQWEQWEQWEWQEQWEQWEQWEQWEQWE.cT';$api_endpoint = "https://api-3t.paypal.com/nvp";$version = '124.0';
$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $api_endpoint); curl_setopt($ch, CURLOPT_VERBOSE, 1);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$api_password&USER=$api_username&SIGNATURE=$api_signature&$nvpStr_";
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $api_endpoint.");
}
return $httpParsedResponseAr;
}

PayPal IPN: custom field not passing to IPN

I have a paypal buy button that looks like this:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="business" value="my#email.com">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="item_name_1" value="item1">
<input type="hidden" name="amount_1" value="3">
<input type="hidden" name="item_name_2" value="item2">
<input type="hidden" name="amount_2" value="5">
<input type="hidden" name="custom" value="Admin|2">
<input type="hidden" name="discount_rate_cart" value="5">
<input type="hidden" name="notify_url" value="paypal-ipn.php">
<input type="hidden" name="currency_code" value="EUR">
<input type="hidden" name="return" value="Thank-you-page">
<input type="hidden" name="country" value="SE">
<input type="submit" value="Checkout" id="checkoutButton">
</form>
And a IPN that looks like this:
<?php
session_start();
// STEP 1: read POST data
// Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
// Instead, read raw POST data from the input stream.
$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 IPN message sent from PayPal and prepend 'cmd=_notify-validate'
$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";
}
// Step 2: POST IPN data back to PayPal to validate
$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'));
// 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);
if(strcmp($res, "VERIFIED") == 0)
{
// The IPN is verified, process it:
// 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 the notification
// assign posted variables to local variables
$custom = explode('|', $_POST['custom']);
$user = $custom['0'];
$itemAmount = $custom['1'];
$item_name = "";
for($i = 0 ; $i < $itemAmount ; $i++)
{
$item_name .= $_POST['item_name_' . ($i + 1)] . '<br>';
}
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'] . ' ' . $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
$accstatus = $_POST['payer_status'];
include("../config.php");
$sql = "INSERT INTO `purchase` (`product`,`member`,`amount`,`ppmail`,`accstatus`,`status`)
VALUES
('$item_name','$user','$payment_amount','$payer_email','$accstatus','$payment_status')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$post_data_string = serialize($_POST);
mail('mail#domain.com', 'PayPal IPN', $post_data_string);
mysql_close($con);
// IPN message values depend upon the type of notification sent.
// To loop through the &_POST array and print the NV pairs to the screen:
foreach($_POST as $key => $value)
{
echo $key." = ". $value."<br>";
}
}
else if(strcmp($res, "INVALID") == 0)
{
// IPN invalid, log for manual investigation
echo "The response from IPN was: <b>" .$res ."</b>";
}
?>
Now why does not the custom field get passed on to the API?
I do get this in error logging, because custom[0] = "" and custom[1] does not exist:
HP Notice: Undefined offset: 1 in /home1/planetzi/public_html/firefallcrystite/action/paypal-ipn.php on line 79

PayPal IPN and PDT - Cannot get buyer postal address on return_url page or email

I am setting up a basic donation system and need to send a confirmation email to the client but cannot get the buyer postal address to show on return_url page of the website, or to show in the email to send to the client. The custom values for the taxpayer yes/no radio selects won't follow through either in the email. I am using a custom form on our website with fields to fill in the donation amount, name, address and if they pay tax (simple radio select.) Not sure if I'm using it right but I have both IPN and PDT settings on the site site and setup within the PayPal account.
Donation Form:
<form class="dsForm" name="details" action="https://www.paypal.com/cgi-bin/webscr" method="post" onsubmit="if ( !CheckForm() ) return false;">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" id="business" name="business" value="charityemail#internet.com">
<input type="hidden" id="item_name" name="item_name" value="Website Donation - Water">
<input type="hidden" name="notify_url" value="http://www.urltoipnscript.com/ipn.php">
<input type="hidden" id="item_number" name="item_number" value="3">
<input type="hidden" name="no_note" value="1">
<input type="hidden" id="currency_code" name="currency_code" value="GBP">
<input type="hidden" name="no_shipping" value="2">
<input type="hidden" name="tax" value="0">
<input type="hidden" name="bn" value="IC_Sample">
<input type="hidden" value="donation" name="custom">
<ul id="donate-form">
<li><label>Amount:</label>
<input type="text" id="amount" name="amount" value="25.00" size='9'>
<select id='currency' onchange='CheckCurrency()'>
<option value="GBP">GBP</option>
<option value="EUR">EUR</option>
<option value="AUD">AUD</option>
<option value="USD">USD</option>
</select>
</li>
<li><label>Program:</label>
<select name='program' id='program' onchange='ProgramChange();' >
<option value=''>Please Select</option>
<option id="education" value='4'>Education</option>
<option id="water" value='3' selected="selected">Water</option>
<option id="health" value='2'>Health Promotion</option>
<option id="community" value='18'>Community Based Projects</option>
<option id="sponsorship" value='8'>Child Sponsorship</option>
</select>
</li>
<li><label>Firstname:</label>
<input type='text' name='first_name' size='30' />
</li>
<li><label>Surname:</label>
<input type='text' name='last_name' size='30' />
</li>
<li><label>Address 1:</label>
<input type='text' name='address1' size='30' />
</li>
<li><label>Address 2:</label>
<input type='text' name='address2' size='30' />
</li>
<li><label>Town/City:</label>
<input type='text' name='city' size='30' />
</li>
<li><label>Postcode/Zip:</label>
<input type='text' name='zip' size='30' />
</li>
<li><label>Country:</label>
<select name='country' id='country' >
<option value='' selected='selected'>Please Select</option>
<option value='AL'>Albania
</option><option value='DZ'>Algeria
</option><option value='GB'>United Kingdom
</option><option value='US'>United States
etc...
</li>
<div id='ukTaxOptions' style='display:none'>
<label style="width:auto; margin-top:20px; margin-bottom:10px;font-weight: bold;" > Please choose an appropriate option below:</label >
<li>
<label style="width:auto" >
<input id='gbTaxPayer_1' name='gbTaxPayer_radio' type='radio' value='1' onchange="SetPayPalCustom('UK')" />
<input id="gbTaxPayer" name="gbTaxPayer" type="hidden" value="1" /> I am a UK taxpayer and would like to Gift Aid all donations I have made to Fields Of Life in the last four years and all donations I make in the future, until I notify you otherwise *
</label>
</li>
<li><label style="width:auto">
<input id='gbTaxPayer_' name='gbTaxPayer_radio' type='radio' value='' checked onchange="SetPayPalCustom('')" />I am not a UK taxpayer
</label></li>
<li><label style="width:auto">* I understand that I must have paid an amount of income tax or capital gains tax at least equal to the tax you reclaim on my donations</label></li>
</div>
<input type="hidden" name="hosted_button_id" value="hidden from stackflow">
<input type="image" src="http://www.hiddenfromsov.com/mybtn.png" border="0" name="submit" alt="PayPal — The safer, easier way to pay online.">
<li><img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif width="1" height="1" /></li>
</ul>
IPN Script:
<?php
$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";
}
$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)) ) {
curl_close($ch);
exit;
}
curl_close($ch);
if (strcmp ($res, "VERIFIED") == 0) {
// 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'];
$address_street = $_POST['address_street'];
$address_city = $_POST['address_city'];
$address_state = $_POST['address_state'];
$address_zip = $_POST['address_zip'];
$address_country = $_POST['address_country'];
$address_status = $_POST['address_status'];
$gbtax = $_POST['gbTaxPayer_radio'];
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
Code on success return_url page
//PDT
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-synch';
$tx_token = $_GET['tx'];
$auth_token = "I've copied this the paypal settings";
$req .= "&tx=$tx_token&at=$auth_token";
// 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);
// $fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
// read the body data
$res = '';
$headerdone = false;
while (!feof($fp)) {
$line = fgets ($fp, 1024);
if (strcmp($line, "\r\n") == 0) {
// read the header
$headerdone = true;
}
else if ($headerdone)
{
// header has been read. now read the contents
$res .= $line;
}
}
// parse the data
$lines = explode("\n", $res);
$keyarray = array();
if (strcmp ($lines[0], "SUCCESS") == 0) {
for ($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
// 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
$item_number = $_GET['item_number'];
$address12 = $_GET['address_street'];
$firstname = $keyarray['first_name'];
$lastname = $keyarray['last_name'];
$payer_email = $keyarray['payer_email'];
$amount = $keyarray['mc_gross'];
$payment_date = $keyarray['payment_date'];
$payment_status = $keyarray['payment_status'];
$payment_type = $keyarray['payment_type'];
$mc_currency = $keyarray['mc_currency'];
$transactionid = $keyarray['txn_id'];
$itemname = $keyarray['item_name'];
$address1 = $keyarray['address1'];
$address_street = $keyarray['address_street'];
$address_city = $keyarray['address_city'];
$address_state = $keyarray['address_state'];
$address_zip = $keyarray['address_zip'];
$address_country = $keyarray['address_country'];
$gbtax = $keyarray['gbTaxPayer_radio'];
echo ("<p><strong>Payment Details</strong></p>\n");
echo ("<ul>\n");
echo ("<li><b>Address</b>: $address12</li>\n");
echo ("<li><b>Item Number</b>: $item_number</li>\n");
echo ("<li><b>Donation Type</b>: $itemname</li>\n");
echo ("<li><b>Date</b>: $payment_date</li>\n");
echo ("<li><b>Name</b>: $firstname $lastname ($payer_email)</li>\n");
echo ("<li><b>Street Address</b>: $address1</li>\n");
echo ("<li><b>Town/City</b>: $address_city</li>\n");
echo ("<li><b>County/State</b>: $address_state</li>\n");
echo ("<li><b>Postcode/ZIP</b>: $address_zip</li>\n");
echo ("<li><b>Country</b>: $address_country</li>\n");
echo ("<li><b>Amount</b>: £$amount</li>\n");
echo ("<li><b>Payment status</b>: $payment_status</li>\n");
echo ("<li><b>Transaction ID</b>: $transactionid</li>\n");
echo ("<li><b>UK Tax Payer?</b> $gbtax</li>\n");
echo ("</ul>\n");
// send e-mail
$today = date("F j, Y, g:i a");
mail("charityemail#internet.com", "Donation made - $itemname", "A donation was made on $today \n Payment Details \r\n\r\n Donation type: $itemname \r\n\r\n Name: $firstname $lastname \n Amount: $amount \n Donator Email: $payer_email \r\n\r\n Address: $address1 \n $address_city \n $address_state \n $address_zip \n $address_country \r\n\r\n Payment date: $payment_date \n Payment status: $payment_status \n Currency: $mc_currency \n Transaction ID: $transactionid \n UK Tax Payer? $gbtax \n", "From: Charity Donation <charityemail#internet.com>");
}
else if (strcmp ($lines[0], "FAIL") == 0) {
// log for manual investigation
}
}
fclose ($fp);
At the moment all I need to get working is the address to show on the email, return_url page and PayPal website (currently says Postal Address: Not Specified.)
Are you entering in an address when testing? Try passing over the variable "no_shipping" and setting the value to "2", and see if this makes a difference. Also PayPal will not pass back variables/values that are not valid PayPal variables, meaning you would not be able to make up your own variables and pass them over.

paypal ipn and mysql

I'm struggling with this problem for some days now but with no success, I'm relatively
new to paypal ipn but have used it succesfully in the past few monhts, now maybe I'm
doing some silly mistake or paypal sandbox ipn server is unresponsible.
The payment is processed properly, the money goes from the buyer account to the seller but still no details are entered in the database.
So this is the html form code:
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="POST">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="sanboxselleremail">
<input type="hidden" name="item_name" value="Product">
<input type="hidden" name="item_number" value="1">
<input type="hidden" name="amount" value="15">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="lc" value="EN">
<input type="hidden" name="bn" value="PP-BuyNowBF">
<input type="hidden" name="return" value="http://mysite.com/testipn/">
<input type="hidden" name="cancel_return" value="http://mysite.com/testipn/">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="notify_url" value="http://mysite.com/testipn/ipn.php" />
<input type="submit" value="submit" />
</form>
And this is the ipn code that I found at paypal:
include('db.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 ('ssl://www.sandbox.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'];
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {
if($payment_status=='Completed'){
$paylog = $db->query("INSERT INTO....);
}
else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
}
fclose ($fp);
}
I've double checked everything, I know that you must post back all the variables so I checked them too. The sql syntax has no problems because I've tested it and it enters
the values to the database table I want.
Can you please take a quick look and please point any errors you might find?
Thank you.
This problem is costing me lot of time and stress... :(
Your code is outdated and doesn't include the HTTP 'Host' header, which is (now) required.
So with this code, it would never get back 'VERIFIED', but instead get a HTTP/1.1 400 'Bad Request' back from PayPal.
To fix this, simply change:
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
To:
$header .= "POST /cgi-bin/webscr HTTP/1.1\r\n";
And add:
$header .= "Host: www.sandbox.paypal.com\r\n";
Should you just wish to use updated sample code, you can find this at https://www.paypal.com/ipn/
hi it seems to me its blocked as dont regcongnise you when it trys to complete the process ,ive read alot of people are experiencing problems with the sandbox theres a thing on paypal that tells you about it brb ill find
easily solved you need a buyer sandbox account and a seller one do you have both sorry for my spelling hope this helps
use this to test it
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_testing_SBAccessing

Paypal Sandbox payment problem

I have the following post button that i use for paypal transactions:
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="my#email.com">
<input type="hidden" name="item_name" value="Item description">
<input type="hidden" name="item_number" value="1">
<input type="hidden" name="amount" value="00.30">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="bn" value="PP-BuyNowBF">
<input type="hidden" name="return" value="website.com/index.php" />
<input type="hidden" name="cancel_return" value="website.com/index.php" />
<input type="hidden" name="rm" value="2">
<input type="hidden" name="notify_url" value="website.com/ipn/ipn.php">
<input type="hidden" name="custom" value="user_id">
<input type="submit" value="upgrade" />
</form>
and the following code in ipn.php
<?php
include_once 'config.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 ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
$fp = fsockopen ('ssl://www.sandbox.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'];
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
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
mysql_query("UPDATE table SET column='1' WHERE column2='13'");
}
else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
}
fclose ($fp);
}
?>
when i click the upgrade button and pay, it doesnt show me a go back to the website button... but there is a go back to my#email.com button, which has a 10 sec delay and takes me back to my website... although it popups a warning about encrypted data, which i dont know what it is.
Also the query i use in ipn.php does not execute.I dont even know if it goes to ipn.php.
Regarding go back to "my#email.com", this could happen if the email you specified doesn't map to an account in the PayPal sandbox. Perhaps you're using your real email in the button instead of a sandbox account email?
Another possibility is that your test account at "my#email.com" is not a business account. If you have a business account it should reflect your business name instead.
As for not receiving the IPNs, the sandbox doesn't always do a great job at delivering IPNs on time, if at all. I'd actually suggest that you try integrating using Express Checkout instead of Website Payments Standard. Express Checkout is a little bit of a confusing dance initially but it is easy to implement after you try to understand it. Here's what I think is the best doc explaining how Express Checkout works:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_ECSimpleIntegration
And when you're ready to dive into the implementation you should look here:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_api_reference
The nice thing about using Express Checkout instead of relying on IPN is that you get to figure out the payment status the moment your user returns to your site, and you don't have to sit around waiting for the IPN to show up.
With Express Checkout you also get to override your business name with a custom "brand name" so you can use the same receiving PayPal account on different sites with different "brands".
Good luck!