How to Set Up PayPal Integration with PHP & MySQL

14 February, 2011

This post was last updated on Thursday 26th July 2018

PayPal is the most popular payment service on the web so being able to integrate your website with PayPal’s Instant Payment Notification Service (IPN) is essential if you need to process payments through your website.

There are 3 main parts to the PayPal IPN system:

  1. A webpage that initiates a request to PayPal to make a payment.
  2. A PHP page on your webserver that PayPal calls to notify you that payment has been made.
  3. A webpage that confirms the above payment and continues on to the next phase of your web application, such as a 'Thank You' page.

Parts 1 and 3 are accessible by customers on your website. Part 2 is only visible to PayPal.  The diagram below illustrates the interaction between your customer, PayPal and your website.

PayPal Interaction

The following steps break down each part of the process into easy to follow chunks, it is assumed that you have knowledge of PHP and MySQL.

Note

  • If you are not receiving the correct response from Paypal ensure that you are using the main test account (Verified Business Account) from your Paypal Sandbox account.
  • Also ensure that you are testing the Paypal IPN Script on an online webserver (Not MAMP, Xampp etc..) as Paypal requires a reachable 'return url', 'cancel url' and 'notify url'.

Step 1 – Setup PayPal Account

Sign up for a PayPal account if you don’t already have one. In order to use IPN, the Paypal account you are selling from must be a Business Account.

Once you have a registered PayPal account your account must be setup correctly to use IPN. Select 'edit profile' from your PayPal account and check the following settings.

  • Under 'My Selling Preferences' >> 'Getting paid and managing risk' >> 'Instant Payment Notification Preferences'
    • Set the IPN value to 'On'
    • Set the IPN URL to the PHP page containing the IPN code shown in steps 3 & 4 of this tutorial. (http://www.example.com/payment.php)
  • Under 'My Selling Preferences' >> 'Getting paid and managing risk' >> 'Block payments'
    • Block payments from users who pay with eCheque. (This is because these will not be instant payments)
  • Under 'account information' >> 'email'
    • Note down your primary email address. This email will be visible to users so make it a professional one. User's may feel apprehensive about sending money to an e-mail address with the domain 'hotmail.com' or 'Yahoo.com' etc...

Step 2 – Simple HTML Form

Your website must now send all the required values to PayPal so that the payment can be processed.

The following code example demonstrates a basic form that we will use to send the values:


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Paypal Integration Test</title>
</head>
<body>

    <form class="paypal" action="payments.php" method="post" id="paypal_form">
        <input type="hidden" name="cmd" value="_xclick" />
        <input type="hidden" name="no_note" value="1" />
        <input type="hidden" name="lc" value="UK" />
        <input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHostedGuest" />
        <input type="hidden" name="first_name" value="Customer's First Name" />
        <input type="hidden" name="last_name" value="Customer's Last Name" />
        <input type="hidden" name="payer_email" value="customer@example.com" />
        <input type="hidden" name="item_number" value="123456" / >
        <input type="submit" name="submit" value="Submit Payment"/>
    </form>

</body>
</html>

The business name, price, submit type, notify URL and other sensitive values will be sent during the next step.

A full list of the values to send can be found at the PayPal website under the title "A Sample IPN Message and Response".

Step 3 – The Request

The payment.php page will be used to handle the outgoing request to PayPal and also to handle the incoming response after the payment has been processed.

To make a request for payment we need to first build up the parameters and pass these to PayPal via the query string.

We need to pass the following values:

  • business - the email address of your PayPal account
  • item_name - the name of the item being purchased
  • amount - the price of the item
  • return - the address to return to after a successful payment
  • cancel_return - the address to return to after a cancelled payment
  • notify_url - the address of the payments.php page on your website
  • custom - any other data to be sent and returned with the PayPal request
// For test payments we want to enable the sandbox mode. If you want to put live
// payments through then this setting needs changing to `false`.
$enableSandbox = true;

// Database settings. Change these for your database configuration.
$dbConfig = [
    'host' => 'localhost',
    'username' => 'user',
    'password' => 'secret',
    'name' => 'example_database'
];

// PayPal settings. Change these to your account details and the relevant URLs
// for your site.
$paypalConfig = [
    'email' => 'user@example.com',
    'return_url' => 'http://example.com/payment-successful.html',
    'cancel_url' => 'http://example.com/payment-cancelled.html',
    'notify_url' => 'http://example.com/payments.php'
];

$paypalUrl = $enableSandbox ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr';

// Product being purchased.
$itemName = 'Test Item';
$itemAmount = 5.00;

// Include Functions
require 'functions.php';

// Check if paypal request or response
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])) {

    // Grab the post data so that we can set up the query string for PayPal.
    // Ideally we'd use a whitelist here to check nothing is being injected into
    // our post data.
    $data = [];
    foreach ($_POST as $key => $value) {
        $data[$key] = stripslashes($value);
    }

    // Set the PayPal account.
    $data['business'] = $paypalConfig['email'];

    // Set the PayPal return addresses.
    $data['return'] = stripslashes($paypalConfig['return_url']);
    $data['cancel_return'] = stripslashes($paypalConfig['cancel_url']);
    $data['notify_url'] = stripslashes($paypalConfig['notify_url']);

    // Set the details about the product being purchased, including the amount
    // and currency so that these aren't overridden by the form data.
    $data['item_name'] = $itemName;
    $data['amount'] = $itemAmount;
    $data['currency_code'] = 'GBP';

    // Add any custom fields for the query string.
    //$data['custom'] = USERID;

    // Build the query string from the data.
    $queryString = http_build_query($data);

    // Redirect to paypal IPN
    header('location:' . $paypalUrl . '?' . $queryString);
    exit();

} else {
    // Handle the PayPal response.
}

To construct the query string we assign the post data to an array that we then push some additional values to that we don't want to be altered by the post data. This way we can ensure that a user cannot manipulate the amount being paid or any other details that may be vulnerable. We then use http_build_query to convert the array to a query string and pass this to PayPal via the header.

Step 4 - The Response

We now want to handle the response from PayPal, this is the callback PayPal makes to our notify URL we configured earlier. We reassign the post response to a local variable and then verify the transaction is authentic and check we've not already processed this transaction before adding the payment to our database.

To do all this we want to add the following code to the else statement of our payments.php script.

// Handle the PayPal response.

// Create a connection to the database.
$db = new mysqli($dbConfig['host'], $dbConfig['username'], $dbConfig['password'], $dbConfig['name']);

// Assign posted variables to local data array.
$data = [
    'item_name' => $_POST['item_name'],
    'item_number' => $_POST['item_number'],
    'payment_status' => $_POST['payment_status'],
    'payment_amount' => $_POST['mc_gross'],
    'payment_currency' => $_POST['mc_currency'],
    'txn_id' => $_POST['txn_id'],
    'receiver_email' => $_POST['receiver_email'],
    'payer_email' => $_POST['payer_email'],
    'custom' => $_POST['custom'],
];

// We need to verify the transaction comes from PayPal and check we've not
// already processed the transaction before adding the payment to our
// database.
if (verifyTransaction($_POST) && checkTxnid($data['txn_id'])) {
    if (addPayment($data) !== false) {
        // Payment successfully added.
    }
}

To verify the authenticity of the response we call the function verifyTransaction. This will take the post data received from PayPal and validate this by making a curl request to PayPal with the transaction data received. If we get back the response VERIFIED then we know that everything is OK and can proceed to add the payment to our database.

The verifyTransaction function looks like this (it can be found in our functions.php file).

function verifyTransaction($data) {
    global $paypalUrl;

    $req = 'cmd=_notify-validate';
    foreach ($data as $key => $value) {
        $value = urlencode(stripslashes($value));
        $value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i', '${1}%0D%0A${3}', $value); // IPN fix
        $req .= "&$key=$value";
    }

    $ch = curl_init($paypalUrl);
    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_SSLVERSION, 6);
    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_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
    $res = curl_exec($ch);

    if (!$res) {
        $errno = curl_errno($ch);
        $errstr = curl_error($ch);
        curl_close($ch);
        throw new Exception("cURL error: [$errno] $errstr");
    }

    $info = curl_getinfo($ch);

    // Check the http response
    $httpCode = $info['http_code'];
    if ($httpCode != 200) {
        throw new Exception("PayPal responded with http code $httpCode");
    }

    curl_close($ch);

    return $res === 'VERIFIED';
}

Once the transaction has been verified and before we add it to our database it is a good idea to check that we've not already processed it. That's what our call to checkTxnid is going to do. This simply checks that the txn_id value from PayPal does not already exist in our database.

function checkTxnid($txnid) {
    global $db;

    $txnid = $db->real_escape_string($txnid);
    $results = $db->query('SELECT * FROM `payments` WHERE txnid = \'' . $txnid . '\'');

    return ! $results->num_rows;
}

This is also a good opportunity for you to add any additional checks you might want to put in place before accepting the payment on your site. For example, you might want to check the amount paid tallies with the amount you were charging.

Step 5 - Add the Payment

With the response from PayPal verified and any additional checks we want to make at our end complete it's time to add the payment to our database.

To store payment details in our database a payments table must be created. The following MySQL will create the payments table used in this example code.

CREATE TABLE IF NOT EXISTS `payments` (
	`id` int(6) NOT NULL AUTO_INCREMENT,
	`txnid` varchar(20) NOT NULL,
	`payment_amount` decimal(7,2) NOT NULL,
	`payment_status` varchar(25) NOT NULL,
	`itemid` varchar(25) NOT NULL,
	`createdtime` datetime NOT NULL,
	PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Then in our code we're calling addPayment to insert a payment into the database. This function looks like this:-

function addPayment($data) {
    global $db;

    if (is_array($data)) {
        $stmt = $db->prepare('INSERT INTO `payments` (txnid, payment_amount, payment_status, itemid, createdtime) VALUES(?, ?, ?, ?, ?)');
        $stmt->bind_param(
            'sdsss',
            $data['txn_id'],
            $data['payment_amount'],
            $data['payment_status'],
            $data['item_number'],
            date('Y-m-d H:i:s')
        );
        $stmt->execute();
        $stmt->close();

        return $db->insert_id;
    }

    return false;
}

Sandbox Testing / Going Live

PayPal Sandbox offers all of the functionality of PayPal, but uses "Fake accounts" created by the developer within the sandbox. You can create fake buyer and fake seller profiles, then test your PayPal integration through your development website. Sandbox accounts can be created on the PayPal Developer website for free.

When testing with the sandbox we use the www.sandbox.paypal.com URL. For live payments we need to use www.paypal.com. Our example code is configured to use the sandbox, but you can switch it to live payments by changing $enableSandbox to false, this will update the URLs used to communicate with PayPal.

Once the payment process is ready to be used by real customers you will need to disable the sandbox mode in the code.

That’s it; you’re ready to start taking payments online through your website.

PayPal Integration - Source Files

You can find the complete code for this integration on GitHub.

76 Comments

Vixka Studio
16th October 2017 at 9:16am

Wow, this article is so useful. I'm trying to make custom payment using Paypal. :)

Post reply
rama krishna
16th October 2017 at 9:16am

Hi, Its very cool code. I was successfully run the code. Thanks .

Post reply
Nick
16th October 2017 at 9:16am

Thank you for this, will be extremely useful. One thing though in the SQL, it says `itemid` int(6) varchar(25) NOT NULL, so which one is it? =)

I'm new to alot of this but int and varchar together return errors in the syntax and I'm guessing you can't have it as both?

Thanks again!

Post reply
Dan Lawson
16th October 2017 at 9:16am

Thank you for highlighting that error Nick. The correct data type should be varchar(25). The article and source code have been updated.

Post reply
Ranjit
16th October 2017 at 9:16am

Very Nice Document.

Post reply
riccardo
16th October 2017 at 9:16am

Hi Dan,
I'm new to this but finally I've found your article because sounds so useful for me.
I've a question: in your example do the customers have a paypal account or they can use even credit cards?
I my previous version (without the paypal feedback) I've simply linked the page "" in this way.
May I do the same putting the right paypal settings?
thank you in advance
Riccardo (Italy)

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Riccardo,
Customers do not need to have a Paypal account to purchase items using this system. They have the option to register and create an account or simply enter their credit/debit card details to complete the purchase.

Post reply
Riccardo
16th October 2017 at 9:16am

dear Dan,
I have another question.
I'm making a test using sandbox but when the paypal window payment appears the customer needs a paypal account, I mean .. he can't use a direct payment via credit card unless he makes a paypal account registration.
Any chances to configure params in order to avoid the paypal account registration?
thank you in advance

Post reply
Rob Petrie
16th October 2017 at 9:16am

@Riccardo (anyone else who wants to know more about using credit cards with PayPal):

Hate to say this, but PayPal doesn't let you submit credit card information directly via an API. You (e.g., the user) are ALWAYS taken to a PayPal interface at some point during the process.

If you are wanting to avoid having the user know you are using PayPal, you might want to consider AuthorizeNet, TrustCommerce.com or a similar payment gateway. Yes, they charge monthly fees, but depending on the volume of your transactions it may be worth it.

tim
16th October 2017 at 9:16am

That is not entirely correct, Rob. If you use THIS method of initiating a transaction (sending the payment request to PayPal via a link with variables) then you WILL have to make your payment on PayPal's site.
PayPal does offer other options (paid options) that allow you to process cards directly from your site, with underlying processes invisible to the user. Website Payments Pro (https://www.x.com/developers/paypal/products/website-payments-pro) is one such option.

Subramanyam
16th October 2017 at 9:16am

Really awesome work.Thanks a lot,this helped me very much.

Post reply
JoeBob
16th October 2017 at 9:16am

Trying to work with this in a test mode, but after filling in the form, I am taken to "payments.php" which displays all of the code in the browser window, rather than taking me to the paypal sandbox. It seems it's not running the PHP script, but instead displaying it. Any idea what I'm missing?

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi JoeBob, Are you testing this locally? If local then PHP requires a free service such as XAMPP or WAMP to run PHP pages.

Post reply
Shaun
16th October 2017 at 9:16am

Hey Dan, thanks so much for this article - developed a credit system using the IPN for my site in about an hour thanks to you!

Post reply
Dan Lawson
16th October 2017 at 9:16am

No problem, glad you got it working.

Post reply
Ashok
16th October 2017 at 9:16am

Hello Dan
How can I add multiple items in a paypal transaction? This should show multiple items in paypal payment screen.

Regards
Ashok

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Ashok,

To send multiple items to Paypal IPN you must first alter your HTML so that:

You can then pass through the Item Name and Item Number as follows:

You can also add 'amount1, amount2 etc..' to specify individual prices per item. These variables should then be added to the $querystring variable and passed to Paypal.

More details in the documentation.

Post reply
Shannon
16th October 2017 at 9:16am

Is _xclick/_cart paypal api variables or are they defined by the developer?

Post reply
Xahyd
16th October 2017 at 9:16am

Nice tutorial, but i didn't get where exactly the following 3 links are used. Please can you explain:

$return_url = 'http://example.com/payment-successful.htm';
$cancel_url = 'http://example.com/payment-cancelled.htm';
$notify_url = 'http://example.com/paypal/payments.php';

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hello.

The $return_url is used on line 42 'Append paypal return addresses'. This is a page on your web server that is displayed after the Paypal transaction is complete.

The $cancel_url on line 43 is a page on your web server that is displayed if the user cancel's the Paypal transaction from the Paypal window.

The $notify_url is the path of the payments.php page on your web server. In the example this is located within a Paypal folder.

Post reply
Xahyd
16th October 2017 at 9:16am

thnx for describing
i hav a prob with this code, when i make transaction using sandbox i m transfered to success page but my database is not updated according to it.
mean to say there is some prob in ipn section

Post reply
Dan Lawson
16th October 2017 at 9:16am

Do you have an example of the code you are using to update your database? If the Paypal IPN is returning back to your $return_url then this would assume the problem is with the database code.

Xahyd
16th October 2017 at 9:16am

thnx for quick reply.
actually i email my self and update record in db. if there is some problem with query, at least it must sent email.
may be code after the following lines didnot work:
if (strcmp ($res, "VERIFIED") == 0)

but i receive payment status "Completed" on success page.

Vikram
16th October 2017 at 9:16am

hi!

We are trying to send Unit Price and item number for multiple items to paypal. But everytime it shows grand total instead of unit price under the column of UNit price.

Any suggestions?

Vikram R

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Vikram, Do you have a demo online anywhere that I can view the problem. It sounds like you are missing out a required parameter in the query string that is being sent to Paypal.

Post reply
Dave
16th October 2017 at 9:16am

Hi,
Thanks for the great script

After the payement, i get this error

The requested method POST is not allowed for the URL

the return url into a https
is that the problem ?

Can you help ?

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Dave,

This sounds like you have set your $return_url to a .htm or .html page.

Try using a .php page as your $return_url.

Post reply
frz
16th October 2017 at 9:16am

Great tutorial Dan!

I'm using Paypal sandbox, after I submit the payment nothing happens, it just shows me the success page and does not update the database. Please help.

Thanks

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi,

Are you using the exact same code as posted in the example or have you changed it in some way?

To test if the updatePayments function has been reached you could add a mail function In before it is called.

You may also want to try testing online rather than locally as this can sometimes lead to unexpected errors.

Post reply
Taylor
16th October 2017 at 9:16am

I'm having the same problem. I used the exact same code, I just inserted my information for the database variables and paypal settings. I get the success page in paypal sandbox but nothing is added to my database. The only way I can get back to my site's success page is by clicking the "Return to Taylor's Test Store" link on the confirmation page. Is that what is supposed to happen? I'm pretty new to all of this so I could just be missing something. Please help

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Taylor

Can you confirm that you are testing the Paypal code on a live server that is reachable by Paypal IPN.

Taylor
16th October 2017 at 9:16am

I do have it uploaded to my live server which should be reachable by the IPN. is there a way to test if the server is reachable?

Isaac
16th October 2017 at 9:16am

Hi Dan, I love your tutorial!

However I have a couple questions to ask as I'm new to this.

I see that your payments.php is receiving $_POST['custom'] so does that mean that if I pass in at html it will return me 444 (if 444 is my customer ID in my website so that I can update him as paid)? Also can this system be used for subscription on paypal?

I also would like to know do we remove this two lines:
14 $item_name = 'Test Item';
15 $item_amount = 5.00;

when we are going to deploy it live?
Thanks

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hello Isaac,

The 'custom' variable can be any value that you wish to transfer between the payments.php page and the response from Paypal. In your case the ID 444 could be used to update the customer as 'paid'.

This system can be used for subscription payments however the sample code Is not currently set up to do so. You can view which extra parameters you need at the paypal website here.

The $item_name and $item_amount variables are to determine what the Paypal payment is for and how much. They can either be pre-set in the payments.php code or brought in dynamically (The user selects a product to purchase on the website).

Post reply
Isaac
16th October 2017 at 9:16am

Hi Dan,

Thanks for the clarification. Therefore so to speak I can just generate the code from paypal's website standard button and throws in those extra parameters in the html submission form ya? Just make sure at ipn handler and grab them

Post reply
Dan Lawson
16th October 2017 at 9:16am

That's right Isaac,

The paypal standard button is performing the same IPN request/ response as this sample code.

Kamaraj
16th October 2017 at 9:16am

Hi Dan,

I have implemented your code in to my Joomla website.
URL: http://singaporetamilwriters.com/wtwc/index.php/register-here/registration-form-locals

I have tested with sandbox many times. It was working fine.
When I am testing with PayPal actual account, payment is made, but the functions inside this
if (strcmp ($res, "VERIFIED") == 0) { } condition is not working.

if (strcmp ($res, "VERIFIED") == 0) {
/* Not working */
}
else if (strcmp ($res, "INVALID") == 0) {
/* Working */
}

Please help me.

Thanks in advance.
Kamaraj.

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Kamaraj,

Could you place the following debug code into your /payment-successful.php file:

This will output all the Paypal response variables. Could you confirm the [pending_reason]?

thanks.

Post reply
Jason Carroll
16th October 2017 at 9:16am

Hello Dan,

Thank you for this great tutorial, I have one question so far, step 3 and 4 have the same file name but different file content ? Not sure if I am missing something here.

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Jason,

The payments.php file is broken up into two parts for the purposes of explaining what each section does in this tutorial. If you open the sample files here it may become clearer.

Thanks.

Post reply
Jason Carroll
16th October 2017 at 9:16am

Thank you Dan.

Post reply
Joseph
16th October 2017 at 9:16am

Hi Dan,

I'm new to php. Is it possible to change the currency to MYR?

Thanks in advance.
Joseph

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Joseph,

To change the currency to Malaysian you would need to change the currency_code variable to MYR.

Post reply
Manjula
16th October 2017 at 9:16am

Thanks for your guide.... this document is clear and really helpfull

Post reply
riccardo
16th October 2017 at 9:16am

Dear Dan,
I'm experiencing a problem: the "fsockopen" fails (I did not change your example).
The paypal transaction is completed and successful. here is the $_POST variable

array(33) { ["mc_gross"]=> string(4) "5.00" ["protection_eligibility"]=> string(10) "Ineligible" ["payer_id"]=> string(13) "NUZDBE7UATCZG" ["tax"]=> string(4) "0.00" ["payment_date"]=> string(25) "04:49:15 Jul 06, 2011 PDT" ["payment_status"]=> string(9) "Completed" ["charset"]=> string(12) "windows-1252" ["first_name"]=> string(8) "Riccardo" ["mc_fee"]=> string(4) "0.52" ["notify_version"]=> string(3) "3.1" ["custom"]=> string(0) "" ["payer_status"]=> string(10) "unverified" ["business"]=> string(30) "info_1309859245_biz@zenweb.biz" ["quantity"]=> string(1) "1" ["payer_email"]=> string(19) "r.rrrrrr@gmail.com" ["verify_sign"]=> string(56) "AAPxdwqA6Qyxa8LzcNiBQOchbiL-AHCr7TjQpRrJ29bkB1Iqw0ozjV.o" ["txn_id"]=> string(17) "32978634XL760873V" ["payment_type"]=> string(7) "instant" ["last_name"]=> string(7) "Rossi" ["receiver_email"]=> string(30) "info_1309859245_biz@zenweb.biz" ["payment_fee"]=> string(0) "" ["receiver_id"]=> string(13) "JB58DVUF63N7A" ["txn_type"]=> string(10) "web_accept" ["item_name"]=> string(45) "Communication Conference Fee" ["mc_currency"]=> string(3) "EUR" ["item_number"]=> string(4) "K143" ["residence_country"]=> string(2) "IT" ["test_ipn"]=> string(1) "1" ["handling_amount"]=> string(4) "0.00" ["transaction_subject"]=> string(45) "Communication Conference Fee" ["payment_gross"]=> string(0) "" ["shipping"]=> string(4) "0.00" ["merchant_return_link"]=> string(44) "Torna al sito Riccardo Rossi\'s Test Store" }

thank you in advance
ciao
Rick

Post reply
George
16th October 2017 at 9:16am

How can I append other form values like Name, Email etc to the database. I am losing all the data once it gets redirected to paypal sandbox

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi George,

You would need to insert your form data into the database before the initial Paypal querystring is sent. The usual process is to insert the form data into the database, retrieve the ID of the newly inserted row then use this as the custom variable in the $querystring.

This will then be returned by Paypal so that you can query your database for the information.

Hope that helped,

Dan.

Post reply
George
16th October 2017 at 9:16am

Thanks Dan

Post reply
Madav
16th October 2017 at 9:16am

Hi Dan,

Sorry I'm new in e-commerce. In the code you gave us, when the paypal transaction has confirmed, the browser return to the payments.php but nothing happend. Just show a BLANK PAGE and the records did not insert in the database. No errors and no clues. Can you help me...? Thanks in advance.

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi,

The code has been updated with the changes listed at the top of the page. If you could try these and see if you are still having any problems.

Thanks

Post reply
Bill
16th October 2017 at 9:16am

Hi Dan,
Pretty good tutorial. I tried your script and it was doing fine all the way to payment successful page. I looked at my sandbox account and all the payments made are there. However, I am puzzled (extremely), why the database are not being updated. I tested it over 10 times, but no luck.

Thanks for your help..
Bill

Post reply
Bill
16th October 2017 at 9:16am

Hi Dan,
I'm sorry for double posts, but I really have to let you know that it is working on my side now.

Great script...thanks for your hard work..

Thanks,
Bill

Post reply
Bill
16th October 2017 at 9:16am

Hi Dan,
Just wondering, is there any way we can make this script to function handling membership payments?

Say, I have a mysql table | id | member | monthly_due | status | rec_date |. Member clicks on the pay now button to pay, and then script upgrades database to record payment made by member.

Just a thought :)

thanks,
Bill

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Bill,

You can pass any values through to Paypal using the 'custom' field. With this you are able to pass the member_id through to paypal using:

If the response from Paypal is then successful, you can update the membership table for that member_id.

Hope that helps,

Dan.

Post reply
Bill
16th October 2017 at 9:16am

Hi Dan,
Thank you very much for speedy reply. Yes, I will do as what you have suggested and post an update here.

Post reply
Aash
16th October 2017 at 9:16am

Hi Dan,

Mind blowing article indeed!!

Really appreciate your efforts in creating such an awesome article on paymentGateway Integration using paypal.

I am just wondering if you can please also supply the same in classic ASP?

Thank you!
Aash

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Aash, Thanks for the feedback.

Unfortunately I cannot provide an example in ASP but Paypal has a range of code samples in various languages, including ASP: https://merchant.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_code_ipn_code_samples

Post reply
Chris
16th October 2017 at 9:16am

Hi Dan,

This is an excellent tutorial I came across while looking for somethin entirely different. I've now bookmarked your site and will do doubt be a frequent visitor.

Top class mate, well done!

Post reply
Hengst
16th October 2017 at 9:16am

Hi Dan, I'm working on integrating your script and have it almost working however I'm having a problem with database being populated with "payment status pending".

Any ideas?

Post reply
Hengst
16th October 2017 at 9:16am

Nevermind my posts. everything worked. problem was the sandbox. created all new testaccounts and all was fine.

Post reply
Hengst
16th October 2017 at 9:16am

Hello Dan,

In the sandbox mode the request to paypal and back is ok but several identical database entries are created with payment status "pending".

Debugging gives me " Verified Responsedata = ". It looks like something is missing. but what?

Post reply
Jeremy
16th October 2017 at 9:16am

Nice one! Worked straight off.

Post reply
Anand
16th October 2017 at 9:16am

Dan, I have just one line to say "you are awesome!.". I have not seen any article explained this simple and easy to implement as you have done. Great work, it worked like a charm

Post reply
denish
16th October 2017 at 9:16am

Dan......
All are cooool here, awessome actly

but just one issue is that,
After payment success , my page is not redirecting to success-payment.php

:(

i am testing on sendbox's accounts..

Any suggestion

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Denish,

Try setting your success page to a .htm page rather than a .php page and see if that works.

Post reply
denish
16th October 2017 at 9:16am

thankx for quick reply
-----------------------------------------
:(
Noppp....

.htm, .html ... not working...
still page is not redirecting to success page...

and one more thing, i was forgot to ask...
that my else part (response part) is not working in payments.php...
after payment success, i didnt get any mail , not DB insertion of orders etc

have set mail just after ELSE
see,
----------------
}
else
{
//response part
mail($to........);
}
----------------

but m not getting any mail...

plz give suggestion...

thank you

Post reply
Jim
16th October 2017 at 9:16am

Hi..great tutorial. I am trying to allow my customers to pay any amount they want for a service with a minimum..for example, I want the user to pay what they feel like paying with as long as it is at least 5$..can I pass this to my paypal account in a way that won't let them change it? thnx!

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Jim,

You would simply need to have an input field on your initial form that could be a textbox or a select box, like so:

In your payments.php page that builds the $querystring you could do a php check to verify that the amount variable from the form is greater than or equal to 5.

You would then need to change $item_amount = 5.00; to reflect the user entered amount $_POST['amount'].

Hope that helps.

Post reply
Jim
16th October 2017 at 9:16am

I sort of snuck up on that same answer after some trial and error...thanks so much, you rock!

Post reply
Jim
16th October 2017 at 9:16am

Dan: I wonder if I can ask you another question..I modified the script so that the user inputs their own amount which is then passed onto the payments.php script by setting the amount equal to the $_POST from the form that asked how much they wanted to pay. It worked great...just like I wanted it to. I then made a few other changes and it stopped working so I went back to the file I had just been using and it no longer works! very strange! Any idea of how to figure out what is happening?

Post reply
Jim
16th October 2017 at 9:16am

Dan:

Is it sometimes not ok to use localhost in order to let the script find the database? I notice that when I use the actual server name provided by my hosting company, I can connect to my database, but not run the script..and when I use 'localhost', I can run the script it doesn't see the database..I'm totally baffled..!

Post reply
Murugan
16th October 2017 at 9:16am

Nice tutorial Dan Lawson

Post reply
Louis
16th October 2017 at 9:16am

Hello Dan,

Such an awesome tutorial, really. I was able to set it up and customize it in less than an hour. Only one thing I haven't been able to figure out: Is there any way to disable the registration when a user pays by Credit Card? Currently, he has to enter an E-Mail and password when entering his Credit-Card details, which bothers my client.

I have a verified business account and E-Mail and I set "Account Optional" in the PayPal-settings, yet the user still has to create an account when entering his CC-details. Anything that I missed?

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Louis,

Thanks for the feedback. PayPal should automatically allow you to pay by your PayPal account or credit card. This sometimes will only display the login box and no credit card details when there is a PayPal cookie set. Has the user tried refreshing their browser cache before making a payment?

Post reply
Dave
16th October 2017 at 9:16am

Hi Dan!

This is really very helpful. I am new to this and your explanation is awesome.

I was creating a small online application where users enter their email and the mobiles phone's IMEI number.

I want to know how to pass the email id and the the IMEI number to paypal and once the payment is successful I need to make use of the email and the IMEI number.

How can I be able to do that. Would you help me?

Thank you!

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Dave,

One option would be to pass the IMEI number into the initial $querystring using the custom parameter:

This could then be retrieved after the paypal payment using $_POST['custom'].

The e-mail address can also be retrieved using $_POST['payer_email'].

Alternatively you could pass both the e-mail and the IMEI number into the custom parameter:

You could then break this string into an array using:

Hope that helps.

Post reply
bhavesh
16th October 2017 at 9:16am

Hi Dan!

This is really very helpful. I am new to this and your explanation is awesome.

But one problem is that i don't know how to use this code in my website please help me.

Thanks

Post reply
Adeel Ishfaq
16th October 2017 at 9:16am

Hi Dan,

Nice tutorial man, awesome instructions, easy to learn paypal integration for a beginner through your article.

Thank You

Post reply
prasanth mathew
16th October 2017 at 9:16am

Hi Dan,
Very good tutorial.
thanks a lot.

Post reply
dran
16th October 2017 at 9:16am

hi, one question, can I test this scripts on localhost, using WAMP

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi dran,

I would test the script on a live server rather than WAMP.

Paypal requires a reachable return URL rather than a local file.

Post reply
Amar
16th October 2017 at 9:16am

Hi Dan,great job.I have integrated paypal.All going well.After payment had done payment-successfull.htm is also showed.But i have a problem that the values are not inserted into database although i have already created a table.I don't have any clue why this is happening.Please help me..
Thanks in advance.....

Post reply
Amar
16th October 2017 at 9:16am

And I have another problem in paypal account Payment status shows Unclaimed.

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Amar,
Can you confirm that you are using a verified Paypal Business account and testing on a live server?

Both these are needed to receive a Verified status.

Post reply
Amar
16th October 2017 at 9:16am

Hi Dan,
I am using verified Paypal personal account and testing on localhost.That might creating the problem for status.Is it also creating for the database problem i.e. data not inserted into database?

Post reply
Amar
16th October 2017 at 9:16am

And i have another problem is that when i changed to [value="_cart"] it detects error .I don't understand why this is happening.Thanks in advance...

Dan Lawson
16th October 2017 at 9:16am

PayPal requires a reachable server for the resquests and responses. Try uploading your website to a live server and try then. Let me know if you have any problems.

Amar
16th October 2017 at 9:16am

Thanks DAN,I uploaded in a live server then i got the problems solved.But when i changed to [value="_cart"] it detects error .
Thanks,thanks........

Post reply
matvinculado
16th October 2017 at 9:16am

Awesome! :)

Post reply
piplin
16th October 2017 at 9:16am

So useful!!
You are my saviour in the issue!!
Very thanks!! ^_^

Post reply
Juan
16th October 2017 at 9:16am

Thank you very, very much, this is very helpful, I couldn't find a decent tut for my 'paypal' problem, and this one simply rocks ;)

thnx from Spain

Post reply
matvinculado
16th October 2017 at 9:16am

hi, im working on my integration now, the payment is working well however the newly added row line from database is not being updated.

please help me:

//get transactions number fo id.
$transactions=mysql_query("select paypal_payment,cashsense_payment from transaction_numbers");
$trow=mysql_fetch_array($transactions);
$pppayment=$trow["paypal_payment"];

$tnid=$pppayment + 1;
$ppuid='PP'.number_pad($tnid,20);

//update webstatus of user
$tnudpate = mysql_query("UPDATE transaction_numbers SET paypal_payment = '".number_pad($tnid,20)."' ");
$newpayments = mysql_query("INSERT INTO payments VALUES('','" .$ppuid. "','no','PAYPAL','" . $current_date . "','".$userid."','".$_POST['bpbuycredits']."')");

/ Append querystring with custom field
$querystring .= "&custom=".$ppuid;

//from other on dataupdating after the payment

// Validate payment (Check unique txnid & correct price)
$valid_txnid = check_tn($data['custom']);
// PAYMENT VALIDATED & VERIFIED!
if($valid_txnid){
$orderid = updatePaypalPayments($data);
if($orderid){
// Payment has been made & successfully inserted into the Database
$updateBPPayment = ("UPDATE payments SET successfulpayment='yes' WHERE paymentid='".$data['custom']."' ");

}

hope you can help me, i have my own id's not using txn_id. and it will be also a great help if you can give some code how to insert the txn_id before redirecting to paypal.

thanks :)

Post reply
matvinculado
16th October 2017 at 9:16am

never mind my last post got it working, honest mistake, forgot mysql_query :)

thanks and very great post :)

Post reply
Bulbul
16th October 2017 at 9:16am

Really great tutorial Dan !!

Post reply
Dave
16th October 2017 at 9:16am

Hey Dan!

This one worked like a charm. But the problem is after the payment is made it does not automatically redirect to the payment-success.htm page.

They should click on go to the store's page on the paypal page in order to get redirected.

Can you help me how to get them redirected automatically?

Thank you!

Post reply
marc
16th October 2017 at 9:16am

Hi Dan,
first of all thank u for ur great tutorial.
Anyway .. got a problem using sandbox.

Anything is working - I mean the transaction is done correclty - but
fsockopen returns $errstr = "Success" so the code cannot continue.
Could be a sandbox problem?

$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

if (!$fp) {
// HTTP ERROR
mail('marc.stefan1968@gmail.com', 'fsockopen error', $errstr);
} else {
#continue
}

thank you in advance
Marc

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Marc,

Is your Paypal IPN code on a live server that can be reached by Paypal (not a localhost testing server) ?

Thanks

Post reply
marc
16th October 2017 at 9:16am

Hi Dan,
thx for your reply.

Yes it is. It's a regular domain (linux + MySQL under Apache)

Post reply
marc
16th October 2017 at 9:16am

hi Dan,
I don't want to stress u but I really need to solve this issue.
The $errno returns 0 and the $errstr returns "success", so apparently the fsockopen works. May I consider as successful the value 0 and Success intead of if (!$fp) { } ?
thank you again
MArc

Sandy
16th October 2017 at 9:16am

Thanks for this tutorial, it is amazing! Just what I was looking for. Once quick questions, do you have to pass over the customer details (address fields etc)? I am looking for a solution that will simply have a "pay via paypal" button at the end where the user goes off to paypal and just signs in. It seems pointless to send over the address details when they can be obtained from paypal? I'm just thinking of convenience for my customers.

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Sandy,

No you don't need to send the address fields to Paypal. You can get the customers address details from the Paypal $_POST response instead.

Thanks.

Post reply
Eric
16th October 2017 at 9:16am

How would you code this so that you can insert any additional variables into the database? There are several other form details that I need to add, but I can't get it to work via a $_POST

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Eric,

You have two options:

Either insert the data into the database before the request is sent off to PayPal and set the status to 'paid' on a successful transaction.

You could also pass the variable through in the Custom field like so:

You can then retrieve these values after payment by:

Hope this helps.

John Milton
16th October 2017 at 9:16am

Hi Dan!

Your tutorial is really amazing. The code works perfectly. Just wanted to know if the customers can be redirected automatically after payment to the success page without click on "Return to customer site".

Is there a way to accomplish this? If yes, how can I do make the customers automatically redirect?

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi John,

Thanks for the feedback. There is a way to accomplish the automatic redirect but it has to be set in the Paypal admin interface.

Here is a quick guide on how to do it: https://www.paypal.com/cgi-bin/webscr?cmd=p/mer/express_return_summary-outside

Post reply
John
16th October 2017 at 9:16am

I just tried the auto redirect method Dan. But the auto redirect dont pass the custom variable values back to success page. The success page doesn't grab the variables when I switched the auto redirect button "on" in paypal options method.

If I dont use that auto redirect the variables can be grabbed and displayed. So, Can you tell me who can I pass them using the auto redirect method.

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi John,

When the success page is live you will need to use the $_REQUEST array to retrieve your data as Paypal changes the method to GET rather than POST.

Try echoing out:

on your success page to see the variables.

dheeraj
16th October 2017 at 9:16am

Hi best article. This is very use full.
Will you suggest about the tax and other charges in paypal.

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi dheeraj,

You can view the full list of variables to be sent to Paypal here:

https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_IPNandPDTVariables#id091EB04C0HS__id0913D0J01O8

Post reply
Modular
16th October 2017 at 9:16am

Awesome tutorial - brilliantly elaborate and extremely practical code without any error (testing on local server, Xampp at the moment - hopefully on live server would be fine.) Your post made my day and save lots of time. Keep up your excellent work.

Merry Xmas and Happy New Year 2012, everyone :)

Post reply
rich
16th October 2017 at 9:16am

hello mate is there any way possible to pass the whole shopping cart to paypal, got something working but its only passing one item to paypal

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Rich,

Yes you can pass the whole shopping cart through to Paypal.

Look here for the 'item_name x' variable.

Post reply
kiko
16th October 2017 at 9:16am

Hi,

What if I am going to use paypal.com instead of sandbox.paypal.com? I want to integrate the real paypal into my website. Thanks in advance!

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi,

You would simply need to remove 'sandbox' from the URL in payments.php

Post reply
param
16th October 2017 at 9:16am

Thanks a lot man.

Post reply
Sandy
16th October 2017 at 9:16am

Hi Don,
Nice Tutorial, I really appreciate. I Have a bit problem. This error is appear wen we click on Submit payment button. Do you Have any idea ?
Thanks for Suggestion.
Warning: Cannot modify header information - headers already sent by (output started at /home/unleashs/public_html/payment/payments.php:1) in /home/unleashs/public_html/payment/payments.php on line 51

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Shandy,

It sounds like you have a debug 'echo' somewhere in your code. Try debugging each line until you find the problem echo.

Thanks

Post reply
Unni
16th October 2017 at 9:16am

Hello Dan...
Just went through your tutorial. And its very nice and clear. Thanks. Now I am about to try it in real.I have a doubt.1> If i select Personal account then is it possible for my customers to pay via debit card? or is Premier account must for this?
2> Is there any pros or cons between them?
3>If i am setting up a small buy option without much buyers and no much huge transactions then which should i opt for.

I Googled it up but it totally confused me. :-( It would be very helpful if you could clear this thing. :-)
Thank you Dan...

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Unni,

Thank you for your comments. To use PayPal's IPN service you must either have a Premier or Business account. These are free to set-up but charge a small percentage fee per transaction.

Hope that helped.

Post reply
John
16th October 2017 at 9:16am

Thank you for this useful information. It helps a lot.

^_^

Post reply
Mint
16th October 2017 at 9:16am

Hello Dan!

Excellent work, just like what i've been looking for, I need to do up a paypal integration with my school project, and i found this! :D

Anyway, really appreciate this effort, and it works for me, I tried in sandbox mode, all the way until the payment is made, the redirection are good,but it did not update my database, did not insert into my payments table and it did not notify me on the page when the payments are made, do you have any idea where is the portion i should look for to edit the codes for notifications to the user when they made a payment?

Thanks in advance :)

Mint

Post reply
edgar
16th October 2017 at 9:16am

Great article about paypal integration. Thanks for this article!!. :)

Post reply
Sebosa
16th October 2017 at 9:16am

Hi
Your tutorial is really very interesting.I want a help..i have created a subscribe button from paypal account and placed it in my website.I would like to use this button to subscribe and pay the amount by the user and return back to my website with an id because i want to save a flag status if he /she pay to my DB.

Post reply
Çağlar
16th October 2017 at 9:16am

Very usefull article, thanks for writing it ^^

Post reply
Sergio
16th October 2017 at 9:16am

For those who wish to submit multiple items to paypal cart, this article could be a good friend. https://www.paypal.com/cgi-bin/webscr?cmd=_pdn_howto_checkout_outside

Post reply
Sergio Felix
16th October 2017 at 9:16am

Hey Dan,

Just wanted to thank you for this amazing resource my friend.

By far the best article I've seen on integrating PayPal with PHP&MySQL, hope I can make it work now! ;-)

Sergio

Post reply
Rob
16th October 2017 at 9:16am

Hi Dan, brilliant guide !!

Could I ask you or anyone of how I can get the "custom" field data back from when a buyer clicks (cancel) to bring them back to my site (cancel_return). The data isn't in the POST data. ($_REQUEST['custom'])...?

Post reply
Paul Angelo Silvestre
16th October 2017 at 9:16am

Hi Dan! great tutorial! i just need something.. i ran this code perfectly and it worked perfectly.. but the thing is.. after a successful payment, it will go back to my website.. but, it doesnt update a value from my website.. like for example.. in my website i got 0 points.. and to have a point/s i need to pay like $3 for 5 points.. what i would like to do is.. after a successful payment.. i will be redirected to my site having the 5 points.. thanks!

Post reply
Lakshman
16th October 2017 at 9:16am

Hii..

The article is really awesome, thanks for posting. very useful

Post reply
Ian.J.Gough
16th October 2017 at 9:16am

Magic!
Works like a dream and is very easy to modify and understand. Thank you for writing and sharing your code.
Ian

Post reply
Likhit
16th October 2017 at 9:16am

Hi Dan Lawson,

Thanks for this great article,
I am working on a php project where i need to integrate paypal. I am trying out your code for the same. But I am stuck at the request line: if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])), can you please tell me where are you setting "txn_id" and "txn_type". Please reply at the earliest, need to role out on production at the earliest.

Post reply
Ganesh
16th October 2017 at 9:16am

Thank you dude

This document is very useful :)

Post reply
Daniel
16th October 2017 at 9:16am

Hi, Is there any way using this script to output the item purchased (i'm using a buy now button with options like 1 month, 2 moths 3months)

Thanks

Post reply
Geoff
16th October 2017 at 9:16am

Total quality. Thanks.

Post reply
Andy
16th October 2017 at 9:16am

I just wanted to thank you from the bottom of my heart. I appreaciate the time and effort you put into this.

With the help of your tutorial, a good php book and the internet in general I was able to tweak your script to fit my needs as well as furthering my php education a great deal.

Again... Thank You!

Post reply
Stephen - The Review Site Guy
16th October 2017 at 9:16am

unless my understanding of PHP is off, line 21 of functions.php references a non-existent mysql function:

if (mysql_numrows($sql) != 0) {

should be mysql_num_rows, right?

Post reply
Craig Hopson
16th October 2017 at 9:16am

Works, simple!!!!

Thank you so much for taking the time

Post reply
Kevin
16th October 2017 at 9:16am

Hello,

Thanks a lot for taking the time to write & share this, it works for me just like everyone else.

The only issue is.. I really don't know anything about php and I have no idea how to change the currency from £ to €, could you please tell me how this is done?

Post reply
Dan Lawson
16th October 2017 at 9:16am

Hi Kevin,

Thanks for reading the post. To change from £ to Euros you will need to change the currency_code value in the form to EUR:

[code]<input name="currency_code" type="hidden" value="EUR" />[/code]

Simples!

Post reply
Daniel
16th October 2017 at 9:16am

Update: remove the '/p/'

$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include “$root/functions.php”;

Post reply

Leave a comment

Replying to: - Cancel