Easily Integrate PayPal IPN in Yii Framework

Wonder how to integrate paypal IPN in Yii framework? Are you searching for Yii extension to integrate paypal IPN into your application? Well, i used to do that until i got fed up with reading all the documentation all excessive code dated by 2012 that hasn't been update for months! So i decided to just integrate paypal ipn alone into my Yii framework and guess what, it was so dead simple that it simply doesn't need any extension to began with.

PayPal IPN Tutorial

Before i began writing this tutorial, you should really understand what is paypal ipn is and why you are integrating it. Paypal IPN refers PayPal's Instant Payment Notification (IPN) which is a service provides by paypal to instantly notify your application whenever there is a payment made to you. And Micah Carrick had explained it perfectly on how to integrate it on a PHP level.

Coding Paypal IPN in Yii Framework

Here we go, firstly, you will need to get the code PHP-PayPal-IPN from github. The library provides you with a simple integration to Paypal IPN. Download the code and placed into your project/protected/vendors/PHP-PayPal-IPN and rename the ipnlistener.php to IpnListener.php.

Next, you will need to create a controller to listen to incoming ipn request and paste the following code into your listener method.

{
class PaymentController extends Controller{
        public function actionListen(){
                // intantiate the IPN listener
                Yii::import("application.vendors.PHP-PayPal-IPN.*", true);
                $listener = new IpnListener();

                // tell the IPN listener to use the PayPal test sandbox
                $listener->use_sandbox = true;

                // try to process the IPN POST
                try {
                        $listener->requirePostMethod();
                        $verified = $listener->processIpn();
                } catch (Exception $e) {
                        // error_log($e->getMessage());
                        Yii::log("IPN FAILED! returned an error: $e",CLogger::LEVEL_ERROR);
                        Yii::app()->end();
                }

                // TODO: Handle IPN Response here
                if ($verified) {
                        $model = new Transaction('search');
                        $model->attributes=$_POST;
                        $model->save();
                        // TODO: Implement additional fraud checks and MySQL storage
                        mail('[email protected]', 'Valid IPN', $listener->getTextReport());
                } else {
                        // manually investigate the invalid IPN
                        mail('[email protected]', 'Invalid IPN', $listener->getTextReport());
                }
        }

}

Do take note that you will need to give your method public access in order for paypal ipn services to reach it. Now, take note that the model i am using here belongs to my own, you can create your own and save every single data passed in by paypal to your database like what i did but do make sure that the naming convention are the same for both paypal $POST request and your own table fields.

Test Paypal IPN

In order to test your Paypal IPN request, you will need to create a sandbox paypal account and use its Instant Payment Notification (IPN) Simulator as show below,

Screen Shot 2014-06-26 at 2.52.33 AM

All you need to do is to scroll it all the way down and click "Send IPN". And you should be able to test your Paypal ipn listener! And guess what? You don't even need to create any sandbox paypal account to create a paypal IPN listener!

Varnish 403 Error – error on page

You have installed varnish into your web server and being happy with it for a few days and suddenly one day you found out that your page is showing an error page with the text "error" on it. And that kept you wonder why is varnish showing error page and after restarting your varnish it is still showing error.

A quick investigation on the http header sent over from the server shows that varnish is serving 403 error page to our visitors! Why?!

Why Varnish serving 403 error page

There are plenty of reasons why varnish is serving a 403 error page but most likely that your backend is only returning 403 once, but then Varnish is caching it for future requests. Some times it happens so we have to explicitly ask Varnish 3.0 to not cache any error pages. On vcl_fetch section, you might want to add the following to prevent it from caching all error page on varnish 3.0.


if (beresp.status >= 400) {
return (hit_for_pass);
}

But if this is not the case, there is also possbility that 403 points at your backend telling varnish it is forbidden. If varnish is giving you that error then it is working and the backend is giving it 403. Most likely this is caused by the backend apps use some sort of rate limiting per ip as by default when you add varnish to an existing setup the ip that gets passed to the backend is the varnish ip not the source ip. In that case you should update the X forwarded by adding the below code to vlc_recv section,

  remove req.http.X-Forwarded-For;
  set req.http.X-Forwarded-For = client.ip;

The above code ensure the correct client ip is being passed into varnish and prevent itself from throwing 403 error!

Lesson 1:How to create a theme using cherry framework

Introduce cherry framework

Cherry is a new framework for WordPress that make it easier for users to build WorldPress themes and WordPress websites. It is a new software framework with most current and sensible approaches to produce a consistent and well-crafted website. Cherry Framework is used in WordPress to build a theme which able to call Cherry WordPress themes.

Why use cherry framework

It is a framework created by developers for developers, but it’s also a perfect solution for anyone who wants to build WordPress sites minimum time. The reason to use Cherry Framework is because themes are easy to install and all changes can be done in the WordPress admin area. There's no need to switch between WordPress, FTP or PhpMyAdmin and you can get thing done simply in WordPress admin also. Other than that, it also allows an easy way to install WordPress plugin.

In the WordPress dashboard is only have one personal dashboard experiences, but in the Cherry Framework contain an additional category called as Cherry Options. The new category has a stylized interface and brings much better overview on WordPress themes. It is contains 100+ handy options integrated into a framework with including easy adjust theme appearance, change typography, logo and navigation so on. Intuitively fine-tune slider, blog pages, portfolio and page footer so that everything appears in the style you prefer.

Installing cherry framework

Framework Installation

There are several steps to teach users how to install the Cherry Framework into WordPress:

Step 1: Go to Dashboard and select the Appearance > Themes > Install Themes. Here you should upload the file named [CherryFramework.zip] that you have download into your computer.

Step 2: After upload is finished, we are able to see the cherry icon in the Appearance > Themes page. Click Activate button to proceed.

Step 3: After the activation of cherry themes, select the Home logo and click Visit Site.

Step 4: The cherry original themes will appear in the current site. At the top you are able to see the Cherry Framework Logo.

Creating a Cherry Framework theme

To create a Cherry Framework theme, usually it will separate into two parts. Cherry Framework can define as a “base/starter” theme framework. It is a stand-alone theme designed to be a flexible foundation for quicker WordPress development, usually serving as a robust Parent theme for Child themes.

Child themes allow user to modify, or add to the functionality of that parent themes. A child theme is the safest and easiest way to modify an existing theme. If we use and modify existing themes (Cherry Framework), your changes will be lost since Cherry Framework updated. Therefore, we are suggesting creating a child theme and overriding within. When the Cherry Framework makes a few tiny changes or updates, the child theme was still keep your changes.

There are several steps to teach users how to create a Child theme and install into the WordPress:

How to create a Child Themes

Step 1: To create a child themes,we would recommend that you use a descriptive name such as “parenttheme-child” (where “parenttheme” is the name of your active theme). Inside the “parenttheme-child” folder >create a style.css, then we wrote the code on below:

You can change each of these lines to suit your theme name. The only required lines are the Theme Name, the Template, and (if the stylesheet of your child theme is being built off of the parent theme -- with a few modifications) the '@import url' line.

Child Themes Installation

Step 2: Again go to Appearance > Themes > Add new > Upload Themes and upload your “parenttheme-child” folder that you have created as a child theme;

Step 3: After upload is finished, go again Appearance > Themes. It will show the Cherry Framework and Child theme you have uploaded just now.

Step 4: Click to active the Child themes, select the Home logo and click Visit Site. (Please refer to Framework Installation step 3 methods). Then you are able to see your site.

Step 5: After the activation of cherry-child, the example output is show like below.

testtest

Step 6: In the Appearance > Themes, once you active the child theme you are able to see and use the cherry option function which is provided by Cherry Framework (Parent theme).

A child theme is a “drop-in” code library framework which is not a stand-alone Theme. Such frameworks cannot be installed or used as a stand-alone theme. Figure 1 below show if the WordPress have no any Parent Theme (Cherry Framework), the Child Theme (cherry-child) is unable to read also.

Figure 1: broken theme

Install the themes into WordPress via Server

You need access to your website via either FTP or your hosting provider’s file manager application (such as Filezilla), as it is easier to add and edit files and folders that way. Once you have logged into your website via your chosen FTP client, navigate to “/wp-content/themes/”.

This directory will contain one or more folders, each of which represents a theme installed on your site. Figure 2 show the example of using Filezilla:

 

Figure 2: File ascending order in FileZilla

Conclusion

This article is to introduce, analyzing and teach how to install the Cherry Framework into the WordPress. It also includes several steps of creating a child theme with override by Cherry Frameworks. Lastly, we have include how to install the child themes into WordPress. The installation method just like the method how to install a Cherry Framework.

The WordPress is a great Platform that uses to build blogs and sites. It also provides the infrastructure to create plugin frameworks or theme frameworks on top of it. The benefits of building theme frameworks are to provide a stable, good quality themes quick and short time. This helps in faster development time and lower costs.

Creating Virtual Host on Nginx Web Server with Example in Centos

Actually this is a the continue part of my previous post which explains how to setup a LEMP server but the tutorial never actually teaches the user how to setup a virtual host for each of their website but this should be pretty straight forward and i am going to show you how this can be done.

Setup Virtual Host Directory

Before we go into nginx configuration, we will need to setup the location where we want our website files to be located. In this case, i have decided to just throw them into /var/www (you can do ln -s /var/www /home/www if you want it to be in /home in a later stage) but the folder isn't available so i will have to setup these virtual host folder myself.

sudo mkdir -p /var/www/monitorboard.com/html

You will need to designate an actual DNS approved domain, or an IP address, to test that a virtual host is working. In this tutorial we will use example.com as a placeholder for a correct domain name.

However, should you want to use an unapproved domain name to test the process i'll explain it later too.

Granting Permission to our Virtual Host Directory

Since we created our directory using a root account, we will have to change it to its rightful owner and in this case, it will be 'nginx' as shown below

sudo chown -R nginx:nginx /var/www/monitorboard.com/html

Additionally, it is important to make sure that everyone is able to read our new files so we have to correct its permission to 755

sudo chmod 755 /var/www

And we are done with permission!

Nginx Virtual Host

To setup your nginx virtual host, you will need to open up nginx virtual file located at /etc/nginx/conf.d/virtual.conf and you will need to update it with the following configuration

server {
    listen       8080;
    server_name  monitorboard.com www.monitorboard.com;
    root   /var/www/monitorboard.com/html;
    index  index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;

    }
# Logging --
    access_log  /var/www/monitorboard.com/access.log;
    error_log  /var/www/monitorboard.com/error.log;

# serve static files directly
    location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt)$ {
            access_log        off;
            expires           max;
    }

    include /etc/nginx/conf.d/global/security.conf;
    include /etc/nginx/conf.d/global/cache.conf;
    include /etc/nginx/conf.d/global/php-fpm.conf;
    include /etc/nginx/conf.d/global/status.conf;
    include /etc/nginx/conf.d/global/wordpress-w3-total-cache.conf;
}

As you can see, i've setup my domain to the folder /var/www/ instead of the default placement of /usr/share/nginx/html which means that this domain will read from the folder /var/www/monitorboard/html instead of anywhere else! Port 8080 is being used because we have varnish installed in our server as shown on our previous tutorial of how to setup a LEMP server.

Lastly all the include file can be get from nicolargo github. This will ensure that all our PHP files can be run off our nginx server but before anything can be run, we will need to restart our nginx server and php-fpm service.

service nginx restart
service php-fpm restart

This will ensure our setup is being updated on our machine.

Fake domain testing

In the case monitorboard.com isn't own by you, you will need to setup your hosts file to reflect your machine to redirect all request to your web server. Assuming your webserver ip is 1.1.1.1, you will need to update your hosts file in your computer/machine located in /etc/hosts and add in the following config

# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost

#Virtual Hosts 
1.1.1.1    www.monitorboard.com 

Now, if you open up your browser and hit 'www.monitoboard.com', you should be able to test your nginx configuration that you have done on your web server at 1.1.1.1 🙂

Setup Linux MySQL, PHP, nginx, php-fpm, varnish and APC on Centos (LEMP)

LEMP stack is a group of open source software to get web servers up and running. The acronym stands for Linux, nginx, MySQL, and PHP. In short, people who are looking into nginx is really looking for better web server as compare to apache which nginx perform better in many aspect although apache is still the most usage web server around due to its stability!

Requirement

Before we can start with all the installation for our fresh installed Centos server, we will need to download and install 2 extra repositories to our server. Below is a 32 bits Centos 6 installation

sudo rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
sudo rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm

64 bits Centos 6 installation you will need to fire the below command,

sudo rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
sudo rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm

We will need to do this in order to get nginx and php-fpm off our centos machine since its not available on our fresh Centos installation.

Install Nginx on Centos

Firstly we will need to install our Nginx web server by firing the below command,

sudo yum install nginx -y

now we will need to update our nginx configuration at /etc/nginx/nginx.conf to the following

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user              nginx;
worker_processes  4;
worker_rlimit_nofile 8192;

error_log  /var/log/nginx/error.log;
#error_log  /var/log/nginx/error.log  notice;
#error_log  /var/log/nginx/error.log  info;

pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
        # Only for Linux 2.6 or >
        use epoll;
        # Accept as many connections as possible
        multi_accept on;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
        tcp_nodelay                     on;

    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
        client_body_timeout             30;
        client_header_timeout           30;
        send_timeout                    30;
        client_max_body_size            8M;
        reset_timedout_connection       on;

        # Gzip module configuration
        gzip                    on;
        gzip_disable            "MSIE [1-6].(?!.*SV1)";
        gzip_vary               on;
        gzip_comp_level         3;
        gzip_proxied            any;
        gzip_buffers            16 8k;

    #gzip  on;

    # Load config files from the /etc/nginx/conf.d directory
    # The default server is in conf.d/default.conf
    include /etc/nginx/conf.d/*.conf;

}

The Above configuration allows nginx web server configuration to be setup properly with gzip enabled. Next we need to edit /etc/nginx/conf.d/default.conf to the following

server {
        listen       80 default_server;
        server_name  server.hungred.com;
        root /usr/share/nginx/html; 
        error_log /var/log/nginx/error.log;
        access_log /var/log/nginx/access.log;

        location / {
                root   /usr/share/nginx/html;
                index  index.html index.htm index.php;
        }

        error_page  404              /404.html;
        location = /404.html {
                root   /usr/share/nginx/html;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
                root   /usr/share/nginx/html;
        }

        location ~ \.php$ {
                root           /usr/share/nginx/html;
                try_files $uri =404;
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_intercept_errors on;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                include        fastcgi_params;
        }

}

The above setup our default directory for this server so if you fire up your server hostname, you will reach the directory as written on the default conf file. Now, we will need to test our nginx configuration before starting it,

nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Once this is done, our nginx web server has been setup and we will need to make sure that it will starts itself every times when it restart by setting up on chkconfig

sudo chkconfig --levels 235 nginx on

All done, we'll need to start up nginx

service nginx start

and we are good to go, you should be able to test whether this is working by firing up your ip address. And you can know your ip address by doing this

ifconfig eth0 | grep inet | awk '{ print $2 }'

But you should know 😉

Install PHP on Centos

Next, we will need to install php by firing

sudo yum install php-cli php-gd php-imap php-ldap php-odbc php-pear php-xml php-xmlrpc php-magickwand php-magpierss php-mbstring php-mcrypt php-mssql php-shout php-snmp php-soap php-tidy

Now edit php.ini file and find "cgi.fix_pathinfo" section then set it to 0 and save it.

Install APC on Centos

Next, we will need to install php-apc by firing

sudo yum install php-apc -y

We will need to update our php.ini file so that apc.so is enabled and is working fine. Edit the file at /etc/php.d/apc.ini and make sure that apc.so is enabled

; Enable apc extension module
extension = apc.so

Now we will need to install php-fpm

Install PHP-FPM on Centos

In order for php-fpm to work, we'll need to install it by running

yum install php-fpm -y

Once php-fpm is installed, we will need to configure it. Open up the file at /etc/php-fpm.d/www.conf and look for the following lines

; RPM: apache Choosed to be able to access some dir as httpd
user = apache
; RPM: Keep a group allowed to write in log dir.
group = apache

and change it to

; RPM: apache Choosed to be able to access some dir as httpd
user = nginx
; RPM: Keep a group allowed to write in log dir.
group = nginx

we are doing this because we are running nginx instead of apache. Next we will need to setup chkconfig so that it will starts itself when our server restart

sudo chkconfig --levels 235 php-fpm on

Lastly we need to start php-fpm

service php-fpm restart

And we are good to go!

Install MySQL on Centos

We will begin installing MySQL server into our machine,

sudo yum install mysql mysql-server 

Once the installation is completed, we will need to secure it!

sudo /usr/bin/mysql_secure_installation

It will prompt and ask you for your current root password.

Since you just installed MySQL, you most likely won’t have one, so leave it blank by pressing enter.

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Then the prompt will ask you if you want to set a root password. Go ahead and choose Y and follow the instructions.

At the end, MySQL will reload and implement the changes.

By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y                                            
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
... Success!

By default, MySQL comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!

we need to setup chkconfig so that mysql will start itself upon reboot,

sudo chkconfig --levels 235 mysqld on

Next we start our database!

service mysqld restart

And we are good here.

Install Varnish on Centos

First off, install varnish!

sudo yum install varnish

Then we will configure varnish to act as the middle man between our visitors and our web server! Open up varnish configure file at /etc/sysconfig/varnish and change the port from

# # Default address and port to bind to
# # Blank address means all IPv4 and IPv6 interfaces, otherwise specify
# # a host name, an IPv4 dotted quad, or an IPv6 address in brackets.
# VARNISH_LISTEN_ADDRESS=
VARNISH_LISTEN_PORT=8080

to

# # Default address and port to bind to
# # Blank address means all IPv4 and IPv6 interfaces, otherwise specify
# # a host name, an IPv4 dotted quad, or an IPv6 address in brackets.
# VARNISH_LISTEN_ADDRESS=
VARNISH_LISTEN_PORT=80

this is to ensure that our varnish will be listening to port 80 which is what our nginx server is currently doing! So we will need to update our nginx configuration so that it will listen to other port. This is my blog nginx virtual host which is listening to port 8080 instead of 80, you'll need to change that from the original 80 to 8080 so that it won't crash with varnish!

server {
    listen       8080;
    server_name  hungred.com www.hungred.com;
    root   /var/www;
    index  index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;

    }

}

P.S: i have alter a bit on the configuration to avoid unnecessary headache lol. Once this is done you will still have to configure varnish! Open up the file at /etc/varnish/default.vcl and make sure that your server ip and port is correctly updated.

backend default {
.host = "127.0.0.1";
.port = "80";
}

to

backend default {
  .host = "12.23.18.1";
  .port = "8080";
}

The above means that all request from varnish that it doesn't have cache on will redirect to port 8080 which is where our nginx server lies! Ok, so same stuff here, we will need to make sure varnish starts itself or else all our web sites on this web server will die if it got rebooted!

chkconfig varnish on

Finally, reboot both nginx and varnish in this sequence!

service nginx restart

this will change nginx listening port from 80 to 8080 and varnish from 8080 to 80! And we are done!

Summary

Ok to be honest, this tutorial was setup using the same exact same steps as how i've setup for this website and also prove whatever is written here works pretty well! So try it out and let me know if you faced any issue with your installation!