PHP Paypal IPN Integration Class
This free PHP script provides a simple method to interface with paypal and the paypal Instant Payment Notification (IPN) system. It is not a complete system but a single PHP class allowing the PHP developer more control. Included in the zip file is a demonstration PHP script called paypal.php which shows the basic usage of the class.
This class handles the submission of an order to paypal as well as the processing an Instant Payment Notification (IPN). Including the demonstration file, the entire "paypal system" consists of just 2 PHP scripts. Once is the class and one implements the class.
Download:
paypal-1.3.0.zip
If you enjoy this free PHP script and want to show your support, you can throw me a couple of bucks using paypal. Any donation, even just a buck, is always appreciated.
Version History
- v1.3.0 [10.10.2005] - Fixed it so that single quotes are handled the right way rather than simple stripping them. This was needed because the user could still put in quotes.
- v1.2.1 [06.05.2005] - Fixed typo from previous fix :)
- v1.2.0 [05.31.2005] - Added the optional ability to remove all quotes from the paypal posts. The IPN will come back invalid sometimes when quotes are used in certain fields.
- v1.1.0 [05.15.2005] - Revised the form output in the submit_paypal_post method to allow non-javascript capable browsers to provide a means of manual form submission.
- v1.0.0 [04.16.2005] - Initial Version
171 Comments about "PHP Paypal IPN Integration Class"
RSS Feed
I implement recurring payment in paypal and working fine. My question is how a user of my site unsubscribe recurring payment subscription by using php script. Please help me.
Dhiraj
HI
I have added your class files namely paypal.php & paypal.class.php.
in that i have added the header image as -"image_url" even i have tried "cpp_header_image" but it displaying only the "dxxxxx@gmail.com" in the header,can you please get me idea to print UserName or logo image in the header of my paypal page
The following is the code i have used and i have attached the code along with this,
please get me the idea..
//$p->add_field('business', 'Jagbir');
$p->add_field('business', 'drbrar1979@gmail.com');
$p->add_field('custom',$_POST['email_txt']);
//$p->add_field('return', $this_script.'?action=success');
//$p->add_field('cancel_return', $this_script.'?action=cancel');
$p->add_field('notify_url', $this_script.'?action=ipn');
$p->add_field('item_name', 'Membership fees for IJSSPE');
$p->add_field('amount', '');
$p->add_field('image_url','http://ijsspe.com/ijsspe/ijsspe.png');
//$cpp_header_image = "http://www.esscentialalchemy.com/img/logo2.gif";
$p->add_field('cpp_header_image' ,'http://ijsspe.com/ijsspe/ijsspe.png');
With Regards
P.Sivasankar
otherwise it won't be recurring ;)
For monthly payments I added these fields:
// Make payment monthly
$p->add_field('reattempt', '1');
$p->add_field('recur_times', '1');
$p->add_field('recurring', '1');
$p->add_field('payment_period', "MONTHLY");
$p->add_field('a3', "{$SETTINGS['paypal']['emailtext_price']}");
$p->add_field('t3', "M");
$p->add_field('p3', "1");
$p->add_field('no_note', "1");
and of course in the paypal class use:
$this->add_field('cmd','_xclick-subscriptions');
instead of "x_click"
Cheers
Anybody know how to send values like Name, email, city, country, phone etc to populate the new account form on the paypal checkout page? I am taking billing and shipping address on my site only. just want to send the same to the checkout page so that the user won't have to fill it up again on that page.
Please help!
this is a nice script. i needed script to allow users to cancel subscription. how is that possible thru php codes. can you plz help me our in this??
$p->add_field('upload', 1);
and
$p->add_field('cmd', '_cart'); // you need this for multiple items
$p->add_field('txn_type', 'cart'); // you need this for multiple items
:)
as a user signs up (via a php based website), it checks them out via paypal, ONCE VERIFIED, it spawn a python script i'm writing that will setup their account, add their name, info to appropriate tables, activate their login and send them a welcome message confirming the info they have submitted.
each month, i will need to verify their subscription status to see if their account needs to be deactivated, reminders send, etc.
do you have such a script?
tia,
greg
mysql_select_db($database_mobile, $mobile);$query_Recordset1 = "SELECT * FROM invoice WHERE invoice.invoice= '$p->ipn_data[invoice]'";$Recordset1 = mysql_query($query_Recordset1, $mobile) or die(mysql_error());$row_Recordset1 = mysql_fetch_assoc($Recordset1);$totalRows_Recordset1 = mysql_num_rows($Recordset1);
Great script. Fairly straightforward and simple, yet comprehensive. I just sent you $5 via PayPal as a small token of appreciation for all of your hard work.
May I suggest that anyone asking Micah for help might want to give very a very detailed description of what they need help with, and throw a couple of bucks his way. This certainly took some work, and it takes a great deal of time to answer questions.
Im trying to get this script to work. What I need it to do is when I get the communication from paypal to say payment has been made I need the script to access a table in my database (QLS3_Users) and then update a field. The field to be updated would be the quantity but only for the user whos email address matches that was used in Paypal. I have tried the following SQL but it dont seem to work
$SQL= "UPDATE qls3_users SET quantity = 'quantity' WHERE email = 'payer_email'";
Any ideas?
http://forums.gplhost.com/phpBB2/image-vp2658.html
Your Reply helped me., but the solution you told is still not clear to me.,
I have found an easy solution to the recurring payment
You just need to add the following fields in your implementing code
$p->add_field('cmd','_xclick-subscriptions');
$p->add_field('sra', "1");
$p->add_field('a3', "$amount"); //here put the amount of subscription
$p->add_field('p3', "$month"); // here put the recurring payment duration
$p->add_field('t3', "M"); //here put the duration type like M for Month Y for Year
$p->add_field('currency_code', "USD");
Thank You
Kind Regards
Rishish Pandey
is it possible with this script make a refund transaction?
if possible...you have some example?
thank so much!
but i i want send in post my order id
and receive from paypal order ID
is possible or not ?
if user doesn't press return to original site
my script send mail and process result or not ?
because have 2 section
case 'success'
and
'ipn'
when user pay
paypal call my page for 'ipn'
and when press return to original site execute case 'success'
or not ?
thaks ;)
I found very useful ur class :D
Greetings from Argentina
I implemented this class in one of our corporate websites, and it just works perfect!
I did have some problems figuring out how to implement this in a wordpress plugin, and what the precise flow between order-actions / steps should be...
I did it like this:
1. Orderform
-- Validate Orderform
OR
-- Continue to "Review"
2. Reviewform
-- Submit to "Processing"
This saves all order data and
if payment method == "paypal", I echo the redirect form.
else step = "Success"
3. Success / Cancel
The same pages as where Paypal customers would be redirected to when coming back from Paypal.
Just added this little "scheme", hoping to help others!
Kind regards, and thanks again,
Kim
I am using you class. I am facing with problem ipn validation...
Here I want to update my database, but I am not able to update database. I hope my notify_url is not called by paypal. I checked ipn_log text file.....
What is problem I don't know . I hope you understand my problem....... Please give me reply as soon as possible
Thank You
Adarsh
How can I simply output the form data (not the ipn data) into the mail message?
thanks very much in advance-
-Adam F.
I m getting a problem, when the site goes live, i m receiving too many IPN emails (sounds paypal is hitting the script again and again) so my IPN code is executing too many time or each single order. I can see my custom variable it contain same primary key!
any idea why paypal is doing so, why its hitting the script many time? should i echo some thing in ipn part so that paypal can read some response from script and stop retrying?
but you suggested to do DB stuff in IPN validation part, but sometimes paypal sends IPN data multiple times and 4-5 or more data goes to DB, what about this ?
thanks
To all those who are asking silly PHP/MySQL/Paypal specific questions, please give Micah a break. This is code that Micah has given freely, if you want to use the code, do yourself a favour and read up on the PayPal HTML and IPN variable documentation. Also, I think its unreasonable to expect Micah to answer your PHP/MySQL related questions.
Thank you so much for such a great paypal code! I'm newbie in PHP and I was wondering if you could please tell me how can I get the variable 'payer_email' that the paypal.com site will send to my website to send the email to my customer.
I tryed the following code but no success:
mail ($p->ipn_data['payer_email'], $email_subject, $email_message, $headers))
Once again, thank you so much!!!
I hope you can answer my question: I run a newspaper and am looking for a way customers can place their classified ads online and charge it to their paypal or credit card account, then have the text of the ad forwarded to my email to be put in the paper's print edition. Is this what your script does, or do you know of one that does this that I can purchase ? Please reply to my email above.
Thanks, Dane Hicks
Publisher
The Anderson County Review
$inumber =1;
foreach($OrderContent as $items)
{
$p->add_field('item_name_'.$inumber, $items['pd_od']);
// $p->add_field('item_number'.$inumber, $SessionId);
$p->add_field('amount_'.$inumber, $items['od_id']);
$p->add_field('quantity_'.$inumber, $items['od_qty']);
$inumber++;
}
if i remove _'.$inumber then it ia taking one items details...but not show item list for multiple. Give me suggestion
I insert order details to DB before submitting to paypal, then on successful notification I want to update the order status field of my db. Im tryin the following:
mysql_query("UPDATE entries SET ORDERSTATUS = 'payment received' WHERE ORDERID='$invoice' ") or die (mysql_error());
The problem is that i can't cant get the value for the invoice number to select the relevant entry to update. Any pointers??
I am using your ipn script, its working fine for me, i am getting the mail, and my database gets updated. But the problem is that when a customer who has no account uses the paypal's direct credit card payment. the auto return does not work for it, so it does not return to my Websites Thank You Page. i have added my affiliate tracking code to the thanks page to sent the sale amount and other details to the affiliate. Unless it returns to the thanks page affiliate tracking doesn't work.
Can u pls help me
can i add that tracking script in the paypal.php file
can anyone help me to sort it out.....
mysql_connect("dsfdsfd","fdsfd","sdffd") or die("Unable to connect to database");
mysql_select_db("sfdsdb") or die("Unable to select database");
$sql="UPDATE payment SET payment.pay_received_amt='".$p->ipn_data['mc_gross']."', payment.paypal_txn_num='".$p->ipn_data['txn_id']."' WHERE payment.quoteNum='".$p->ipn_data['item_number']."'";
mysql_query($sql);
but if I use:
require_once('config.inc.php');
require_once('mysql.class.php');
require_once('order.class.php');
require_once('showorders.class.php');
require_once('customer.class.php');
require_once('paypal.class.php'); // include the class file
$p = new paypal_class;
$order= new Order($mysql);
and
if ($p->validate_ipn()) {
$quoteNum=$p->ipn_data['item_number'];
$payment=$p->ipn_data['mc_gross'];
$txn_id=$p->ipn_data['txn_id'];
$order->setPaymentStatus($quoteNum,$payment,$txn_id);
it does not get to sending out the IPN email.
Does anyone have any example of using an instance of an another class in the script?
Thank you in advance.
PayPal: I have a Premier account. I have enabled IPN and directed it to http://tools4fantasy.com/paypal.php
This includes a settings.php file. From what I understand, this is all I have to do in PayPal.
Hosting: This is where I think the problem may be. The server is using version PHP 5.4.2 I've tested the email using a contact page and that works fine. I don't know if there are any specific settings in the PHP configuration I need to check.
The class refers to an error log "ipn_log_file" but I haven't been able to locate this log. I have checked every directory via ftp but no joy.
I have spent 5 weeks using trial and error to resolve but just cannot get it to work. Any help would be greatly appreciated and would gladly make a donation.
The format required would be like this to get the correct headers in the email:
$From = "Firstname Lastname ";
The IPN info is coming back in the following:
email address:
$p->ipn_data['option_selection10']
Firstname:
$p->ipn_data['option_selection3'].
Lastname:
$p->ipn_data['option_selection1']
I hav made a hotel booking script. When the payment is complete and paypal confirms , I get a email which says status pending. Why is this.
Secondly , after the payment is complete i want to update my database. For this i want to update dates for which the booking has been made. I am storing the dates in variable called $to_date and $from_date. My problem is the data is not being passed from paypal and back to my site after payment confirmation.
PLS help.
firts of all thanks for your paypal class, it works great!
But i have one problem, anybody tried to use it with GoDaddy hosting? This script works just fine anywhere else, but not on their servers.
I've spent last 3 days trying all those solutions with curl, proxies, etc. AND still i can't get it working....
Guys, have anyone tried to implement this class at godaddy? Any advice would help because i'm getting crazy already..
ipn_data['payment_status'] = Completed if payment is successful
to get ipn from paypal when your code is on localhost, you should set your "return_url" field with your ip. something like http://localhost/.../paypal.php won't work because you're not localhost to paypal :) so do it like http://your IP/.../paypal.php and then it works. additionally, you may have to set DMZ Host thing on your modem.
@William
the ipn_data holds everythng that comes from paypal. so there's ipn_data['payment_status'] which is set to VERIFIED when the payment is complete.
____
by the way, the post variables that is sent to paypal via clicking paypal button can be altered/changed using some debugging tools. so you should check the details after the payment is complete.
this is important because you won't like the customer to pay 1$ for something that costs 100$.
so you could do 2 things to preserve yourself from fraud:
1) log the variables on buy button pressed and compare them with the ipn. post back the original values to paypal on ipn stage.
2) log the variables on ipn stage and check them after the verification is complete.
the point of doing these stuff is to make sure that the amount and the receiver is not changed.
good luck with your work everybody..
The custom field holds the uid of my customer (who is already in database)
a1, p1, t1 are the trial settings. In my case, $amount, 10, D(ays)
a3, p3, t3 are the subscription settings. Again, $amount, 1, M(onth)
Have Fun!
//////////////////////////////////////////////////
$p->add_field('first_name', $first_name);
$p->add_field('last_name', $last_name);
$p->add_field('custom', $uid);
$p->add_field('cmd', '_xclick-subscriptions');
$p->add_field('business', $paypal_mail);
$p->add_field('item_name', $item_name);
$p->add_field('no_shipping', '1');
$p->add_field('no_note', '1');
$p->add_field('currency_code', 'USD');
$p->add_field('lc','US');
$p->add_field('bn', 'PP-SubscriptionsBF');
$p->add_field('a1', $trial_amount);
$p->add_field('p1', '10');
$p->add_field('t1', 'D');
$p->add_field('a3', $subscription_amount);
$p->add_field('p3', '1');
$p->add_field('t3', 'M');
$p->add_field('src', '1');
$p->add_field('sra', '1');
$p->add_field('return', $this_script.'?id=scripts/paypal_ipn&action=success');
$p->add_field('cancel_return', $this_script.'?id=scripts/paypal_ipn&action=cancel');
$p->add_field('notify_url', $this_script.'?id=scripts/paypal_ipn&action=ipn');
$p->submit_paypal_post(); // submit the fields to paypal
//$p->dump_fields(); // for debugging, output a table of all the fields
break;
/////////////////////////////////////////////////
First time using IPN and your Class is the best I have found so far but there is something I just don't understand so any word of help would be great.
To me your suggesting that I should process the payment and insert it to database THREE times and I just dont get that at all!
1. The line, case 'ipn' in paypal.php: Your example already includes emailing and commented code suggests processing.
2. Then in checkpayment.php has this and also suggest processing the data...
$isPaid = $doCheck->checkPayment($_POST);
if($isPaid == true)
3. function checkPayment($_POST) in paypal.class.php also states that the payment should be processed.
All three indicate some sort of database or email activity but its totally confused me and I only see number 2 being the place to save to database and send emails.
Paypal cant communicate with your localhost during the ipn validation.
I only was wondering (like Sunil) if you coud (or sombady else) help me with the IPN.
The whole script (except the IPN part) works.
In the IPN I want to write a line in my database (I have checked that code and that works) but in the IPN is doenst places anything in the database. I also get no errors.
Even when i place the mysql_query outside the if ($p->validate_ipn()) { it wont work.
** I am testing on localhost **
i have installed the paypal-1.3.0 on localhost.on successful transaction success ins areturned.but "case:ipn" is not working at all.i ahve tried to echo some lines at the start of loop and after the "if ($p->validate_ipn()) {" ,but no line is echoed.any suggestions.what variables are to posted to make case:ipn working.thanks in advance.
I found your PayPal class from some forum. Thanks for making this.
// GET THE TOTAL PRICE
global $db;
$cart = $_SESSION['cart'];
$items = explode(',',$cart); // get the items from shopping cart
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$i=1;
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM shirts WHERE id = '.$id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$total += $price * $qty;
// now add the multiple items to ipn checkout
$p->add_field('item_number_' . $i, $i);
$p->add_field('item_name_'.$i, $row['title'] . ' - ' . $row['size']);
$p->add_field('quantity_'.$i,$qty);
$p->add_field('amount_'.$i, $price);
$i++;
}
$total_amount = $total; // my total price
$p->add_field('cmd', '_cart'); // you need this for multiple items
$p->add_field('txn_type', 'cart'); // you need this for multiple items
$p->add_field('upload', 1);
$p->add_field('payment_gross', $total_amount);
$p->add_field('num_cart_items', $i-1);
$p->add_field('business', 'jason_1204649129_biz@towerbridgetech.com');
$p->add_field('return', $this_script.'?action=success');
$p->add_field('cancel_return', $this_script.'?action=cancel');
$p->add_field('notify_url', $this_script.'?action=ipn');
$p->add_field('currency_code', 'USD');
// the old 1 item only version
/*
$p->add_field('item_name', 'My Good Luck Shirt');
$p->add_field('quantity', $qty);
$p->add_field('amount', $price);
*/
$p->add_field('custom', $referer); // my custom field
$p->submit_paypal_post(); // submit the fields to paypal
Hopefully you can figure it out because it has been a while since I've messed with this IPN script.
thank for given sript i use one site
I hope you can help. I'm a newbie in Pay Pal and trying to set up a 'Paypal Express Checkout', it seems that I've put every code in place, but when I test it, this message show up:
ACK=Failure&L_ERRORCODE0=81002&L_SHORTMESSAGE0=Unspecified%20Method&L_LONGMESSAGE0=Method%20Specified%20is%20not%20Supported&L_SEVERITYCODE0=Error
A clue would really help.Thanks
after successfull payment ,on clicking "Return to merchant" button it going to this page.
Then when the "success" case will be executed.I want to redirect the user to "thankyou.php" page after successful payment.Please help.
Also when the case "cancel" will beexecuted.Because when i click on the link "Cancel and return to ----", iam going to the page that i have specified with $p->add_field('cancel_return', $this_script.'?action=cancel');
Im new to programming and paypay ipn. I got the class to work and also update a database but I just cannot configure it to work with recurring/monthly subscription.
Can I get some help.
- a customer needs to verify his/her paypal account by transferring $5 to my paypal, so i created a buy button. but i assured my customer that after 5 days he/she will have his/her $5 refund. so he/she'll be hitting the buy button, access his/her paypal account, pay $5, then goes back to my website.
i'm already done with adding the buy buton & confirming the transaction, now here's the hard part: i want to use the PHP Paypal IPN Integration Class (paypal.class.php & paypal.php) to allow me to grab the Unique Transaction ID and the IPN after confirming the payment and goes back to my site...
I already read the "Website Payments Standard Integration Guide" and i already have the idea of its flow, but if you could provide like links and other resources that i could use with this that would be so cool... thanks in advance.
i am some problem i have included else condition like this.
the problem is paypal is constantly mailling me test data that i used months ago in sandbox even i have removed that.
the second thing is when today i got the error i got the mail of this ERROR.
it is not validating ipn it is going in else condition.
please let me know.
thanks.
if ($p->validate_ipn()) {
foreach ($p->ipn_data as $key => $value) {
$body .= "\n$key: $value";
}
require('reservation-letter.php');
mail($to,$subject, $body, $headers);
}
else{
$headers .= 'From: Estate400 ' . "\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
foreach ($p->ipn_data as $key => $value) { $body .= "\n$key: $value"; }
mail('--------------------','Error',$body, $headers);
}
Yes, the sample provided is just the starting point. You will need to add your own logic for ensuring the post back is valid and processing the data returned as outlined in the Paypal Integration Guide.
I don't have a "php shopping cart" on hand to send you. Sorry. This code is intended to be used by intermediate/advanced coders to more quickly implement their own shopping carts.
i.e. if ($p->ipn_data['payment_status'] =="Refunded") { do this} else { mark as paid }..
you can get other information from the return ipn_data, such as ascertaining whether something is a direct payment or an echeck.
1) $p->add_field('custom',$_SESSION['userid']);
2) $p->ipn_data['custom']
Is work, but how may this "custom field" i can setting , have already try another method
$p->add_field('custom1',$_SESSION['userid']);
$p->add_field('custom2',$_SESSION['userid']);
Is not work , just only setting "custom" is work fine , Can you help me ?
Thank you
Dick Leung
How can i solve that ? Hope you can help, thank you!
//=====================================================
if ($p->validate_ipn()) {
$subject = 'Instant Payment Notification - Recieved Payment';
$to = 'email@email.com'; // your email
$createdate=$p->ipn_data['payment_date'];
$bank = "PAYPAL PAYMENT";
$query = "INSERT INTO pay ( memberid, pay, bank, bankn, paydate ) values ({$_SESSION['userid']},$p->ipn_data['mc_gross']},'{$bank}','{$p->ipn_data['payer_id']}','{$createdate}' )";
mail($to, $subject, $query);
Plz anyone help me to get a simple example for paypal in php script... I have searched a lot of codes.. But yet I didnt get a clear idea in this... Plz someone help me to get a clear idea in paypal with a simple example... thanks for your timely help...
tino, try this:
echo $p->ipn_data['payer_email'];
echo $p->ipn_data['item_name'];
Iyas
Amila
really useful, helped me a lot.
May you gain more and more knowledge each day for the good work you done here.
Amila
I'm afraid I had problem with Invoice field, besides it has nothing to do with Micah's paypal class, it actually refers to IPN server that expects to receive a STRING variable in Invoice field (Check variable types here :
https://www.paypal.com/IntegrationCenter/ic_ipn-pdt-variable-reference.html
), if you are passing a number (INTEGER) to IPN using Invoice field try another structure for that like converting "1234" to "I-1234", then detach "I-" part when IPN calls your script, in that case it will work like a champ ;)
Good Luck ;)
Is there any other way of finding if an IPN message actually made it to my site outside of this code ? anything that I can see at my hosting providers logs ?
Please help
Regards
snthelion
Thanks for your code, it is pretty simple and organizes stuff well.
I am able to integrate this into my code, i am able to complete the transaction at the sandbox and get a success message, but where is the IPN message ? I can't see it, since it is sent by paypal i am guessing something should happen on my screen that shows "Thank you for your order.", am I missing something.
Since i was able to complete the transaction and got a success page, I am assuming I have setup thing right.
Please help
Regards
snthelion
Thank you
Thanks excellent article.
And the Money In Euro?
Thks
url : http://127.0.0.1/paypal.php?action=ipn
Error :
Notice: Use of undefined constant host - assumed 'host' in d:\web_project\www\paypal.class.php on line 162
Please Help my.
I tested it through sandbox and it was working just fine and I was receiving all IPN notifications through POST method from paypal... but now as soon as I've put it alive in real mode and testing it with my real paypal account, I find that after completing the transaction on paypal, paypal is redirecting the user to the main site and forwarding only a limited variables through GET while all variables are in the url... Also, it says... if you aren't redirected to the site in 10 seconds, click on the link below.... and the link carries those variables for transferring them to the site through GET method! I believe its insecure, but paypal is doing that right now in that way...
I'm getting the following material in the url from paypal to my thankyou.php page :
action=success&tx=0FS74310PM366620C&st=Completed&amt=0.02&cc=USD&cm=&item_number=&sig=v%2bUR5VjDGgEHjTLNxKnXcTv%2bMeNHXEdcF8RJCknrIkL2s1Mwqx1LMj%2bwyCS7t3Aqq8maca5mQVcqRq3Bdur3bJczFk48GbwIPOMCfGM2S4kvxYJ3nUCXCmaEDiHXy2T%2f8PNaphck4QwR7x3KLgWqpSzTIBYPhaLXneMmuHX%2b3D4%3d
All I can do is, store the VERIFIED IPN info in the database and tally it with the transaction id that I receive in the above link.
Now if someone tampers with the above info, there can be trouble to be addressed!
Is there any way to force paypal to send user back to the site at the end of transaction and forwarding all info using POST?
Please help!
Thanks.
Tracy.
Thanks.
newbei
Thanks.
When trying to reference these variables in the sendmail function of the IPN the variables are coming back blank. Am I doing somthing wrong?
Thanks
Gary
ok,, I may be not so coding savvy... but I don't quite get how to use your script or how to integrate it into a payment process...
Is there a file that would describe the implementation of the class a bit,, or am I missing something?
i used your code for single item i worked well, now i am working on shopping cart what changes required on the same code for multiple items plz. help me out
thanks
This class is not a shopping cart and is not a plug and play script. You need to understand PayPal and modify the fields you are sending to suit your application.
https://www.paypalobjects.com/WEBSCR-510-20080402-1/en_US/pdf/PP_WebsitePaymentsStandard_IntegrationGuide.pdf
Checkout page 161 in the above PDF. It lists all the variables and when to use them.
Hope this helps some people
Thank you for this, it is a great help for something I have always found to be very confusing. I think I have it all set up and working correctly, but I just wanted to check...
I'm sandboxing at the moment and have created a simple form that passes "item_name" and "amount" to paypal.php. This is processed and I'm sent to Paypal, I process my payment and then click the return to merchant link and I see the success page with all the variables. I also receive an email, but on both of these pages, "payment_status" is listed as pending. Am I doing something wrong? Is there a step I'm missing, or is that email all I should receive in confirmation from Paypal? Also, is there something in your script that I can alter to have the buyer automatically returned to my site without having to click the return to merchant link?
Thanks again for making this information available.
Rory
This is how I add multiple items:
After you have added all your fields to field array, loop through your items as below
This code assumes your items are in array $order_items. Read on to see how to create this. You will need to change the column names ("txt_item_name") to suit your mysql table where your items are stored
$number='1';
foreach ($order_items as $item)
{
$p->add_field('item_name_'.$number, $item['txt_item_name']);
$p->add_field('amount_'.$number, $item['int_item_amount']);
$p->add_field('quantity_'.$number, $item['int_item_quantity']);
$p->add_field('shipping_'.$number, $item['int_item_shipping']);
$number++;
}
To create the array $order_items I do the following:
// sql to pull items from your cart. Obviously you will need to change this to suit
$order_recordset_items = mysql_query("select * from tbl_shopping_order_details where tbl_shopping_order_details.int_order_id = '". $this->order_id ."'");
// add each item to the array
$order_items = array();
while ($item_row = mysql_fetch_assoc($order_recordset_items))
{
$this->order_items[] = $item_row;
}
}
This assumes your items are added added to your database in your shopping cart scripts
// GET THE TOTAL PRICE
global $db;
$cart = $_SESSION['cart'];
$items = explode(',',$cart); // get the items from shopping cart
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$i=1;
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM shirts WHERE id = '.$id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$total += $price * $qty;
// now add the multiple items to ipn checkout
$p->add_field('item_number_' . $i, $i);
$p->add_field('item_name_'.$i, $row['title'] . ' - ' . $row['size']);
$p->add_field('quantity_'.$i,$qty);
$p->add_field('amount_'.$i, $price);
$i++;
}
$total_amount = $total; // my total price
$p->add_field('cmd', '_cart'); // you need this for multiple items
$p->add_field('txn_type', 'cart'); // you need this for multiple items
$p->add_field('upload', 1);
$p->add_field('payment_gross', $total_amount);
$p->add_field('num_cart_items', $i-1);
$p->add_field('business', 'jason_1204649129_biz@towerbridgetech.com');
$p->add_field('return', $this_script.'?action=success');
$p->add_field('cancel_return', $this_script.'?action=cancel');
$p->add_field('notify_url', $this_script.'?action=ipn');
$p->add_field('currency_code', 'USD');
// the old 1 item only version
/*
$p->add_field('item_name', 'My Good Luck Shirt');
$p->add_field('quantity', $qty);
$p->add_field('amount', $price);
*/
$p->add_field('custom', $referer); // my custom field
$p->submit_paypal_post(); // submit the fields to paypal
Hopefully you can figure it out because it has been a while since I've messed with this IPN script.
Good luck!
This is really a cool script, but the only thing that I would like to know is how can I submit multiple items in one order.
Example
My cart contains two items
product: Mobile Phone
Quantity:1
price: $23
product: book
Quantity: 2
price: $32
Any help will be highly appreciated.
Regards,
Mustafa Jalil.
your script is nice and it's working well. but i have a problem. in your script there is switch case ipn. for example when any user click on the pay button on my website and the system goes to the paypal's site. then user input the information and then submit. i think ipn works in this stage i.e. when user pay the amount then paypal notify the ipn url that the paypemt is successed. but i don't get any notification. i set the notification url in the sandbox account and also set a url in the code. so i can't update the users database in backend cause i don't get any notification.
if u help me about ipn more then it helps me a lot.
1/ The user click the link 'Pay now' for example
2/ He is redirected to the file paypal.php (without action=anything). So in the file paypal.php, the action=process is automatically set with if (empty($_GET['action'])) $_GET['action'] = 'process'. Then the switch case structure matched the 'process' case
3/ The message 'you will be rederected...' appears and validate the form with your orders data
______________ Solution 1 _______________________
4/ Buyer pay the item and click 'Return to the store', which will get him to paypal.php?action=success as specified with $p->add_field('return', $this_script.'?action=success');
5/ PAYPAL CALLS paypal.php?action=ipn to validate the IPN (this is specified with $p->add_field('notify_url', $this_script.'?action=ipn');)
______________ Solution 2 _______________________
4/ The buyer, during the payment process, click cancel. Then he will be redirected to paypal.php?action=cancel
I'm using your script. It's working well. I'm running the script from my localhost. The payment is done successfully but I face problem to handle ipn response.I think the line of code ### if (empty($_GET['action'])) $_GET['action'] = 'process'; ### in the script paypal.php is not working properly.
I think the variable $_GET['action'] is always empty so it's assigned by 'process' and the case 'process' is executed only. Any other case ('success','cancel' and 'ipn') is not executed so there is not any ipn response.
Is there any solution of the problem ? I'll be grateful if you please reply me. Thanks in advance.
It is really a very simple script and run in a first try.
Thanks!!!!!!!!
$p->add_field('item_name1', 'White Bread');
$p->add_field('amount1', $total_amount);
$p->add_field('item_name2', 'Wheat Bread');
$p->add_field('amount2', $total_amount);
etc etc... Any help would be greatly appreciated.
i mean , how to configure the buy now button form to work with this script?
please help !
I'm italian, i speack english so and so. I have a problem, I can't update my database in Section 'ipn'
f ($p->validate_ipn())
{
// Payment has been recieved and IPN is verified. This is where you
// update your database to activate or process the order, or setup
// the database with the user's order details, email an administrator,
// etc. You can access a slew of information via the ipn_data() array.
// Check the paypal documentation for specifics on what information
// is available in the IPN POST variables. Basically, all the POST vars
// which paypal sends, which we send back for validation, are now stored
// in the ipn_data() array.
$updateSQL = sprintf("UPDATE utenti SET stato_account='1' WHERE id='$id'");
mysql_select_db($database_data, $data);
$Result1 = mysql_query($updateSQL, $data) or die(mysql_error());
foreach ($p->ipn_data as $key => $value) { $$key == $value; }
......
}
Thanks
Matt86
It does work for recurring payment too, the detail is that you have to change the
"$this->add_field('cmd','_xclick');" to "$this->add_field('cmd','xclick-subscription');" BUT "xclick-subscription" doesn't work when it is encrypted so the problem is not with the code, but with paypal.
What I suggest you to do is to create your own form and add return variable with the address
http://yourdomain.com/paypal.php?action=success
can anyone help me.
thanks for advnce
Not sure if it's still helpful, but from what I can see Derek needs to change this line:
foreach ($p->ipn_data as $key => $value) { $$key == $value; }
to this:
foreach ($p->ipn_data as $key => $value) { $$key = $value; }
Note the SINGLE equals sign instead of the double equals.
Huge error showing up with this class. One person made payment, and for some reason, it seems like the IPN keeps getting triggered. They paid only one time, but 15 entries have been created over the last 2 days.
Any ideas why?
Mark
If you put the payment bits back on your site.......
But it's moot, I guess, since I turned auto-return off and now those values get posted to the success page! Yay! So, subquestion: I can get $key -> $value combinations from paypal on the success page now. Is there any way to put them into variables? For instance, how to I turn the output of mc_gross into $mc_gross = value;?
Keep in mind, the success page and the ipn case are completely independent of one another. The success page is the page the user goes back to, the ipn page is a separate process which the paypal server requests--not the user.
Your code for the success case:
echo "SuccessThank you for your order.";
foreach ($_POST as $key => $value) {echo "$key: $value";}
echo "";
What I get back:
SuccessThank you for your order.
But I know the data is getting passed back, since I can receive emails via the ipn case that contain all the raw data parsed into table format. So I'm really at a loss.
However, I've run into a situation where everything works correctly (IPN sends email, Success outputs a Success message), but on the Success page, I am getting no values back.
It's almost as if the entire loop is being bypassed.
Any ideas why this might be?
I haven't worked with recurring payments, so I'm afraid I am of no help. However, this class just passes variables to paypal the same way any other form would, so it's hard to imagine that it wouldn't theoretically work. I believe some people have had success with recurring payments, though I don't have the specifics.
"Your IPN script should then post back a 200 OK response to prevent additional attempts by PayPal to post your transaction data. If PayPal does not receive the 200 OK response from your server, PayPal will resend the notification for up to four days."
I'll make a note to update my class.
I was reading your CLASS file. As the last transmission of data between paypal and your server I think we're suppose to send Response 200 Ok
This is the reason I was reading your class as I've alread a script that seems to be working.
Do you send the 200 ok? If so how do you do it?
I think the flow of info is Paypal ipn -> myserver -> postback all data to paypal -> verified sent from paypal to myserver (i do the checks) -> I send paypal 200ok
I'm not sure actually. Although it has been my experience that no, you cannot do that from paypal, I haven't used it in a couple years and have never used premium account or services.
can this script process the creditcard payment automatically, without any user intervention?
if not, is there a way to bypass the paypal front page? where you does not have to click on "Don't have a paypal account? use creditcard click here ..." and send the user directly to the billing info page ?
thanks
Thanks again for the great IPN handler you have made available to all. I was trying to use your code and so far, it was a success.
The only problem I am having is when I try to set up a recuring payment, so that the payment happens every month.
I have tried adding the varibles listed in the IPN documentation but I was unsuccessful
$p->add_field('username', $_POST['paypalemail']);
$p->add_field('business', $owner_paypal_email);
$p->add_field('return', $this_script.'?action=success');
$p->add_field('cancel_return', $this_script.'?action=cancel');
$p->add_field('notify_url', $this_script.'?action=ipn');
$p->add_field('item_name', $item_name.$_POST['login']);
$p->add_field('amount', $price);
//MY THREE VARIABLES FOR RECURING
$p->add_field('reattempt', '1');
$p->add_field('recur_times', '1');
$p->add_field('recurring', '1');
$p->add_field('custom', $_POST['login']);
$p->submit_paypal_post();
break;
I have also tried with
$p->add_field('a3', $price);
$p->add_field('t3', 'M');
$p->add_field('src', '1');
$p->add_field('sra', '1');
But same problem, a payment is possible but no "recurring payment" is set...
Pease help me out, I have been working on it for three days now and no one on the paypal community seems to be able to help.
Sincerely,
Ali
If it's still not working, make sure PHP is reporting errors to a text file and then check it for any PHP errors. You can write debugging information to this text file from within this script using something like:
trigger_error("Testpoint", E_USER_NOTICE);
Putting that towards the top of the script will tell you the script is getting called, putting it right within the IPN block will tell you it's getting called with an IPN from paypal, etc.
I am using your paypal class
paypal.class.php
It works very fine, but i want to change the currency to "GBP".
i add the following line for this
$p->add_field('currency_code','GBP');
but it wont works, i write this line above the amount variable.
Please tell me that how can i use "GBP" currency
thanks
waiting for your reply
Eshban
This script is very great!! It works perfect ... until when the customer's info (such as memo, Address ...) contains special characters such as (') quote, (") double quote, or (_) underscore.
Then, inside the paypal.php,
foreach ($p->ipn_data as $key => $value)
{
$body .= "\n$key: $value";
}
$body= addslashes("$body");
mail($to, $subject, $body, $headers);
the function "mail" stopped.
Please advise.
Could you please tell me what the problem is ???
$p->add_field('mc_currency', 'CAD');
thanks again
Ive written a Free digital downloads delivery script using your class. Any recommendations would be welcome.
You can check it out here
http://www.ngcoders.com/php/selling-digital-goods-with-paypal-ipn-and-php/
Thanks for the class.
Here is the complete ipn section:
if ($_GET['action'] == 'ipn')
{// Paypal is calling page for IPN validation...
// It's important to remember that paypal calling this script. There
// is no output here. This is where you validate the IPN data and if it's
// valid, update your database to signify that the user has payed. If
// you try and use an echo or printf function here it's not going to do you
// a bit of good. This is on the "backend". That is why, by default, the
// class logs all IPN data to a text file.
if ($p->validate_ipn())
{
// Payment has been recieved and IPN is verified. This is where you
// update your database to activate or process the order, or setup
// the database with the user's order details, email an administrator,
// etc. You can access a slew of information via the ipn_data() array.
// Check the paypal documentation for specifics on what information
// is available in the IPN POST variables. Basically, all the POST vars
// which paypal sends, which we send back for validation, are now stored
// in the ipn_data() array.
mysql_connect("localhost","ediblepr_dgomez","mozart123") or die("Unable to connect to database");
mysql_select_db("ediblepr_paypal") or die("Unable to select database");
foreach ($p->ipn_data as $key => $value) { $$key == $value; }
$qry="INSERT INTO paypal_table VALUES (0 , '$payer_id', '$payment_date', '$txn_id', '$first_name', '$last_name', '$payer_email', '$payer_status', '$payment_type', '$memo', '$item_name', '$item_number', $quantity, $mc_gross, '$mc_currency', '$address_name', '".nl2br($address_street)."', '$address_city', '$address_state', '$address_zip', '$address_country', '$address_status', '$payer_business_name', '$payment_status', '$pending_reason', '$reason_code', '$txn_type')";
mysql_query($qry);
}
}
Is *anything* getting into the database?
Looks like you had a suggestion for coding but it's not in your message?
along the lines of:....
thanks again
For troubleshooting that code, you will need to log the errors. Try the debugging log that is provided with the class, or setup php.ini to log errors and check the error log.
Here is what I tried so far:
foreach ($p->ipn_data as $key => $value) { $$key == $value; }
$qry="INSERT INTO paypal_table VALUES (0 , '$payer_id', '$payment_date', '$txn_id', '$first_name', '$last_name', '$payer_email', '$payer_status', '$payment_type', '$memo', '$item_name', '$item_number', $quantity, $mc_gross, '$mc_currency', '$address_name', '".nl2br($address_street)."', '$address_city', '$address_state', '$address_zip', '$address_country', '$address_status', '$payer_business_name', '$payment_status', '$pending_reason', '$reason_code', '$txn_type')";
mysql_query($qry);
Your help is greatly appreciated.
If you put the payment bits back on your site.......
Leave a Comment about "PHP Paypal IPN Integration Class"