how to implement paypal in cakephp?

Here is an idea how to implement paypal in cakephp less than 5 mins? Answer is use Socket programming!! Yes, I found these very handy two classes from my friend Rajib Deb. So big big thanks for him.

Now step by step to implementation of this component.

Step 1: Create paypal.php file in /app/controllers/components/
Step 2: Paste this two class in paypal.php file

Click here to see the code

Step 3: In your controller add

var $components=array( ‘Paypal’);

Step 4: For PayPal Express Check Out use somthing like

public function expressPaypalCheckOut(){
$this->Paypal->paypalUserName = $pyapal_settings['user'];
$this->Paypal->paypalPassword = $pyapal_settings['password'];
$this->Paypal->paypalSignature = $pyapal_settings['signature'];
$this->Paypal->returnSuccessUrl = "/success/url/returnByPaypal/pay?csid=" . session_id();
$this->Paypal->returnCancelUrl = "/cancel/url/returnByPaypal/cancel?csid=".session_id();
$ret = ($this->Paypal->doExpressCheckout($user_info["amount"], 'Access to source code library','','EUR')); // use USD for dollar

Step 5: For PayPal Direct Payment use somthing like

$order = array(
'AMT'=> ($FREQUEST->postvalue('amount')/100),
'FIRSTNAME'=> $session_information["billto_array"]["firstname"],
'LASTNAME'=> $session_information["billto_array"]["lastname"],
'STREET'=> $session_information["billto_array"]["street_address"],
'STATE'=> $session_information["billto_array"]["state"],
'ZIP'=> $session_information["billto_array"]["postcode"],
'COUNTRYCODE'=> $session_information["billto_array"]["country"]["iso_code_2"],


$this->Paypal->paypalUserName = $pyapal_settings['user'];
$this->Paypal->paypalPassword = $pyapal_settings['password'];
$this->Paypal->paypalSignature = $pyapal_settings['signature'];
$this->Paypal->returnSuccessUrl = "/success/url/returnByPaypal/pay?csid=" . session_id();
$this->Paypal->returnCancelUrl = "/cancel/url/returnByPaypal/cancel?csid=".session_id();
$ret = ($this->Paypal->doDirectPayment($order));

6 Now after getting the responds from PayPal you need to reconfigure again the PayPal settings something like

public function returnByPaypal($callback = null){
if ($callback == 'cancel') {
	    } else if ($callback == 'pay') {
               $pyapal_settings = Configure::read('paypal_settings');
			$this->Paypal->paypalUserName = $pyapal_settings['user'];
			$this->Paypal->paypalPassword = $pyapal_settings['password'];
			$this->Paypal->paypalSignature = $pyapal_settings['signature'];
			$paypalRespons = $this->Paypal->doPayment();
                        if($paypalRespons['ACK'] == 'Success'){
                             /* your code in here*/

Well, thats it. Please consider some syntax error or other cause i am not testing these code yet!!! enjoy 😉

Inspired from Martin Maly’s Paypal Library


[CakePHP] Unit Testing

What a fun !! 😀
Today i test one of my Country Model using cakephp component. That why i write down this notes to make sure that i can use several times.

1. Download Simple Test unit testing suite.
2. Uncompress it in my app/vendors directory.
3. Change DEBUG level of 1 in my app/config/core.php file
4. Create a new database connection in app/config/database.php for only testing purpose like;

var $test = array(
‘driver’ => ‘mysql’,
‘persistent’ => true,
‘host’ => ‘localhost’,
‘login’ => ‘root’,
‘password’ => ”,
‘database’ => ‘db_name’,
‘prefix’ => ”,
‘encoding’ => ‘utf8’

5. Fixture : Create a file named country_test_fixture.php in your app/tests/fixtures directory, with the following content

class CountryTestFixture extends CakeTestFixture {

var $name = ‘CountryTest’;

var $import = array(‘model’ => ‘Country’, ‘records’ => true , ‘connection’ => ‘test’);


6. Test Case : Create a file named country.test.php in your app/tests/cases/models directory, with the following contents:



class CountryTest extends Country {
var $name = ‘Country’;
//var $useDbConfig = ‘test_suite’;

class CountryTestCase extends CakeTestCase {

var $fixtures = array( ‘Country_test’ );

function testFindAll() {

$this->CountryTest =& new CountryTest();

$result = $this->CountryTest->findAll(“Country.country_id=1”);

$expected = array(

array (
‘Country’ => array( ‘country_id’ => 1, ‘region_id’ => 2 , ‘country’ => ‘Bangladesh’ ),



$this->assertEqual($result, $expected);



7. Running My Test Case: Point my browser to http://tanveer-noman/myProject/test.php. Click on App Test Cases and find the link to your models/country.test.php. Click on that link.
Waoow!! I got a nice green screen saying that your test succeded.

To know more

cake bake

CakePHP: Creating a route usage https (SSL connection)

While playing in my workspace i need to make a route which should be use a secure path. That means https (SSL connection). So after googled for while i got the idea. Basically what i need is.. when an user in my sing in page will go through via the ssl connection. After entering user name and password will validated and redirect in to another location. So usually user will go through in https protocol then again redirected into http.

Here what i did;

Well, obviously i use cake’s component

1. Create a file ssl.php into app/controllers/components/
paste this code

class SslComponent extends Object {

	var $components = array('RequestHandler');

	var $Controller = null;

	function initialize(&$Controller) {
		$this->Controller = $Controller;

	function force() {
		if(!$this->RequestHandler->isSSL()) {

	function unforce() {
		if($this->RequestHandler->isSSL()) {

	/**This method updated from John Isaacks**/
	function __url($default_port = 80)
		$port = env('SERVER_PORT') == $default_port ? '' : ':'.env('SERVER_PORT');
		return env('SERVER_NAME').$port.env('REQUEST_URI');

you can find it also here but i added unforce() 😉

3. Now, in my case only when user click in to sign in or lend now, I need the https connection. Thats why, in my home controller i added this beforeRender() method, but make sure you assign this Ssl component.

var $components = array( 'Ssl' );
public function beforeRender(){

$action = array( 'signin', 'lendnow' );

if( in_array( $this->params['action'] , $action ) ){



So, i will create a secure connection with my apache server.
4. User now enter their user name and password and submit

5. If anyone click beside this they will have only http connection

That’s it

enjoy 😉

cakephp : $ajax.observeField and Session lost

Finlay i made the solution in my style… 🙂
In my cakePHP project when ever i made any Ajax request to my system… my session was lost.. and the new requested controller and action take the place on my session variable. I was totally mad.. because it takes my localization action away… The thing is when ever i change my combo box.. it calls the ajax request and reset my language session value and if any one click on the language flag on that moment my page layout was lost and broke down… 😦


1. Change the CAKE_SECURITY in app core.php to a level of medium or low
(don't worry it will not make any hole in the system and someone says that it can be the solution anyway..)
2. In app_controller set
var $components=array('RequestHandler');
3. Now, inside the beforeRender() method...add
$current_session_value = $this->Session->read('my_sess_var') ;
// this is the session which i want to have it
//What i did just check is ther any Ajax request has occurred.. so i use isAjax()
if ( $this->RequestHandler->isAjax() ) {
$this->Session->write('my_sess_var', null ); //i reset that session which was use to store
$this->Session->write('my_sess_var', $current_session_value ); // re-assign again

yahoo…. my problem is solved… no i can change my language whenever i want…


open-flash-chart in cakephp

Today i implement open-flash-chart into one of my cakephp project. The main goal of my work was to show a line graph with total amount of loan per month from june 2007 to till. Then take some time in google to find out some useful tutorials and i made my one way.

First i made the helper as describe in

mktime() First Day of the Last Week

The mktime() function returns the Unix timestamp for a date.
This timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

Assumed Moday is the firstday of the week.

$yesterday = date('Y-m-d H:i:s',mktime(0, 0, 0, date('m')  , date('d')-1, date('Y')));

$fromDate = date('Y-m-d H:i:s',mktime(0, 0, 0, date('n'), date('j'), date('Y')) - ((date('N')-1)*3600*24));

$fromDate = date('Y-m-d H:i:s',mktime(0, 0, 0, date('n'), date('j')-6, date('Y')) - ((date('N'))*3600*24));
$toDate = date('Y-m-d H:i:s',mktime(23, 59, 59, date('n'), date('j'), date('Y')) - ((date('N'))*3600*24));

$fromDate = date('Y-m-d H:i:s',mktime(0, 0, 0, date('m')  , 1, date('Y')));

$fromDate = date('Y-m-d H:i:s',mktime(0, 0, 0, date('m')-1  , 1 , date('Y')));
$toDate = date('Y-m-d H:i:s',mktime(23, 59, 59, date('m'), date('d')-date('j'), date('Y')));

$fromDate = date('Y-m-d H:i:s',mktime(0, 0, 0, date(1)  , date(1), date('Y')));

$fromDate = date('Y-m-d H:i:s',mktime(0, 0, 0, 1  , 1, date('Y')-1));
$toDate = date('Y-m-d H:i:s',mktime(23, 59, 59, 12, 31, date('Y')-1));

enjoy 😉

Thumbnail Generator in CakePHP

class ImagesController extends AppController {

var $name = ‘Images’;
var $uses = null;

// we want to ensure that the default layout doesn’t get rendered around your image data
// that was causing me lots of errors that i thought were BOM errors, until i commented
// out the header call in the view file

var $layout = null;

function thumbnail($filename=”) {

// create a thumbnail on the fly for product images

$parentImage = IMAGES_ROOT.’productImages/’.$image_file;
$thumbImage = IMAGES_ROOT.’productThumbs/’.$image_file;

// the thumbnail does not exist, create it before sending the location of it to the browser.
//header(“Content-type: image/jpeg”);
$im = imagecreatefromjpeg($parentImage);
$orig_height = imagesy($im);
$orig_width = imagesx($im);
$new_height = 60;
$new_width = (int) (($new_height / $orig_height) * $orig_width);
$new_im = imagecreatetruecolor($new_width,$new_height);
$image = ob_get_clean();
$thumb_pointer = fopen($thumbImage,’w+’);
header(“Location: /img/productThumbs/{$image_file}”);

%d bloggers like this: