Symfony2 PayPal IPN Bundle
Overview
symfony2-paypal-ipn is a Symfony2 bundle for working with the PayPal IPN (Instant Payment Notification) service. The bundle acts as a listener for the PayPal IPN service and logs the incoming orders to your database using Doctrine. Sending order confirmation emails is easy too (see the sample Twig email controller for details)., (*1)
symfony2-paypal-ipn is available on Packagist and KnpBundles as well as on GitHub., (*2)
Description
symfony2-paypal-ipn is a direct port of codeigniter-paypal-ipn, an equivalent library for CodeIgniter users, also by Orderly Ltd., (*3)
This library ("bundle" in Symfony language) focuses on the "post-payment" workflow, i.e. the processing required once the payment has been made and PayPal has posted an Instant Payment Notification call to the IPN controller., (*4)
This library handles:, (*5)
- Validating the IPN call
- Logging the IPN call
- Extracting the order and line item information from the IPN call
- Interpreting PayPal's payment status
- Storing the order and line items in the database
- Dispathing an event so that other bundles can do their stuff
All pre-payment functionality (e.g. posting the checkout information to PayPal) and custom post-payment workflow (e.g. sending emails) is left as an exercise for the reader. If you require a more general-purpose Symfony2 toolkit for working with PayPal, please see the JMSPaymentPaypalBundle., (*6)
This library also support getting the status from the Payment Data Transfer (PDT)., (*7)
Dependencies
The Symfony PayPal IPN Bundle depends on Symfony2, Doctrine 2.0, and curl., (*8)
An example order confirmation email which uses the Twig templating language is also provided., (*9)
Installation
1. Install from GitHub
We're going to install the PayPalIPNBundle directly into your Symfony vendor
directory:, (*10)
$ cd {{YOUR SYMFONY APP}}/vendor
$ git clone git://github.com/orderly/symfony2-paypal-ipn.git
...
$ mv symfony2-paypal-ipn orderly
Now the all-important OrderlyPayPalIpnBundle.php
file should now be available here:, (*11)
{{YOUR SYMFONY APP}}/vendor/orderly/src/Orderly/PaypalIpnBundle/OrderlyPayPalIpnBundle.php
2. Register the bundle
We now need to register the new bundle. Edit your AppKernel.php
file:, (*12)
{{YOUR SYMFONY APP}}/app/AppKernel.php
and add the following line to the end of the $bundles
array in the registerBundles()
method:, (*13)
new Orderly\PayPalIpnBundle\OrderlyPayPalIpnBundle(),
Now edit your autoload.php
file:, (*14)
{{YOUR SYMFONY APP}}/app/autoload.php
and add the following line to the end of your registerNamespaces()
invocation:, (*15)
'Orderly' => __DIR__.'/../vendor/orderly/src',
3. Deploy the database tables
With the PayPalIPN Bundle you have the choice of storing your date in a rational database like MySQL or to use MongoDB.
The next section provides information on how to use the two different systems., (*16)
3.1 Deploy the database tables using ORM (MySQL)
If you're going to use a rational database system like MySQL you have to configure the driver to use a doctrine ORM.
You can achive this by adding the following configuration to your bundles configuration:, (*17)
orderly_pay_pal_ipn:
# ... Rest of the configuration
drivers:
orm:
object_manager: doctrine.orm.entity_manager
classes: ~
The next step is to update/create the necessary database tables required by PayPalIpnBundle. There are two different ways of deploying the three database tables:, (*18)
Using the Symfony console
You can install the tables with the following command in your project console:, (*19)
$ php app/console doctrine:schema:update --force
Note that this method does not copy across the table field comments found in the SQL file., (*20)
Manually running the MySQL script
Alternatively, you can run the create_mysql_tables.sql
MySQL file against your database. You can find the file here:, (*21)
Orderly/PayPalIpnBundle/Resources/config
If you choose this option, you may want to modify the DEFAULT CHARSET
for each table (currently set to "utf8") before running., (*22)
3.2 Deploy the database tables using ODM (MongoDB)
To use MongoDB for your data store, make sure to install the DoctrineMongoDBBundle before activating the ODM Driver in your section.
More information on how to configure the bundle can be found on the Symfony2 website., (*23)
orderly_pay_pal_ipn:
#....
drivers:
odm:
object_manager: doctrine.odm.mongodb.document_manager
classes: ~
Note: A fully configured example can be found under 4.1 Use MongoDB backend, (*24)
Create the database tables
By running the following command your going to create/update the MonogoDB Collections:, (*25)
$ php app/console doctrine:mongodb:update --force
Now we need to configure the bundle. Add the below into your Symfony2 YAML configuration file app/config/config.yml
:, (*26)
# PaypalIpnBundle Configuration
orderly_pay_pal_ipn:
# If set to false then service loads settings with "sandbox_" prefix
islive: false
# Constants for the live environment (default settings in Configuration.php)
email: sales@CHANGEME.com
url: https://www.paypal.com/cgi-bin/webscr
proxy: ~
debug: %kernel.debug%
pdttoken: pdt-token
# Constants for the sandbox environment (default settings in Configuration.php)
sandbox_email: system_CHANGEME_biz@CHANGEME.com
sandbox_url: https://www.sandbox.paypal.com/cgi-bin/webscr
sandbox_proxy: ~
sandbox_debug: true
sandbox_response: VERIFIED
sandbox_pdttoken: pdt-token
sandbox_pdtresponse:
payment_status: Completed
mc_gross: 123.00
drivers:
orm:
object_manager: doctrine.orm.entity_manager
classes: ~
Make sure to update the email
and sandbox_email
settings to your own PayPal account's., (*27)
When islive
is set to false, the following configuration can be activated:, (*28)
-
sandbox_response
allows you to mock IPN Paypal's response. If you don't set its value, your server will hit the Paypal server and most likely return INVALID.
-
sandbox_pdtresponse
allows you to mock PDT Paypal's response. If you don't set its value, your server will hit the Paypal server and most likely return FAIL. To mock the value, simply pass in a list of key value pair the server would return.
A note on the debug
setting: if set to true, then PayPalIpnBundle will store the last IPN access which had IPN data (i.e. POST variables) into the database. Then when you access the IPN URL directly without data, it reloads the cached data. So it's effectively a "replay" mode which let's you directly inspect what the validateIPN()
IPN handler is doing., (*29)
4.1 Use MongoDB backend
To use the IPN listener with a MongoDB backend change the drivers section to odm and provide the name of your MongoDB object manager. Enclosed is a basic example configuration., (*30)
# PaypalIpnBundle Configuration
orderly_pay_pal_ipn:
# If set to false then service loads settings with "sandbox_" prefix
islive: false
# Constants for the live environment (default settings in Configuration.php)
email: sales@CHANGEME.com
url: https://www.paypal.com/cgi-bin/webscr
proxy: ~
debug: %kernel.debug%
pdttoken: pdt-token
# Constants for the sandbox environment (default settings in Configuration.php)
sandbox_email: system_CHANGEME_biz@CHANGEME.com
sandbox_url: https://www.sandbox.paypal.com/cgi-bin/webscr
sandbox_proxy: ~
sandbox_debug: true
sandbox_response: VERIFIED
sandbox_pdttoken: pdt-token
sandbox_pdtresponse:
payment_status: Completed
mc_gross: 123.00
drivers:
odm:
object_manager: doctrine.odm.mongodb.document_manager
classes: ~
5. Setup routing (optional but recommended)
To tell Symfony's routing system where to find one of our sample controllers, first open up the following file:, (*31)
{{YOUR SYMFONY APP}}/app/config/routing.yml
To send order confirmations with Twig
Assuming you want to send order confirmation emails using Twig, add in this controller:, (*32)
OrderlyPayPalIpnBundleEmail:
resource: "@OrderlyPayPalIpnBundle/Controller/TwigNotificationEmailController.php"
type: annotation
prefix: /ipn/
Your site will now be listening for incoming Instant Payment Notifications on the URL:, (*33)
http://{{YOUR DOMAIN}}/ipn/ipn-twig-email-notification
Note that the sample email template provided depends on Twig's number_format
filter, which was added in December 2012 (you may need to update your Twig version to use this). Don't forget to tell PayPal about your new PayPal IPN URL., (*34)
To log orders but not send notifications
Alternatively if you just want to log orders in the database (and not send out any notifications), then add in this controller:, (*35)
OrderlyPayPalIpnBundleNoEmail:
resource: "@OrderlyPayPalIpnBundle/Controller/NoNotificationController.php"
type: annotation
prefix: /ipn/
Your site will now be listening for incoming IPNs on:, (*36)
http://{{YOUR DOMAIN}}/ipn/ipn-no-notification
Don't forget to tell PayPal about your new PayPal IPN URL., (*37)
Disclaimer: the sample controllers provided are exactly that - samples. Please update one or other of these sample files with your own business logic before putting this bundle into production., (*38)
To receive PDT variables
This is an example of what your PDT call would look like., (*39)
namespace Your\OwnBundle;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class YourPaypalController extends Controller {
/**
* Your return action from Paypal.
*/
public function completeAction() {
$tx = $this->getRequest()->get('tx');
if (!$tx) {
// Redirect to a non-found page
return $this->redirect($this->generateUrl('notFound'));
}
$pdt = $this->get('orderly_pay_pal_pdt');
$pdtArray = $pdt->getPdt($tx);
$status = 'unknown';
if (isset($pdtArray['payment_status'])) {
$status = $pdtArray['payment_status'];
}
return $this->render('YourOwnBundle:YourPaypal:complete.html.twig',
array('status' => $status)
);
}
}
6. Subscribing to events (if you need custom processing)
After an IPN is received and if it is a valid one, an event with the incoming IPN will be dispatched. You can then subscribe a listener and perform whatever you need to do. Change your config.yml
with something like this:, (*40)
services:
# ...
paypal_im_received:
class: Your\OwnBundle\Event\YourPayPalListener
arguments: ["@doctrine.orm.entity_manager"]
tags:
- { name: kernel.event_listener, event: paypal.ipn.receive, method: onIPNReceive }
Now you just need to code your custom listener, (*41)
namespace Your\OwnBundle\Event;
use Orderly\PayPalIpnBundle\Event\PayPalEvent;
use Doctrine\Common\Persistence\ObjectManager;
class YourPayPalListener {
private $om;
public function __construct(ObjectManager $om) {
$this->om = $om;
}
public function onIPNReceive(PayPalEvent $event) {
$ipn = $event->getIPN();
// do your stuff
}
}
7. Test and troubleshoot
Now it's time to test. First, make sure that islive
is set to false, and sandbox_debug
is set to true., (*42)
Once debugging is switched on, this is how you test:, (*43)
- Run through your checkout process as normal, making your PayPal sandbox payment etc
- PayPal will send the IPN POST data to your new PayPal IPN URL
- Check the PayPal IPN history for success or failure (e.g. HTTP status code 500)
- Check you received the order confirmation email (if you're sending one)
- Check the order and line items are stored in your database
If you have problems with any of your checks, then the next step is to manually invoke your IPN URL in a browser and see what happens (for example a PHP or Symfony error, or perhaps a database or Twig not found error). This works because of the debug "replay" functionality explained in step 3 above. Next:, (*44)
8. Full configuration
# PaypalIpnBundle Configuration
orderly_pay_pal_ipn:
# If set to false then service loads settings with "sandbox_" prefix
islive: false
# Constants for the live environment (default settings in Configuration.php)
email: sales@CHANGEME.com
url: https://www.paypal.com/cgi-bin/webscr
proxy: ~
debug: %kernel.debug%
pdttoken: pdt-token
# Constants for the sandbox environment (default settings in Configuration.php)
sandbox_email: system_CHANGEME_biz@CHANGEME.com
sandbox_url: https://www.sandbox.paypal.com/cgi-bin/webscr
sandbox_proxy: ~
sandbox_debug: true
sandbox_response: VERIFIED
sandbox_pdttoken: pdt-token
sandbox_pdtresponse:
payment_status: Completed
mc_gross: 123.00
drivers: # Define one driver only.
orm:
object_manager: doctrine.orm.entity_manager
classes:
ipn_log: Orderly\PayPalIpnBundle\Entity\IpnLog
ipn_order_items: Orderly\PayPalIpnBundle\Entity\IpnOrderItems
ipn_orders: Orderly\PayPalIpnBundle\Entity\IpnOrders
# OR for MongoDB support
odm:
object_manager: doctrine.odm.mongodb.document_manager
classes:
ipn_log: Orderly\PayPalIpnBundle\Document\IpnLog
ipn_order_items: Orderly\PayPalIpnBundle\Document\IpnOrderItems
ipn_orders: Orderly\PayPalIpnBundle\Document\IpnOrders
Support and bugs
For support requests, please email Orderly Ltd. If you think there is a bug in the library, or a missing feature you would like to see added, please raise a new GitHub issue., (*45)
Credits
This library is a port of the Codeigniter PayPal IPN library, also released by Orderly Ltd., (*46)
Many thanks to all the contributors to symfony2-paypal-ipn:, (*47)
Disclaimer and warning
Orderly Ltd does not accept any liability for any processing errors made by the Symfony2 PayPal
IPN Bundle, or any financial losses incurred through its use., (*48)
In particular, this library does not fulfil the PayPal IPN requirement to:, (*49)
verify that the payment amount actually matches what you intend to charge. Although not technically
an IPN issue, if you do not encrypt buttons, it is possible for someone to capture the original
transmission and change the price. Without this check, you could accept a lesser payment
than what you expected., (*50)
(This verification step is out of scope for this bundle because it would require integration with
your product catalogue.), (*51)
Additionally this library does not properly handle refunds. Typically refunds are stored as
a new order line in ipn_orders
with a negative balance, but even this is not 100% predicatable., (*52)
Copyright
symfony2-paypal-ipn is copyright (c) 2012 Orderly Ltd., (*53)
License
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at:, (*54)
http://www.apache.org/licenses/LICENSE-2.0, (*55)
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License., (*56)