How to integrate payment gateway in yii2 using PayPal extension for the Yii2
Asked Answered
S

4

14

How to use paypal extension in yii2. I am using this link
https://github.com/marciocamello/yii2-paypal.
I installed extension and also added code in config file .

But there is not more information what to do next . So please help me.

Thanks

Sunken answered 5/2, 2015 at 12:5 Comment(2)
Maybe it's better to ask the actual developer about it. You can create issue on Github about problems with documentation. From what I see, documentation is pretty poor and there is no other links where it can be. Another options is just figuring it out by yourself looking at the source code. There is only one method in main class (besides init and demo) and configurational file. Maybe extension is in initial stage of development.Palate
Not an answer, but wondering if paypal.github.io/PayPal-PHP-SDK could be of any help. I am not a YII developer, and so not sure if it needs any special consideration. PayPal-PHP-SDK is available in composer as paypal/rest-api-sdk-php.Paten
I
18

There is no need to use an extension for this. You can simply install the paypal/rest-api-sdk-php package and perform the following steps.

1. Create a component to glue Paypal to Yii2

Create a components folder in your @app directory. If you are using the basic template, this is the same folder as webroot; in the advanced template, this folder is in the app you want to enable payments in.

Create a PHP class file (CashMoney for example) with the following content

use yii\base\Component;

use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;

class CashMoney extends Component {
  public $client_id;
  public $client_secret;
  private $apiContext; // paypal's API context

  // override Yii's object init()
  function init() { 
    $this->apiContext = new ApiContext(
      new OAuthTokenCredential($this->client_id, $this->client_secret)
    );
  }

  public function getContext() {
    return $this->apiContext;
  }
}

This is enough to get started. You may choose to add other configurations specific to PayPal later on.

2. Register your glue component with Yii2

In your app/config/main.php (or app/config/main-local.php), include the following to register the CashMoney component.

'components' => [
  ...
  'cm' => [ // bad abbreviation of "CashMoney"; not sustainable long-term
    'class' => 'app/components/CashMoney', // note: this has to correspond with the newly created folder, else you'd get a ReflectionError

     // Next up, we set the public parameters of the class
    'client_id' => 'YOUR-CLIENT-ID-FROM-PAYPAL',
    'client_secret' => 'YOUR-CLIENT-SECRET-FROM-PAYPAL',
    // You may choose to include other configuration options from PayPal
    // as they have specified in the documentation
  ],
  ...
]

Now we have our payment component registered as CashMoney, we can access it using Yii::$app->cm. Cool, huh?

3. Make API calls

To Make Your First API call in Yii2,

Open the controller action in which you want to handle payments, and include the following

use Yii;
...
use PayPal\Api\CreditCard;
use PayPal\Exception\PaypalConnectionException;

class PaymentsController { // or whatever yours is called
  ...
  public function actionMakePayments { // or whatever yours is called
    ...
    $card = new PayPalCreditCard;
    $card->setType('visa')
      ->setNumber('4111111111111111')
      ->setExpireMonth('06')
      ->setExpireYear('2018')
      ->setCvv2('782')
      ->setFirstName('Richie')
      ->setLastName('Richardson');

    try {
      $card->create(Yii::$app->cm->getContext());
      // ...and for debugging purposes
      echo '<pre>';
      var_dump('Success scenario');
      echo $card;
    } catch (PayPalConnectionException) {
      echo '<pre>';
      var_dump('Failure scenario');
      echo $e;
    }
    ...
  }

  ...

}

The expected output is similar to that in the PayPal documentation.

Once you get the connection going, you should be able to perform other tasks.

Intoxicate answered 8/4, 2015 at 12:47 Comment(3)
$this->apiContext = new ApiContext( new OAuthTokenCredential($this->client_id, $this->client_secret); ); should be $this->apiContext = new ApiContext( new OAuthTokenCredential($this->client_id, $this->client_secret) ); . Also public function getContext() { return $this->apiContext(); } should be public function getContext() { return $this->apiContext; } . Plz correct them. Can't edit due to minimum char limit ( which sucks lol).Harmless
Where are you initializing the CashMoney component?Ecru
the link you have referred to for Making the first call does not have any similarity to the code block you have added , you might need to update the code as there isnt any class with the name PayPalCreditCardCooperman
M
4

This is my solution, it's works with yii2 advanced tempalte!

I'v moved this class marciocamello/yii2-paypal/PayPal.php from vendor folder to common/component/PayPal.php

You have to "include" common\components\paypal in frontend\config\main.php under components section:

 'components' => [
    'paypal'=> [
        'class'        => 'common\components\Paypal',
        'clientId'     => 'your id you can find it over your paypal develpoer account. Ypu ah to create an application',
        'clientSecret' => 'your id you can find it over your paypal develpoer account. Ypu ah to create an application',
        'isProduction' => false,
         // This is config file for the PayPal system
         'config'       => [
             'http.ConnectionTimeOut' => 30,
             'http.Retry'             => 1,
             'mode'                   => \common\components\Paypal::MODE_SANDBOX, 
             'log.LogEnabled'         => YII_DEBUG ? 1 : 0,
             'log.FileName'           => '@runtime/logs/paypal.log',
             'log.LogLevel'           => \common\components\Paypal::LOG_LEVEL_INFO,
        ]
    ],

],

In PPHttpConfig.php on line 11 i have changed the following line

    //CURLOPT_SSLVERSION => 3,
    CURLOPT_SSLVERSION => 'CURL_SSLVERSION_TLSv1',

In PPLoggingManager.php on line 48-52 i'v hard coded the log path

if($this->isLoggingEnabled) {
        $this->loggerFile = $_SERVER['DOCUMENT_ROOT'].'/domain/frontend/runtime/logs/paypal.log';//($config['log.FileName']) ? $config['log.FileName'] : ini_get('error_log');
        $loggingLevel = strtoupper($config['log.LogLevel']);
        $this->loggingLevel = (isset($loggingLevel) && defined(__NAMESPACE__."\\PPLoggingLevel::$loggingLevel")) ? constant(__NAMESPACE__."\\PPLoggingLevel::$loggingLevel") : PPLoggingManager::DEFAULT_LOGGING_LEVEL;
    }

In site controller i'v called the component function

      echo '<pre/>';
  print_r(Yii::$app->paypal->payDemo());  
  exit();

I got a successfully response with redirect url, transactionId etc.

--------------  400 ERROR Debuging ----------

I'v always got 400 error because i had problem with price format, i fixed it with using number_format function.

I modified little the payDemo() function.

    $amount = 16;    
$formattedAmount = number_format($amount,2);
        $payer = new Payer();
        $payer->setPayment_method("paypal");
        $item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
    ->setCurrency('USD')
    ->setQuantity(1)
    ->setPrice($formattedAmount);
$item2 = new Item();
$item2->setName('Granola bars')
    ->setCurrency('USD')
    ->setQuantity(1)
    ->setPrice($formattedAmount);
$itemList = new ItemList();

$itemList->setItems(array($item1, $item2));
        //  $amountDetails = new Details();
        // $amountDetails->setSubtotal('7');
        // $amountDetails->setTax('0.00');
        // $amountDetails->setShipping('0.00');

         $amount = new Amount();
        $amount->setCurrency('USD');
        $amount->setTotal(number_format((2*$formattedAmount),2));
      //  $amount->setDetails($amountDetails);

        $transaction = new Transaction();
        $transaction->setDescription("creating a payment");
        $transaction->setItemList($itemList);
        $transaction->setAmount($amount);

        //$baseUrl = getBaseUrl();
        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturn_url("https://devtools-paypal.com/guide/pay_paypal/php?success=true");
        $redirectUrls->setCancel_url("https://devtools-paypal.com/guide/pay_paypal/php?cancel=true");

        $payment = new Payment();
        $payment->setIntent("sale");
        $payment->setPayer($payer);
        $payment->setRedirect_urls($redirectUrls);
        $payment->setTransactions(array($transaction));


        return $payment->create($this->_apiContext);

If you still get 400 or 40x error you can print the whole PayPal response with error messages etc in PPHttpConnection.php on line 107.

    $ex->setData($result);
        // echo '<pre>';
        // print_r($ex);exit;
        throw $ex;
Meadows answered 7/2, 2015 at 17:34 Comment(10)
Hello user3387825 Thanks for your reply and sorry for late response. i did as you told but i am getting the error ("Setting unknown property: common\components\Paypal::config ") plz help me thanksSunken
Hello could you provide me your email address, i have a YII2 advanced starter project with this PayPal module and it works well. I can send it to you via email. :)Meadows
I just sent an email :). If you have any question please do not hesitate to contact meMeadows
Thanks user3387825 for you attention but i did not get your email. can you send it again . My email Address is [email protected] I am waiting for your reply. ThanksSunken
Please check your inbox folder. I'v sent a link where you can download the project. Have nice day.Meadows
Thanks user3387825 i worked that project what you have given. The third sample is working proper but in first getting error "'common\components\ResultPrinter' not found" and while using second sample "getting error : Trying to get property of non-object for this $url = $response->links[1]->href;" How can i solve this. => one more question How can i perform recurring payment by onsite paypal payment integration system. Thanks for your help.Sunken
I just sent an email, please check your mail address.Meadows
Thank nagy for reply it worked how you sugessted. My question is like that. 1) As we take membership in any project take this as example elegantthemes.com/join.php there is three type of subscription. This is like subscription . I will paid automatic after the end of subscription preid like one moth or year. This is recurring payment in paypal how can i achieve this in yii2. ThanksSunken
Tjere is not need to move the class out of the vendor location. Simply include autoloader from composer and use path/to/class; at th etop of your Yii 2 controller class to access the logic of the library class.Torrez
Hi @NagyErvin I want to integrate same in yii2 advanced project. Can you please send the code to my email? My Mail Id - [email protected]..Goat
D
1

https://github.com/marciocamello/yii2-paypal. By this extension you can just setup/installed the paypal library which is avialable on this link- https://github.com/paypal/PayPal-PHP-SDK
This papypal-php-SDK having examples with different methods.

I have installed/setup this library in YII2 and used payment methods.

Domett answered 7/4, 2015 at 11:29 Comment(1)
Spoiler: Minimum supported: PHP 5.5Harmless
U
1

I use paypal express checkout based on Rest API in my website. No need for any third party extension. The solution can be applied to any website in general not limited to Yii framework. To get basic concepts read https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/

Here is my approach :

  1. Create a REST API APP in https://developer.paypal.com . Once you have created your APP, you would get Client ID and Secret Key, to be used later for authentication.

  2. On your webpage, where you want to display checkout button, create a empty div <div id="paypal-button"></div>

  3. Include https://www.paypalobjects.com/api/checkout.js javascript in your asset.

4.Render the paypal button with the following Javascript code

paypal.Button.render({
    env: 'sandbox', // Specify 'sandbox' for the test environment
    client: {
        sandbox: 'CLIENT-ID of your APP in step1'           
    },
    payment: function (resolve, reject) {

        /* URL which would create payment */
        var CREATE_PAYMENT_URL = '/transactions/create-paypal';

        paypal.request.post(CREATE_PAYMENT_URL)
            .then(function (data) {
                resolve(data.paymentID);
            })
            .catch(function (err) {
                reject(err);
            });
    },

    onAuthorize: function (data, actions) {

        // Execute the payment here, when the buyer authorize and approves the transaction
        var EXECUTE_PAYMENT_URL = '/transactions/execute-paypal';
        paypal.request.post(EXECUTE_PAYMENT_URL,
            {paymentID: data.paymentID, payerID: data.payerID, token: data.paymentToken,serviceId:serviceId})

            .then(function (data) {
                console.log(data);
                if(data.http_code == '200') {
                    /* payment done .. do something here */
                    handleCreateService(url);
                }else {
                    /* something didn't went right with payment */
                }
            })
            .catch(function (err) {
                /* catch any exceptions */
                console.log(err);
            });
    }

}, '#paypal-button');
  1. Now you need to code your create payment and execute payment methods in controller.

    /* Create Paypal function will pass token,
    paymentID back to JS in step 4. */
    
    public function actionCreatePaypal() {        
        $paypal = new Paypal();
        $paypal->getToken();
        $res = $paypal->createPayment();
        echo json_encode($res);
    }
    
    public function actionExecutePaypal() {
        $paymentID = $_POST['paymentID'];
        $payerID =  $_POST['payerID'];
        $access_token = $_POST['token'];
        $paypal = new Paypal(['paymentID'=>$paymentID,'payerID' =>$payerID,'access_token' =>$access_token]);
        $paypal->getToken();
        $res = $paypal->executePayment();
        echo json_encode($res);
    }    
    
  2. Finally create a component to do authentication/ generating token and executing payment.

    class Paypal {  
    
        public $url;
        public $env;
        public $clientId;
        public $clientSecret;
        public $access_token;
        public $paymentID;
        public $payerID;
        public $premiumService;
    
        public function __construct($params=0) {
            $this->access_token = '';
            /* for sandbox url is https://api.sandbox.paypal.com */
            $this->url = \Yii::$app->params['paypal_url'];
            $this->clientId = \Yii::$app->params['paypal_clientId'];
            $this->clientSecret = \Yii::$app->params['paypal_clientSecret'];
    
            if(isset($params['paymentID'])) {
                $this->paymentID = $params['paymentID'];
            }
    
            if(isset($params['payerID'])) {
                $this->payerID = $params['payerID'];
            }
    
            if(isset($params['access_token'])) {
                $this->access_token = $params['access_token'];
            }
    
            /* This is where you describe the product you are selling */    
            $this->premiumService = '{
            "intent":"sale",
            "redirect_urls":{
                 "cancel_url":"https://cancelurl.com",
                 "return_url":"https://returnurl.com"
            },
            "payer":{
                "payment_method":"paypal"
            },
            "transactions":[
            {
                "amount":{
                "currency":"USD",
                "total":"39.00"
                },
                "item_list":{
                    "items": [
                    {
                        "quantity": "1",
                        "name": "Premium Service",
                        "price": "39.00",
                        "currency": "USD",
                        "description": "Purchase allows one time use of this premium service"
                    }]
                },
                "description":"Premium Service"
    
            }]
            }';
    }
    public function getToken() {
        $curlUrl = $this->url."/v1/oauth2/token";
        $curlHeader = array(
            "Content-type" => "application/json",
            "Authorization: Basic ". base64_encode( $this->clientId .":". $this->clientSecret),
        );
        $postData = array(
            "grant_type" => "client_credentials"
        );
    
        $curlPostData = http_build_query($postData);
        $curlResponse = $this->curlCall($curlUrl, $curlHeader, $curlPostData);
        if($curlResponse['http_code'] == 200) {
            $this->access_token = $curlResponse['json']['access_token'];
        }
    }
    
    
    public function createPayment() {
        $curlUrl = $this->url."/v1/payments/payment";
        $curlHeader = array(
            "Content-Type:application/json",
            "Authorization:Bearer  ". $this->access_token,
        );
    
    
        $curlResponse = $this->curlCall($curlUrl, $curlHeader, $this->premiumService);
        $id = null;
        $approval_url = null;
        if($curlResponse['http_code'] == 201) {
            $id = $curlResponse['json']['id'];
            foreach ($curlResponse['json']['links'] as $link) {
                if($link['rel'] == 'approval_url'){
                    $approval_url = $link['href'];
                }
            }
        }
    
        $res = ['paymentID' =>$id,'approval_url'=>$approval_url];
        return $res;
    }
    
    public function executePayment() {
        $curlUrl = $this->url."/v1/payments/payment/".$this->paymentID."/execute";
    
        $curlHeader = array(
            "Content-Type:application/json",
            "Authorization:Bearer ".$this->access_token,
        );
        $postData = array(
            "payer_id" => $this->payerID
        );
    
        $curlPostData = json_encode($postData);
        $curlResponse = $this->curlCall($curlUrl, $curlHeader, $curlPostData);
    
        return $curlResponse;
    }
    
    function curlCall($curlServiceUrl, $curlHeader, $curlPostData) {
        // response container
        $resp = array(
            "http_code" => 0,
            "json"     => ""
        );
    
        //set the cURL parameters
        $ch = curl_init($curlServiceUrl);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
    
        //turning off the server and peer verification(TrustManager Concept).
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    
        curl_setopt($ch, CURLOPT_SSLVERSION , 'CURL_SSLVERSION_TLSv1_2');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        //curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeader);
    
        if(!is_null($curlPostData)) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPostData);
        }
        //getting response from server
        $response = curl_exec($ch);
    
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
        curl_close($ch); // close cURL handler
    
        // some kind of an error happened
        if (empty($response)) {
            return $resp;
        }
    
        $resp["http_code"] = $http_code;
        $resp["json"] = json_decode($response, true);
    
        return $resp;
    
    }
    }
    
Updraft answered 17/3, 2017 at 0:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.