Yii 1.1: paypal

A PayPal component for Yii framework to utilize Express Checkout and Direct Payment APIs
45 followers

A PayPal component for Yii framework to utilize Express Checkout and Direct Payment APIs. A simple component that will help you easily implement Express Checkout and Direct Payment APIs in your Yii applications

Requirements

  • The component is build for Yii framework version 1.1 or above
  • You will need CURL PHP extension
  • Paypal credentials (username, password, signature) are required

Installation

Download the extension here or from the Github repo, extract the files to their appropriate folders. After place this code within your configuration file (main.php) inside the 'components' section

'Paypal' => array(
    'class'=>'application.components.Paypal',
    'apiUsername' => 'YOUR_API_USERNAME',
    'apiPassword' => 'YOUR_API_PASSWORD',
    'apiSignature' => 'YOUR_API_SIGNATURE',
    'apiLive' => false,
 
    'returnUrl' => 'paypal/confirm/', //regardless of url management component
    'cancelUrl' => 'paypal/cancel/', //regardless of url management component
 
    // Default currency to use, if not set USD is the default
    'currency' => 'USD',
 
    // Default description to use, defaults to an empty string
    //'defaultDescription' => '',
 
    // Default Quantity to use, defaults to 1
    //'defaultQuantity' => '1',
 
    //The version of the paypal api to use, defaults to '3.0' (review PayPal documentation to include a valid API version)
    //'version' => '3.0',
),

Usage

A sample controller to demonstrate the usage of the component

directpayment action demonstrates the Direct Payment API usage, the rest demonstrates Express Checkout API step by step implementation.

class PaypalController extends Controller
{
    public function actionBuy(){
 
        // set 
        $paymentInfo['Order']['theTotal'] = 0.00;
        $paymentInfo['Order']['description'] = "Some payment description here";
        $paymentInfo['Order']['quantity'] = '1';
 
        // call paypal 
        $result = Yii::app()->Paypal->SetExpressCheckout($paymentInfo); 
        //Detect Errors 
        if(!Yii::app()->Paypal->isCallSucceeded($result)){ 
            if(Yii::app()->Paypal->apiLive === true){
                //Live mode basic error message
                $error = 'We were unable to process your request. Please try again later';
            }else{
                //Sandbox output the actual error message to dive in.
                $error = $result['L_LONGMESSAGE0'];
            }
            echo $error;
            Yii::app()->end();
 
        }else { 
            // send user to paypal 
            $token = urldecode($result["TOKEN"]); 
 
            $payPalURL = Yii::app()->Paypal->paypalUrl.$token; 
            $this->redirect($payPalURL); 
        }
    }
 
    public function actionConfirm()
    {
        $token = trim($_GET['token']);
        $payerId = trim($_GET['PayerID']);
 
 
 
        $result = Yii::app()->Paypal->GetExpressCheckoutDetails($token);
 
        $result['PAYERID'] = $payerId; 
        $result['TOKEN'] = $token; 
        $result['ORDERTOTAL'] = 0.00;
 
        //Detect errors 
        if(!Yii::app()->Paypal->isCallSucceeded($result)){ 
            if(Yii::app()->Paypal->apiLive === true){
                //Live mode basic error message
                $error = 'We were unable to process your request. Please try again later';
            }else{
                //Sandbox output the actual error message to dive in.
                $error = $result['L_LONGMESSAGE0'];
            }
            echo $error;
            Yii::app()->end();
        }else{ 
 
            $paymentResult = Yii::app()->Paypal->DoExpressCheckoutPayment($result);
            //Detect errors  
            if(!Yii::app()->Paypal->isCallSucceeded($paymentResult)){
                if(Yii::app()->Paypal->apiLive === true){
                    //Live mode basic error message
                    $error = 'We were unable to process your request. Please try again later';
                }else{
                    //Sandbox output the actual error message to dive in.
                    $error = $paymentResult['L_LONGMESSAGE0'];
                }
                echo $error;
                Yii::app()->end();
            }else{
                //payment was completed successfully
 
                $this->render('confirm');
            }
 
        }
    }
 
    public function actionCancel()
    {
        //The token of the cancelled payment typically used to cancel the payment within your application
        $token = $_GET['token'];
 
        $this->render('cancel');
    }
 
    public function actionDirectPayment(){ 
        $paymentInfo = array('Member'=> 
            array( 
                'first_name'=>'name_here', 
                'last_name'=>'lastName_here', 
                'billing_address'=>'address_here', 
                'billing_address2'=>'address2_here', 
                'billing_country'=>'country_here', 
                'billing_city'=>'city_here', 
                'billing_state'=>'state_here', 
                'billing_zip'=>'zip_here' 
            ), 
            'CreditCard'=> 
            array( 
                'card_number'=>'number_here', 
                'expiration_month'=>'month_here', 
                'expiration_year'=>'year_here', 
                'cv_code'=>'code_here' 
            ), 
            'Order'=> 
            array('theTotal'=>1.00) 
        ); 
 
       /* 
        * On Success, $result contains [AMT] [CURRENCYCODE] [AVSCODE] [CVV2MATCH]  
        * [TRANSACTIONID] [TIMESTAMP] [CORRELATIONID] [ACK] [VERSION] [BUILD] 
        *  
        * On Fail, $ result contains [AMT] [CURRENCYCODE] [TIMESTAMP] [CORRELATIONID]  
        * [ACK] [VERSION] [BUILD] [L_ERRORCODE0] [L_SHORTMESSAGE0] [L_LONGMESSAGE0]  
        * [L_SEVERITYCODE0]  
        */ 
 
        $result = Yii::app()->Paypal->DoDirectPayment($paymentInfo); 
 
        //Detect Errors 
        if(!Yii::app()->Paypal->isCallSucceeded($result)){ 
            if(Yii::app()->Paypal->apiLive === true){
                //Live mode basic error message
                $error = 'We were unable to process your request. Please try again later';
            }else{
                //Sandbox output the actual error message to dive in.
                $error = $result['L_LONGMESSAGE0'];
            }
            echo $error;
 
        }else { 
            //Payment was completed successfully, do the rest of your stuff
        }
 
        Yii::app()->end();
    } 
}

Resources

Github repo for this extension

Total 20 comments

#18123 report it
begemotik at 2014/09/12 08:39am
Adaptive / Chained Payments

Hi everyone,

if you're looking on how to integrate PayPal chained payments into Yii (where a user pays the site and then the site pays someone else, for instance), I suggest you check out this little tutorial I've written: link

Hope it's helpful!

#17769 report it
KonApaz at 2014/07/21 06:48am
Twice set the amount

I have another question

Why sould set twice the amount ?

In actionBuy

$paymentInfo['Order']['theTotal'] = xy.zw;

And In actionConfirm

$result['ORDERTOTAL'] = xy.zw;

If I set another amount in the actionConfirm all works properly (It shouldn't be) for example $result['ORDERTOTAL'] = aa.bb;

The

$paymentResult = Yii::app()->Paypal->DoExpressCheckoutPayment($result);

of actionConfirm returns the aa.bb but the actionConfirm has set in the first time xy.zw

so which price of the transaction has been considered ??

#17767 report it
KonApaz at 2014/07/21 04:06am
Transactions

Good Extension

Does anybody know the steps to register a transaction ?

For example in actionBuy after of success buy (but before confirmation) we can store the $result in the database (TOKEN,TRANSACTIONID etc)

In the confirmation I want to match the Tranaction (that generated in actionBuy) with succeded final confirmation and store all important data in the database

So, The admin could see all the tranaction of any user and tranaction status (succeeded,failure etc)

How can I make it in the right way ?

Thanks

#17558 report it
Rajith R at 2014/07/02 08:38am
Good

Thank you for the good extension.

#17419 report it
Edgar Kuskov at 2014/06/09 09:11am
Credit card payment / Demo

Hello,

is there demo available? Is the credit card payment also included?

Best regards,

#16391 report it
Vernes at 2014/02/17 07:36pm
@marcoaurelio

Set 'apiLive' => false in your main config and username and pass of your sandbox account, like this:

'Paypal' => array(
            'class'=>'application.components.Paypal',
            'apiUsername' => 'USERNAME',
            'apiPassword' => 'PASS',
            'apiSignature' => 'SIG...',
            'apiLive' => false,
            'currency' => 'EUR',
            'returnUrl' => 'payment/paypalConfirm/', 
            'cancelUrl' => 'payment/paypalCancel/',
        ),
#16390 report it
marcoaurelio at 2014/02/17 06:08pm
Test Mode

How do I set this to a Sandbox Mode (test mode)? How can I configure de main.php file? I have a bussiness account in PayPal whithin my credentials. Im testing this in Localhost. I got this error message: Security header is not valid!!! Can anybody help me, please?!

#16181 report it
Ankit Modi at 2014/01/27 12:05am
How to set a default sandbox error

Hi When I was test a default error message get a error

Undefined index: L_LONGMESSAGE0

How this solved?please help

#15647 report it
Vinny.freire at 2013/12/03 09:32pm
Error

Fatal error: Class 'PayPal\Common\PPApiContext' not found in ...\protected\extensions\paypal\lib\Rest\ApiContext.php on line 10

Help Please! Tanks!

#13766 report it
sheraz.s at 2013/06/24 03:54am
How to implement Recurring payment with this extension

I have used this extension and its very simple and amazing. i really appreciate your efforts. Now i want to implement recurring payment. Can you tell me how i can do this.

#12109 report it
eamador at 2013/02/27 02:13pm
ORDERTOTAL

@FcoKraken thanks a lot for your suggestion, it helped me to solve the issue! :)

#12100 report it
FcoKraken at 2013/02/27 08:49am
re: actionConfirm ODERTOTAL Hard coded

you can use session vars. in actionBuy add this next to $paymentInfo['Order']['theTotal'] = 0.00

Yii::app()->session['theTotal'] = 0.00

and in actionConfirm change $result['ORDERTOTAL'] = 0.00; to

$result['ORDERTOTAL'] = Yii::app()->session['theTotal'];
#12086 report it
eamador at 2013/02/26 04:16pm
actionConfirm ODERTOTAL Hard coded

Hi! Thanks for the extension, it's great!! but i have a doubt, the ORDERTOTAL on actionConfirm is hardcored $result['ORDERTOTAL'] = 0.00;

I guess this has to match with the $paymentInfo['Order']['theTotal'] which was set up on actionBuy, how can i get the $paymentInfo['Order']['theTotal'] in the actionConfirm??

Thanks!

#12079 report it
FcoKraken at 2013/02/26 12:08pm
Security header is not valid

In the sandbox enviroment everything works OK, but when i go live, i get the error "Security header is not valid".

I already: - Check the credentials and are ok (im using the credentials for production, not sandbox) - Change apiLive to true in config/main

I dont know what else to do, plz help me Thanks

SOLUTION! When you change apiLive to true in config/main, it doesnt work. You have to change it directly in PayPayl.php (line 32: change public $apiLive = false to public $apiLive = true)

#11986 report it
sanguina at 2013/02/18 01:32pm
Slight Modification

the paypal api has changed.. for this code to work you should modify the $nvpstr in extensio/paypal.php to:

$nvpstr="&PAYMENTACTION=Sale&IPADDRESS=$ip&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber&EXPDATE=".$padDateMonth.$expDateYear."&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName&STREET=$address1&STREET2=$address2&CITY=$city&STATE=$state". "&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=$currencyCode";

There have been minor changes in naming of country, zip, state and city.. but important in that you will keep getting error msgs if you dont correct them.

thanks for this great extension

@skall - thanks for replying - it did solve the problem

#11984 report it
skall at 2013/02/18 10:08am
re: ["L_SHORTMESSAGE0"]=> string(12) "Invalid Data"

@sanguina

I've got a similar issue when trying the extension. I only did a quick setup, and changed the actionBuy $paymentInfo['Order']['theTotal'] to something more (10.00).

You need to set the same amount in the actionConfirm, currently, it is hard coded to 0.00 which obviously won't match 10.00, hence the invalid data error.

Hope that helps.

#11977 report it
sanguina at 2013/02/17 12:34pm
["L_SHORTMESSAGE0"]=> string(12) "Invalid Data"

thanks for this great extension.

while trying out the direct payment, i am getting an error: "This transaction cannot be processed." ["L_ERRORCODE0"]=> string(5) "10747" ["L_SHORTMESSAGE0"]=> string(12) "Invalid Data" ["L_LONGMESSAGE0"]=> string(37) "This transaction cannot be processed." ["L_SEVERITYCODE0"]=> string(5) "Error"

I suspect the error results from an invalid credit card type. What is the list of valid data for credit card type ?

some articles on web suggest it as an error of IP address format.. but the code seems to be OK for that.

the only place i see ip mentioned is in the Paypal.php $ip=$_SERVER['REMOTE_ADDR']; does this ip needs to be formatted ?

Any suggestions on how to correct this would be really appreciated thanks for replying

#11890 report it
STDev at 2013/02/11 10:32am
re: 2 urls

Hi skall,

We have made modifications you have suggested. Now configuration parameters only need the path to be specified.

Thanks!

#11886 report it
STDev at 2013/02/11 08:59am
re: Currency should be easily configurable

Hi skall,

We have updated downloads section here it is also up to date now along with the Installation section.

#11876 report it
skall at 2013/02/10 04:45pm
2 urls

Hi,

If you use the following in your init() function, I wouldn't have anything to change weither I use urlManager or not.

$this->returnUrl = Yii::app()->createAbsoluteUrl($this->returnUrl);
        $this->cancelUrl = Yii::app()->createAbsoluteUrl($this->cancelUrl);

Leave a comment

Please to leave your comment.

Create extension