January 2, 2024 5:04 am

How to Integrate Paypal Payment System in PHP & MySQL

I received a tutorial requests from my reader that asked to me how to implement payment gateway system with Paypal API. In this tutorial I want to explain how to work with Paypal Sandbox test accounts for payment system development and sending arguments while click buy now button. It’s simple and very easy to integrate in your web projects.

PayPalPaymennt

[wpdm_file id=18]DEMO

Step 1

Create a Paypal Sandbox account at https://developer.paypal.com/

Step 2

Now create test accounts for payment system. Take a look at Sandbox menu left-side top Sandbox->Test Accounts

PayPal1

Step 3

Here I have created two accounts Buyer (personal) and Seller (merchant/business)

PayPal2

index.php

Contains PHP code. Displaying products, product image, product name and product price. Here you have to give your business(seller) $paypal_id id. Modify paypal button form return and cancel_return URLs.

<?php
$paypal_url='https://www.sandbox.paypal.com/cgi-bin/webscr'; // Test Paypal API URL
$paypal_id='your_seller_id'; // Business email ID
?>
<h4>Welcome, Guest</h4>

<div class="product">            
    <div class="image">
        <img src="https://www.phpgang.com/wp-content/uploads/gang.jpg" />
    </div>
    <div class="name">
        PHPGang Payment
    </div>
    <div class="price">
        Price:$10
    </div>
    <div class="btn">
    <form action="<?php echo $paypal_url; ?>" method="post" name="frmPayPal1">
    <input type="hidden" name="business" value="<?php echo $paypal_id; ?>">
    <input type="hidden" name="cmd" value="_xclick">
    <input type="hidden" name="item_name" value="PHPGang Payment">
    <input type="hidden" name="item_number" value="1">
    <input type="hidden" name="credits" value="510">
    <input type="hidden" name="userid" value="1">
    <input type="hidden" name="amount" value="10">
    <input type="hidden" name="cpp_header_image" value="https://www.phpgang.com/wp-content/uploads/gang.jpg">
    <input type="hidden" name="no_shipping" value="1">
    <input type="hidden" name="currency_code" value="USD">
    <input type="hidden" name="handling" value="0">
    <input type="hidden" name="cancel_return" value="http://demo.phpgang.com/payment_with_paypal/cancel.php">
    <input type="hidden" name="return" value="http://demo.phpgang.com/payment_with_paypal/success.php">
    <input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
    <img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
    </form> 
    </div>
</div>

success.php

Paypal payment success return file. Getting Paypal argument like item_number. Paypal data success.php?tx=83437E384950D&st=Completed&amt=10.00&cc=USD&cm=&item_number=1

<?php
$item_no            = $_REQUEST['item_number'];
$item_transaction   = $_REQUEST['tx']; // Paypal transaction ID
$item_price         = $_REQUEST['amt']; // Paypal received amount
$item_currency      = $_REQUEST['cc']; // Paypal received currency type

$price = '10.00';
$currency='USD';

//Rechecking the product price and currency details
if($item_price==$price && $item_currency==$currency)
{
    echo "<h1>Welcome, Guest</h1>";
    echo "<h1>Payment Successful</h1>";
}
else
{
    echo "<h1>Payment Failed</h1>";
}

cancel.php

Paypal API cancel_return file.

<?php
echo "<h1>Welcome, Guest</h1>";
echo "<h1>Payment Canceled</h1>";
?>

 Step 4

When your web application test payment system workflow is completed. Change the form action development API URLs to original API URLs and give valid $paypal_id seller email id.

$paypal_url='https://www.sandbox.paypal.com/cgi-bin/webscr';
//to
$paypal_url='https://www.paypal.com/cgi-bin/webscr';

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

87 responses to “How to Integrate Paypal Payment System in PHP & MySQL”

  1. Gethin says:

    Very good tutorial so far but I have a small issue with it. I always get the Payment failed in the success page. This is because $item_price and $item_currency are empty. They are empty because the page doesn’t get redirected from the paypal page in 10 seconds like the demo , you have to click return to store and this brings you back to success.php with out anything for $_REQUEST to retrieve instead of success.php?tx=83437E384950D&st=Completed&amt=10.00&cc=USD&cm=&item_number=1. Hope you can help Thanks

    • Huzoor Bux says:

      Hello Gethin

      Auto Return is turned off by default.
      To turn on Auto Return:

      Log in to your PayPal account at https://www.paypal.com. The My Account Overview page appears.

      Click the Profile sub-tab.
      The Profile Summary page appears.

      Under the Setting Preferences column, click the Website Payment Preferences link. The Website Payment Preferences page appears

      Under Auto Return for Website Payments, click the On radio button to enable Auto Return.

      In the Return URL field, enter the URL to which you want your payers redirected after they complete their payments.

      NOTE: PayPal checks the Return URL that you enter. If the URL is not properly formatted or cannot be validated, PayPal will not activate Auto Return.

      Scroll to the bottom of the page, and click the Save button.

      • Ahesanali Suthar says:

        step-1 :Please sign in with your sandbox business account on
        sandbox.paypal.com

        step-2 : than go to profile my selling tool link

        step-3: refer image-1

        step-4 : refer image-2

        • Ramesh Singh says:

          sry to say but the pay pal does not return me auttomatically after payment all the settings are done….any other suggestion

      • jayden says:

        The Problem with this is, you have to enter a static url. I wonder how it is possible, to make the redirect go automatically to the page, one has entered in the form from begin with, that url, that you get redirected to, when click on the various “back to page” usw buttons. I would like to have this automatically, so users content can be activated after payment. Or does anyone here know another maybe better way to achieve this?
        Thx

  2. Sam says:

    Hi i followed this tutorial and your little extra bit about auto-return but the paypal still doesn’t either auto-return or pass along those variables and so keeps displaying the error message about the transcation not being completed. However when i check the actual test accounts in paypal the money has been transferred properly.

    • Huzoor Bux says:

      Hello Sam

      Auto Return is turned off by default.
      To turn on Auto Return:

      Log in to your PayPal account at https://www.paypal.com. The My Account Overview page appears.

      Click the Profile sub-tab.
      The Profile Summary page appears.

      Under the Setting Preferences column, click the Website Payment Preferences link. The Website Payment Preferences page appears

      Under Auto Return for Website Payments, click the On radio button to enable Auto Return.

      In the Return URL field, enter the URL to which you want your payers redirected after they complete their payments.

      NOTE: PayPal checks the Return URL that you enter. If the URL is not properly formatted or cannot be validated, PayPal will not activate Auto Return.

      Scroll to the bottom of the page, and click the Save button.

      • sam says:

        i have done this yet it still refuses to auto-return or to pass back the variables for the request[] to grab. Would you have any further suggestions?

  3. simm says:

    tutorial is super simple.
    i have a question, Do we need to have a merchant paypal account for accepting payments? and activating Return URL? or it can be done in personal account too?

    • huzoorbux says:

      Yes you can do this on your personal account. Return url is necessary if you want your customers return on your website back after payment. Its upto your application’s requirement.

      • simm says:

        I logged into my paypal personal account but the problem is When i go to Profile page i do not see these options

        Setting Preferences column

        Under the Setting Preferences column, click the Website Payment Preferences link

        that is why i asked my problem 🙁

  4. sudesh says:

    Hi,
    Can I know about paypal ID.. In sand box and real one.. is it. paypal login email..?

    • huzoorbux says:

      Its your login email on live.
      on sandbox your business id which you have created for testing as defined in Step 3.

      • Sanjeev says:

        HI @huzoorbux:disqus ! YOU THERE?
        Can you let me know how can we get parameters like tx and cc back on our website , as i have been trying the same from morning , and i cant get it .
        Please helo

  5. gayatri says:

    Even if return url is given,transaction id and other details not getting in the redirected page…

  6. rahul says:

    thank you!!!

  7. mittul chauhan says:

    can you show me how to make refund now ? how can i make the refund ?

  8. Tinny says:

    return url is given, but getting no transaction id and other details, please help me out

  9. CCAvenue payment integration php
    Integrating CCavenue payment gateway is simple
    We need a merchant id and working for implementing payment gateway

    check link
    http://www.codingprogrammer.com/tutorialdemo/php-tutorial/ccavenue-payment-integration-php/

  10. Shubham Jain says:

    Thanks.. its awesome article that you sharing with us. Thanks again

  11. mukesh says:

    sandbox i couldnt find menu test thing

  12. mahesh says:

    on success i m getting txt, amnt, tranction id values so it showing warning error

  13. anil says:

    hey iam not directly redirecting untill i click on “Return to facilitators accounts test store”

    if i click on only its goes to next page and saying that within 10sec redirect to page

    iam attaching files

    • huzoorbux says:

      Auto Return is turned off by default.
      To turn on Auto Return:

      Log in to your PayPal account at https://www.paypal.com. The My Account Overview page appears.

      Click the Profile sub-tab.
      The Profile Summary page appears.

      Under the Setting Preferences column, click the Website Payment Preferences link. The Website Payment Preferences page appears

      Under Auto Return for Website Payments, click the On radio button to enable Auto Return.

      In the Return URL field, enter the URL to which you want your payers redirected after they complete their payments.

      NOTE: PayPal checks the Return URL that you enter. If the URL is not properly formatted or cannot be validated, PayPal will not activate Auto Return.

      Scroll to the bottom of the page, and click the Save button.

      • anil says:

        hey iam facing a problm with return url iam not getting parameters to success.php
        in my local host
        and if i run in this file from my server
        iam getting this message
        Cannot GET /us/cgi-bin/www.(my server url)

        whats problem

  14. anil says:

    hey iam getting this message when i put in server

    Cannot GET /us/cgi-bin/www.(my server url)

  15. Paresh says:

    I am trying to many things but no one things go right please someone make new demo for new paypal

  16. Mr Long says:

    Notice: Undefined index: item_number in E:CTPvampwampwwwpayment_with_paypalsuccess.php on line 2

    Notice: Undefined index: tx in E:CTPvampwampwwwpayment_with_paypalsuccess.php on line 3


    help me.:(

  17. Jeet says:

    Hi i have integrated the paypal it is working fine with the sandbox account but with the live account the transaction id is not generated sir please guide me what may be the error

  18. Jeet says:

    jeet
    how to generate response code for error if transaction failed due to some reason .

    Thanks

  19. Umair Shah says:

    To All Who Are Not Getting The Data At Return URL or Any Type of Notices So PHPGang Needs To Update There Code To This Updated Code..it Works 100% You Just Need To Add This Field To Your Form As :

    And Then Update Your Code In success.php As :

    <?php

    $item_no = $_POST['item_number'];

    $item_transaction = $_POST['txn_id']; // Paypal transaction ID

    $item_price = $_POST['payment_gross']; // Paypal received amount

    $item_currency = $_POST['mc_currency']; // Paypal received currency type

    $price = '10.00';

    $currency='USD';

    //Rechecking the product price and currency details

    if($item_price==$price && $item_currency==$currency)

    {

    echo "Item No : $item_no”;

    echo “Item Transaction ID : $item_transaction”;

    echo “Item Price : $$item_price”;

    echo “Item Currency : $item_currency”;

    echo “Welcome, Guest”;

    echo “Payment Successful”;

    }

    else

    {

    echo “Payment Failed”;

    }
    ?>

    If anyone has any question can contact me at skype as : nicefellow1111
    I am online any time…! besides I am a Web Developer you can contact for any type of web development or custom PHP/MySQLi Script..!

  20. I am getting Payment Failed. But it is a successful transaction.
    And how can I replace “[email protected]”, this with my site name and image ?

  21. Haider Abbas says:

    Add following to your form fields and variables will be returned as $POST fields:

    This will work with both auto return on or auto return off.

    Hope this will help all those complaining variables were not returning.

    • Bhavin Vaghela says:

      quick and effective solutions 🙂

    • chetan S says:

      No POST back data will be sent on submit.php. PayPal returns data back to your site via what they call IPN. Its really just a callback to a URL you specify. You can set this URL via the variable notify_url you can send to PayPal. adding rm = 2 not a recommeded method.

  22. amit ranjan says:

    Notice: Undefined index: item_number in varwwwpayment_with_paypalsuccess.php on line 2
    Please reply soon

  23. Druva says:

    Hi All,
    I am getting payment failed but transaction was successful and not getting response to success.php
    Help??

  24. jim_paris says:

    Hi, you’ve done great job with this script. I need your help with the following error. TheTransaction is OK but always I receive “Payment Failed”. Please can you advice me what to do?

  25. kapil sharma says:

    i could not detail of success.php page plz hlp me how can get value on success.php page

  26. Avadhesh Bhatt says:

    very good code snippet for payment gateway..i try this first time as i am beginner to payment gateway ..and it was successful ….thanx php gang !!! really appropriated to your team .

  27. rushikesh says:

    Hi i have site where i get some money from one user’s paypal account in my paypal account and get response for it. IT working perfectly fine. from here i get the code for it. It is working 100% with perfection what i want.

    Now i want something different scenario, from admin site i want to pay some payment back to my customer as special discount back offer. When i log-in from my account and do transaction to my customer’s account it shows payment failed. what is solution for it?

  28. gufoe says:

    Are you kidding? You’re not even checking the autenticity of the transaction id, anyone could fake any transaction!
    At least you should say that it is missing, otherwise people will implement this and (surprise surprise) get hacked!

  29. gufoe says:

    Are you kidding? You’re not even checking the autenticity of the transaction id, anyone could fake any transaction!
    At least you should say that it is missing, otherwise people will implement this and (surprise surprise) get hacked!

  30. gufoe says:

    Are you kidding? You’re not even checking the autenticity of the transaction id, anyone could fake any transaction!
    At least you should say that it is missing, otherwise people will implement this and (surprise surprise) get hacked!

  31. amit says:

    Hi how can i send list of item on paypal please help me

  32. Arif Ali Mughal says:

    Ive noticed that for me when doing this with a business sandbox email I created, the parameters tx, amt and cc do not work. have they been changed by PayPal?

  33. Harshad Patel says:

    I have also same problem. Did you found any solutions? or please post solution phpgang.

  34. hello… is there a way to find tx paramater after the user submit the form from your index.php? basicly i need to know if i need this parameter to indentify the payment in success.php or cancel.php. Second question: can you describe parameters i need to submit in index.php form? item_number = product_number (in my site), credits? user_id = user_id (in my site), amount= product_price( in my site), handling? … thanks a lot

  35. Gourav says:

    it’s helpness

  36. Amol Navsupe says:

    hello nice article, but when i used your mail id it redirect correctly but when i used my email id it will not redirect. what is that error please explain me and one more thing i ON Auto Return checkbox.
    thanks.

  37. hemanth says:

    Currently PayPal accounts in India are only able to send payments. This recipient is not eligible to receive funds.

    can any one let me know how to resolve this.?

  38. hemanth says:

    how to change the button.??

  39. P Kalbi says:

    Hello Sir,
    your code is very nice but there is error.
    I change the product value by inspect element like a 10 to 1 that user pay only USD 1. That is the wrong.
    please give me your solution.

  40. mercy says:

    Hi,I keep getting these error kindly help
    Fatal error: Call to a member function fetch() on null in my index.php

  41. lchhieu says:

    I want divide Paypal Standard Payments to two separate accounts. thanks

  42. dasu says:

    Waste tutorials. It gives error everywhere.

  43. inf haris says:

    hi you have to active PDT first, here is there reference https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/paymentdatatransfer/ and it works for me

    hope it help

  44. Rishabh Gusain says:

    Do I have a great future with PHP ? or I should change my mind and should go with something like JAVA and C#

  45. gokul krishanan says:

    Thanks a lot I can understand very easily..

  46. rishiba pp says:

    how to send a mail using php in localhost with wamp server
    ?

  47. angeliestolle says:

    Interesting piece . Just to add my thoughts , people are searching for a Qualify for no cost adult electronic monitor tulare county form , We saw a blank version here http://goo.gl/pyR9G2.

  48. Nitin says:

    Hello
    In this PayPal example, where do we use these email ids – info_**[email protected] & info_**[email protected] ? What will be the value of $paypal_id ?
    thanks

  49. Anthony Francis Fernandes says:

    hello,
    i wanted to know if you could help me with the cancellation of the booking of which the payment is already done and get the payment back in the paypal account..

    Thanks.

  50. shail says:

    Hello,
    My Question is Send & Receive Payment is Workin On Localhost(Wamp Server)?

    Thanks,

  51. Joe says:

    Thanks a lot!

  52. Ashiq Nazir says:

    Hello Sir, I Have Completed my Feed Subscription but i am not able to Download Code Using my email id [email protected]

  53. Ghanshyam Sharma says:

    Please help me for

    Paystack payment getway

  54. imran ali says:

    hello sir how i can store all paypal’s value in database table after payment success i want store all value in my database table how i can do that

  55. Rajesh Kannan says:

    i implement this code in my project page only redirect nothing value show

  56. chetan S says:

    No POST back data will be sent on submit.php. PayPal returns data back to your site via what they call IPN. Its really just a callback to a URL you specify. You can set this URL via the variable notify_url you can send to PayPal. adding rm = 2 not a recommeded method.

    Note that IPN won’t work on “localhost” as it is invalid domain name for paypal server.

  57. Info says:

    Form field values can be modified on client side, thus resulting in possible transactions of 0.01 in total.

  58. Deep Web says:

    Thanks for clear demo.

  59. devendra says:

    not warking on localhot

  60. devendra says:

    hello sir i have test this exmaples in localhost but after payment done i have not getting all this

    $item_no = $_REQUEST[‘item_number’];
    $item_transaction = $_REQUEST[‘tx’]; // Paypal transaction ID
    $item_price = $_REQUEST[‘amt’]; // Paypal received amount
    $item_currency = $_REQUEST[‘cc’]; // Paypal rece
    please any help?

  61. Bindeshwar Kush says:

    Clear explanation, thanks for sharing.

  62. prajapati sanjay says:

    success.php file no get txtid, amount item name, not get?

  63. Dharmesh Chuahan says:

    123

Leave a Reply

Your email address will not be published. Required fields are marked *