We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to integrate PayPal REST PHP SDK into phalcon autoloader?!

Hi there,

I want to integrate the PayPal REST PHP SDK into my phalcon project. You can find the SDK here:

https://github.com/paypal/PayPal-PHP-SDK

The documentation of this SDK says, that I have to include the autoloader.php file in my project:

"If your application has a bootstrap/autoload file, you should add include '<vendor directory location>/vendor/autoload.php' in it. The location of the <vendor directory> should be replaced based on where you downloaded vendor directory in your application."

So I tried several things:

include($config->application->libraryDir . "paypal-vendor/autoload.php");

and

$loader->registerDirs(array(
    $config->application->controllersDir,
    $config->application->modelsDir,
    $config->application->libraryDir,
    $config->application->libraryDir . "paypal-vendor/",
    $config->application->pluginsDir,
    $config->application->langDir,
));

I inserted the namespaces into my controller file:

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

But when I want to create an object like this:

$apiContext = new ApiContext(new OAuthTokenCredential('<clientId>', '<clientSecret>'));

I got an error:

Fatal error: Class 'PayPal\Rest\ApiContext' not found in .../app/controllers/IndexController.php on line 23

What am I doing wrong?

Thanks for your help!

Best, elchueko



58.4k
Accepted
answer

Hey

You just must inserting paypal library into composer

"require": {
        "phalcon/incubator": "dev-master",
        "swiftmailer/swiftmailer": "@stable",
        "kzykhys/ciconia": "~1.0.0",
        "paypal/rest-api-sdk-php" : "*",
        "fabfuel/prophiler": "~1.0"
    }

Then use it


<?php
namespace ZPhalcon\Tools;

use Phalcon\Mvc\User\Component;

if (!file_exists(ROOT_DIR . 'vendor/autoload.php')) {
    echo "The 'vendor' folder is missing. You must run 'composer update' to resolve application dependencies.\nPlease see the README for more information.\n";
    exit(1);
}
require_once ROOT_DIR . 'vendor/autoload.php';

use PayPal\Api\Address;
use PayPal\Api\CreditCard;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\FundingInstrument;
use PayPal\Api\Item;
use PayPal\Api\ItemList;

class Paypal extends Component
{

    /**
    * ### getBaseUrl function
    * // utility function that returns base url for
    * // determining return/cancel urls
    * @return string
    */
    public function getBaseUrl()
    {
        $protocol = 'http';
        if ($_SERVER['SERVER_PORT'] == 443 || (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on')) {
            $protocol .= 's';
            $protocol_port = $_SERVER['SERVER_PORT'];
        } else {
            $protocol_port = 80;
        }
        $host = $_SERVER['HTTP_HOST'];
        $port = $_SERVER['SERVER_PORT'];
        $request = $_SERVER['PHP_SELF'];
        return dirname($protocol . '://' . $host . ($port == $protocol_port ? '' : ':' . $port) . $request);
    }

    public function makePaymentUsingPayPal($id, $total, $paymentDesc = null)
    {

        $currency = $this->config->payment->currency;
        $tax      = $this->config->payment->tax;
        $shipping = $this->config->payment->shipping;
        $cancelUrl = $this->config->payment->paypal->cancelUrl;
        $returnUrl = $this->config->payment->paypal->returnUrl;
        $itemQuantity = 1;
        $itemName = "Post jobs on Phalconjobs.com";

        $payer = new Payer();
        $payer->setPaymentMethod("paypal");

        $item = new Item();
        $item->setQuantity($itemQuantity);
        $item->setName($itemName);
        $item->setPrice($total);
        $item->setCurrency($currency);

        $itemList = new ItemList();
        $itemList->setItems(array($item));

        // Specify the payment amount.
        $amount = new Amount();
        $amount->setCurrency($currency)
               ->setTotal($total + $shipping + $tax);

        //Transaction
        $transaction = new Transaction();
        $transaction->setDescription($paymentDesc)
                    ->setAmount($amount)
                    ->setItemList($itemList);

        // Create the payment and redirect buyer to paypal for payment approval.
        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl($this->getBaseUrl() . $returnUrl .'&id='. $id . '&success=true');
        $redirectUrls->setCancelUrl($this->getBaseUrl() . $cancelUrl . '&success=false');

        $payment = new Payment();
        $payment->setRedirectUrls($redirectUrls);
        $payment->setIntent("authorize");
        $payment->setPayer($payer);
        $payment->setTransactions(array($transaction));
        try {
            $payment->create($this->getApiContext());
        } catch (PayPal\Exception\PPConnectionException $ex) {
            echo "Exception: " . $ex->getMessage() . PHP_EOL;
            var_dump($ex->getData());
            exit(1);
        }

        /**
         * Get redirect url
         * The API response provides the url that you must redirect
         * the buyer to. Retrieve the url from the $payment->getLinks() method
         *
         */
        foreach ($payment->getLinks() as $key => $link) {
            if ($link->getRel() == 'approval_url') {
                $redirectUrl = $link->getHref();
                break;
            }
        }
        if (isset($redirectUrl)) {
            return $this->response->redirect($redirectUrl);
            exit;
        }
    }
    /**
     * Helper method for getting an APIContext for all calls
     *
     * @return PayPal\Rest\ApiContext
     */
    public function getApiContext()
    {

        // ### Api context
        // Use an ApiContext object to authenticate
        // API calls. The clientId and clientSecret for the
        // OAuthTokenCredential class can be retrieved from
        // developer.paypal.com

        $apiContext = new ApiContext(
            new OAuthTokenCredential(
                $this->config->payment->paypal->clientId,
                $this->config->payment->paypal->secret
            )
        );
        // #### SDK configuration

        // Comment this line out and uncomment the PP_CONFIG_PATH
        // 'define' block if you want to use static file
        // based configuration
        $apiContext->setConfig(
            array(
                'mode' => $this->config->payment->paypal->env,
                'http.ConnectionTimeOut' => $this->config->payment->paypal->timeout,
                'log.LogEnabled' => $this->config->payment->paypal->log,
                'log.FileName' => $this->config->payment->paypal->fileName,
                'log.LogLevel' => $this->config->payment->paypal->logLevel
            )
        );
        return $apiContext;
    }
}
//


8.9k

Thanks for your solution!

Honestly I have the following problem:

Fatal error: Class 'Paypal' not found in /app/controllers/IndexController.php on line 23

What I did:

  • creating a file "Paypal.php" in "library" dir with your sourcecode
  • adding the following line to my index.php

$di->set('paypal', function(){ return new Paypal(); });

In my ControllerFile I called this:

$this->paypal->getApiContext();

...btw, when I delete this:

namespace ZPhalcon\Tools;

I get another error:

Fatal error: Class 'PayPal\Rest\ApiContext' not found in /app/library/Paypal.php on line 132

Paypal Class is found, but no context from PayPal vendor directory.

What did I wrong?

Thx!



8.9k

Sry, it works!

Using the vendor dir, downloaded from composer (before used vendor dir from paypal sdk Zipfile).

Thx for your help!!



59.9k

Hi,

maybe someone can help me. I tried to rebuild this library, but i get this error message:

    Fatal error: Class 'Vokuro\Paypal\Paypal' not found in /Users/stefan/Sites/website/app/config/services.php on line 214

Library Paypal.php

  namespace Vokuro\Paypal;
  namespace ZPhalcon\Tools;
  use Phalcon\Mvc\User\Component;
  use PayPal\Api\Address;
  use PayPal\Api\CreditCard;
  use PayPal\Api\Amount;
  use PayPal\Api\Details;
  use PayPal\Rest\ApiContext;
  use PayPal\Auth\OAuthTokenCredential;
  use PayPal\Api\Payer;
  use PayPal\Api\Payment;
  use PayPal\Api\Transaction;
  use PayPal\Api\RedirectUrls;
  use PayPal\Api\FundingInstrument;
  use PayPal\Api\Item;
  use PayPal\Api\ItemList;

  class Paypal extends Component{

loader.php

  $loader = new \Phalcon\Loader();
  $loader->registerNamespaces(array(
      'Vokuro\Models' => $config->application->modelsDir,
      'Vokuro\Controllers' => $config->application->controllersDir,
      'Vokuro\Forms' => $config->application->formsDir,
      'Vokuro' => $config->application->libraryDir
  ));

  $loader->register();

  require_once __DIR__ . '/../../vendor/autoload.php';

services.php

  use Vokuro\Paypal\Paypal;
  $di->set('paypal', function(){
      return new Paypal();
  });

Thx Stefan