Composer + CodeIgniter (Paypal REST API)

Hi everybody, this is how to do to use Composer with CodeIgniter. For this tutorial we assume that we want to use the new Paypal REST API.

So first of all we need to have CodeIgniter (http://ellislab.com/codeigniter). Once it's installed you need to install composer for that you can just get it from http://getcomposer.org/download/.

For GNU/Linux user just get into your codeigniter install dir, the root of codeigniter install folder (let's say it's /var/www/myWebSite), and run the commande :

$ curl -sS https://getcomposer.org/installer | php

Alright now we need to create the composer.json file and put into the following code :
{
    "require": {
        "php": ">=5.3.0",
        "ext-curl": "*",
        "ext-json": "*",
        "paypal/rest-api-sdk-php" : "0.7.*"
    }
}
Once it's done run the command :
$ php composer.phar install
It'll create a new folder vendor with the new Paypal REST SDK. Alright now edit the index.php file and add the following line just before require_once BASEPATH.'core/CodeIgniter'.EXT;
include_once './vendor/autoload.php';
That's it now you can create a library to implement Paypal functions for example :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Address;
use PayPal\Api\Authorization;
use PayPal\Api\Amount;
use PayPal\Api\AmountDetails;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\FundingInstrument;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Rest\ApiContext;
 
class PaypalRest {
 
    private $endpoints = array ('test' => 'api.sandbox.paypal.com', 'live' => 'api.paypal.com');
    private $clientIds = array ('test' => 'testtest', 'live' => 'livelive');
    private $secrets = array ('test' => 'testtest', 'live' => 'livelive');
 
    private $live = false;
    private $endpoint;
    private $clientId;
    private $secret;
    private $CI;
   
    public function __construct() {
        try {
            if ($this->live == false) {
                $this->endpoint = $this->endpoints['test'];
                $this->clientId = $this->clientIds['test'];
                $this->secret = $this->secrets['test'];
            } else {
                $this->endpoint = $this->endpoints['live'];
                $this->clientId = $this->clientIds['live'];
                $this->secret = $this->secrets['live'];
            }
 
            $this->CI = &get_instance();
        } catch (Exception $e) {
            throw new Exception("Paypal Rest error in constructor : " . $e->getMessage());
        }
    }
 
    public function getAccessToken() {
        $oauthCredential = new OAuthTokenCredential($this->clientId, $this->secret);
        $accessToken     = $oauthCredential->getAccessToken(array('mode' => 'sandbox'));
 
        return $accessToken;
    }
}
 

 

September 10, 2013