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(
'PAYMENTACTION'=>'Sale',
'AMT'=> ($FREQUEST->postvalue('amount')/100),
'CREDITCARDTYPE'=>$FREQUEST->postvalue('card_type'),
'ACCT'=>$FREQUEST->postvalue('creditCard1'),
'EXPDATE'=>$FREQUEST->postvalue('expire_month').$FREQUEST->postvalue('expire_year'),
'CVV2'=>$FREQUEST->postvalue('cvvno'),
'FIRSTNAME'=> $session_information["billto_array"]["firstname"],
'LASTNAME'=> $session_information["billto_array"]["lastname"],
'STREET'=> $session_information["billto_array"]["street_address"],
'CITY'=>$session_information["billto_array"]["city"],
'STATE'=> $session_information["billto_array"]["state"],
'ZIP'=> $session_information["billto_array"]["postcode"],
'COUNTRYCODE'=> $session_information["billto_array"]["country"]["iso_code_2"],
'CURRENCYCODE'=> 'USD'</code>

);

$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') {
			$this->redirect("your/cancel/page");
	        exit;
	    } 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

Advertisements

About Tanveer
RIA (Rich Internet Application) Developer with a wide variety of business applications. Particularly interested in client/server and relational database design. Always interested in migration projects, as well as close interaction with the DB manufacturers.

33 Responses to how to implement paypal in cakephp?

  1. I found a small error in line 72 see this while ($read_length header = chop($responseHeader);

    Falopa!

  2. Pingback: 2010 in review « Tanveer's Weblog

  3. Ankita says:

    I think two end braces are left at line 78. But really this code is very helpful. I am implementing it in my project.
    Thanks for the code.

  4. Hi! Tanveer,
    You have written good code here but there is some error in this code I just trying to make you notice over it:

    1. at line 72:
    while ($read_length header = chop($responseHeader);
    what is header here

    2. $this->buildQuery(); is undefined in your component.

    3. at line 161 : if ($resultpaypalUserName;
    Invalid syntax wont identify that how many lines is to come in the condition coz end braces also missing.

    Please Correct them I need to Use this script onto my Project.
    I shall be very thankful to you!

  5. Sav says:

    Hello Tanveer,
    Where to save step 4 and 5 contents in files?

    thanks

    • Tanveer says:

      Hi Sav,
      Step 4. is nothing but a method name in your controller where you want to call expressPaypalCheckOut()

      Step 5. is for Direct Payment. This step is also depends on your business logic and you can use in
      your controller. So make $order array first.
      $order = array( … ); Then, you must need to call:
      $this->Paypal->doDirectPayment($order);

      Feel free to drop comments if any!

      • Sav says:

        Hello Tanveer,
        I’m getting same error.
        1. at line 72:
        while ($read_length header = chop($responseHeader);

        thanks

  6. ianemv says:

    Interesting. I might try this method if the methods I’m trying to implement won’t work 🙂

  7. Mir Ali says:

    How do I create a subscription?

  8. srikanth ganta says:

    Reblogged this on Srikanth's Blog.

  9. web hosting says:

    Thank you for your wise critique. Me and my neighbor were just preparing to do some research on this. We got a grab a guide from our nearby library but I think I learned more from this publish. I’m extremely glad to determine this kind of great information being shared freely available.

  10. Hi Tanveer

    I am using cakephp 2.2.5 and i follow given steps but comes these errors:

    Error: PaypalComponent could not be found.

    Error: Create the class PaypalComponent below in file: app\Controller\Component\PaypalComponent.php

    Please consider these two things and how to resolve them.

    Thanks

    Gajendra

    • Tanveer says:

      Assuming you have created a file paypal.php in /app/controllers/components directory. Check the file if PaypalComponent class is available or not? Check your first error.

      • thanks for reply Simply i have created paypal.php and paste your given code that code define PaypalComponent

        Plz can u give me suggestion how to resolve these problems.

        Simply i have worked in cakephp 2.2.5 and no other component i will drive.

      • Tanveer says:

        Check the error log and paste it here.

      • 2014-03-18 14:18:12 Error: [MissingComponentException] Component class PaypalComponent could not be found.
        #0 C:\xampp\htdocs\tyreexpo\lib\Cake\Controller\ComponentCollection.php(52): ComponentCollection->load(‘Paypal’, Array)
        #1 C:\xampp\htdocs\tyreexpo\lib\Cake\Controller\Controller.php(634): ComponentCollection->init(Object(UserProfilesController))
        #2 C:\xampp\htdocs\tyreexpo\lib\Cake\Routing\Dispatcher.php(182): Controller->constructClasses()
        #3 C:\xampp\htdocs\tyreexpo\lib\Cake\Routing\Dispatcher.php(161): Dispatcher->_invoke(Object(UserProfilesController), Object(CakeRequest), Object(CakeResponse))
        #4 C:\xampp\htdocs\tyreexpo\app\webroot\index.php(92): Dispatcher->dispatch(Object(CakeRequest), Object(CakeResponse))
        #5 {main}
        2014-03-18 14:19:11 Error: [MissingComponentException] Component class PaypalComponent could not be found.
        #0 C:\xampp\htdocs\tyreexpo\lib\Cake\Controller\ComponentCollection.php(52): ComponentCollection->load(‘Paypal’, Array)
        #1 C:\xampp\htdocs\tyreexpo\lib\Cake\Controller\Controller.php(634): ComponentCollection->init(Object(UserProfilesController))
        #2 C:\xampp\htdocs\tyreexpo\lib\Cake\Routing\Dispatcher.php(182): Controller->constructClasses()
        #3 C:\xampp\htdocs\tyreexpo\lib\Cake\Routing\Dispatcher.php(161): Dispatcher->_invoke(Object(UserProfilesController), Object(CakeRequest), Object(CakeResponse))
        #4 C:\xampp\htdocs\tyreexpo\app\webroot\index.php(92): Dispatcher->dispatch(Object(CakeRequest), Object(CakeResponse))
        #5 {main}

      • Tanveer says:

        Did you clear the cake cache? cake might have outdated info in /cache/persistent/
        Make sure your app is using component like this

        App::uses(‘Component’, ‘Controller’);

        and you added this line into your controller

        var $components=array( ‘Paypal’);

      • i have written in our controller like

        <?php
        App::uses('AppController', 'Controller');
        App::uses('Component', 'Controller');
        /**
        * UserProfiles Controller
        *
        * @property UserProfile $UserProfile
        */
        class UserProfilesController extends AppController {
        var $components=array('Paypal');

        }

        and clear cache but there is no updates.

        can u provides some other ways that help to solve my problems.

        Basically i will do recurring payment only for credit cards.

        either i have to send zip file link for that problems can you spend few more times that problems.

        thanks

  11. please can u advice for me another way to solve this problems.

    Thanks

    Gajendra

    • Tanveer says:

      The error looks like it’s missing cake’s componet somehow! You can find out another way to solve your problem. But you need to google it. You can also check this out http://stackoverflow.com/questions/4871433/is-there-a-cakephp-paypal-plugin

      • thanks for reply.

      • Given method not working so what problems comes in this method can u explain.

      • Tanveer your given code i break into two parts

        line 1 to 110 paypal.php
        and 111 to last line PaypalComponent .php in \lib\Cake\Controller\Component Location

        and i do one small change

        class PaypalComponent extends Object {
        replace
        class PaypalComponent extends Component {

        then error resolve but its right or wrong please confirm me.

        i also check there is no error in log file.

        Plz reply me still i am waiting for your reply.

        Thanks

      • Tanveer says:

        Yes, you can do that. Nothing wrong with that.

        Anyway, thanks for all your patience. You inspired me to move the code to my github repository. So that the code will not break out next time for someone else who wants to use it. If you have any more suggestions please add here. I will add that too.

        Happy coding!

  12. ok one thing is that where to pass username passowrd and signature of my paypal account please consider when u free asap.

    can i subscribe your cakephp articles its my 3rd project in cakephp and first time use in paypal but that time i feel good to resolve that problem with your help.

    Thanks

    • Tanveer says:

      You can set that in your config file or in the database anywhere you want. I prefer DB cause client can change username, password and the signature anytime he want.

      Yes, sure! You can subscribe the article if you like 🙂

  13. In cakephp I assign in config/folder and create paypal.php and create a array

    paypal array (app/config/paypal.php)
    ……………….

    $config = array(
    ‘Paypal’ => array(
    ‘username’ => ‘gajendra.nayal_api1.gmail.com’,
    ‘password’ => ‘IAVFQBTZUEC3TXU8’,
    ‘signature’ => ‘ANshZCPOkx1j9a53IUAqKfyekcDtAI-LZ6HXNZOAwqoN07zzxSFam0Bs’,
    ‘endpoint’ => ‘https://api-3t.paypal.com/nvp’,
    ‘version’ => ‘53.0’,
    ),
    );

    then then how to call in controller action in your given code plz modify my code

    $this->Paypal->paypalUserName = $pyapal_settings[‘user’];
    $this->Paypal->paypalPassword = $pyapal_settings[‘password’];
    $this->Paypal->paypalSignature = $pyapal_settings[‘signature’];

    thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: