menu

Sunday 26 July 2015

how to integrate paypal payment in codeignitor

create a file in  appication/libraries/  
======= paypal.php ===========
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package      CodeIgniter
 * @author      Romaldy Minaya
 * @copyright     Copyright (c) 2011, PROTOS.
 * @license      GLP
 * @since          Version 1.0
 * @version      1.0
 */

// ------------------------------------------------------------------------

/**
 * Paypal Class
 *
 * @package      CodeIgniter
 * @subpackage     Libraries
 * @category     Payment process
 * @author      Romaldy Minaya
 *

// ------------------------------------------------------------------------

Documentation
    This class let you make the payment procces based on paypal API,
    effortless and easy.

*1)Use the same documentation about the vars from paypal page. http://bit.ly/j4wRR   
*2)Customize the payment procces as you desire.   
*3)Build with love.   

Implementation

*1)Copy this code in your controller's function

        $config['business']             = 'demo@demo.com';
        $config['cpp_header_image']     = ''; //Image header url [750 pixels wide by 90 pixels high]
        $config['return']                 = 'sucess.php';
        $config['cancel_return']         = 'shopping.php';
        $config['notify_url']             = 'process_payment.php'; //IPN Post
        $config['production']             = TRUE; //Its false by default and will use sandbox
        $config['discount_rate_cart']     = 20; //This means 20% discount
        $config["invoice"]                = '843843'; //The invoice id
       
        $this->load->library('paypal',$config);
       
        #$this->paypal->add(<name>,<price>,<quantity>[Default 1],<code>[Optional]);
       
        $this->paypal->add('T-shirt',2.99,6); //First item
        $this->paypal->add('Pants',40);       //Second item
        $this->paypal->add('Blowse',10,10,'B-199-26'); //Third item with code
       
        $this->paypal->pay(); //Proccess the payment
       
    The notify url is where paypal will POST the information of the payment so you
    can save that POST directly into your DB and analize as you want.
   
    With $config["invoice"] is how you identify a bill and you can compare,save or update
    that value later on your DB.
   
    For test porpuses i do recommend to save the entire POST into your DB and analize if
    its working according to your needs before putting it in production mode. EX.
   
    $received_post = print_r($this->input->post(),TRUE);
    //Save that variable and analize.
   
    Note: html reference page http://bit.ly/j4wRR
 */
class Paypal {
   
    var $config         = Array();
    var $production_url = 'https://www.paypal.com/cgi-bin/webscr?';
    var $sandbox_url    = 'https://www.sandbox.paypal.com/cgi-bin/webscr?';
    var $item            = 1;
   
    /**
     * Constructor
     *
     * @param    string
     * @return    void
     */
    public function __construct($props = array())
    {
        $this->__initialize($props);
        log_message('debug', "Paypal Class Initialized");
    }
    // --------------------------------------------------------------------

    /**
     * initialize Paypal preferences
     *
     * @access    public
     * @param    array
     * @return    bool
     */
    function __initialize($props = array())
    {
        #Account information
        $config["business"]     = ''; //Account email or id
        $config["cmd"]             = '_cart'; //Do not modify
        $config["production"]     = FALSE;

        #Custom variable here we send the billing code-->
        $config["custom"]    = '';
        $config["invoice"]    = ''; //Code to identify the bill

        #API Configuration-->
        $config["upload"]          = '1'; //Do not modify
        $config["currency_code"] = 'USD'; //http://bit.ly/anciiH
        $config["disp_tot"] = 'Y';

        #Page Layout -->
        $config["cpp_header_image"]         = ''; //Image header url [750 pixels wide by 90 pixels high]
        $config["cpp_cart_border_color"]     = '000'; //The HTML hex code for your principal identifying color
        $config["no_note"]     = 1; //[0,1] 0 show, 1 hide

        #Payment Page Information -->
        $config["return"]             = ''; //The URL to which PayPal redirects buyers’ browser after they complete their payments.
        $config["cancel_return"]    = ''; //Specify a URL on your website that displays a “Payment Canceled” page.
        $config["notify_url"]         = '';  //The URL to which PayPal posts information about the payment (IPN)
        $config["rm"] = '2'; //Leave this to get payment information
        $config["lc"] = 'EN'; //Languaje [EN,ES]

        #Shipping and Misc Information -->
        $config["shipping"]     = '';
        $config["shipping2"]     = '';
        $config["handling"]     = '';
        $config["tax"]             = '';
        $config["discount_amount_cart"] = ''; //Discount amount [9.99]
        $config["discount_rate_cart"]     = ''; //Discount percentage [15]

        #Customer Information -->
        $config["first_name"]         = '';
        $config["last_name"]         = '';
        $config["address1"]         = '';
        $config["address2"]         = '';
        $config["city"]             = '';
        $config["state"]             = '';
        $config["zip"]                 = '';
        $config["email"]             = '';
        $config["night_phone_a"]     = '';
        $config["night_phone_b"]     = '';
        $config["night_phone_c"]     = '';
       
        /*
         * Convert array elements into class variables
         */
        if (count($props) > 0)
        {
            foreach ($props as $key => $val)
            {
                $config[$key] = $val;
            }
        }
        $this->config = $config;
    }
   
    // --------------------------------------------------------------------   
   
    /**
     * Perform payment process
     *
     * @access    public
     * @param    array
     * @return    void
     */   
    function pay(){
       
        #Convert the array to url encode variables
        $vars =  http_build_query($this->config);

        if($this->config['production'] == TRUE){
            header('LOCATION:'.$this->production_url.$vars);
        }else{
            header('LOCATION:'.$this->sandbox_url.$vars);
        }
    }
   
    // --------------------------------------------------------------------   
   
    /**
     * Add a product to the list
     *
     * @access    public
     * @param    array
     * @return    void
     */   
    function add($item_name = '',$item_amount = NULL,$item_qty = NULL,$item_number = NULL){
        $this->config['item_name_'.$this->item]     = $item_name;
        $this->config['amount_'.$this->item]         = $item_amount;
        $this->config['quantity_'.$this->item]         = $item_qty;
        $this->config['item_number_'.$this->item]     = $item_number;
        $this->item++;
    }   
}
// END Paypal Class

/* End of file Paypal.php */
/* Location: ./application/libraries/Paypal.php */

=============================================
 appication/controlers/payments.php
=============================================
<?php
Class Payments extends CI_Controller{
public function __construct()
{
    parent::__construct();
    $this->load->helper("string");
    $this->load->library('session');   
    $this->load->library('cart');
    $this->load->model('user_model');
    if($this->session->userdata('username')=='')
    {
        redirect(base_url());
    }
    error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
}
/*This will trigger to purchase item and go to paypal page*/

public function do_purchase()
{
   
       $arr['posted_project_details1']=$this->session->userdata('posted_project_details');
       $data = array_merge($arr, array('project_price'=>$this->input->post('project_price'),'project_commition'=>$this->input->post('commitions')));
       //print_r($data);die;
       $this->session->set_userdata($data);//finally stored full data of posted projected.
     
      //  echo "<pre>";print_r($this->session->userdata);die;
     
   
      
            $config['business']             = 'atulsharma6j87@gmail.com';
            $config['cpp_header_image']     = ''; //Image header url [750 pixels wide by 90 pixels high]
            $config['return']                 = base_url().'payments/success_payment';
            $config['cancel_return']         = base_url().'payments/cancel_payment';
            $config['notify_url']             = 'process_payment.php'; //IPN Post
            $config['production']             = FALSE; //Its false by default and will use sandbox
            $config["invoice"]                = random_string('numeric',8); //The invoice id
           
           
            $this->load->library('paypal',$config);
           
            #$this->paypal->add(<name>,<price>,<quantity>[Default 1],<code>[Optional]);
            //$this->input->post('project_price');
            $this->paypal->add($this->session->userdata['posted_project_details']['project_name'],$this->input->post('project_price')+$this->input->post('commitions')); //First item
            //$this->paypal->add('Pants',40);       //Second item
            //$this->paypal->add('Blowse',10,10,'B-199-26'); //Third item with code
           
            $this->paypal->pay(); //Proccess the payment
       

}

/* I want to update my database for the item that the payer had just purchased an item*/
public function success_payment()
{
   
   
   
    $imgdata=str_replace(" ", "_", $this->session->userdata['posted_project_details']['name']);
    $data=array(
            'fld_project_userid'=>$this->session->userdata('user_id'),
            'fld_project_title'=>$this->session->userdata['posted_project_details']['project_name'],
            'fld_project_description'=>$this->session->userdata['posted_project_details']['project_detail'],
            'fld_project_amount'=>$this->session->userdata['project_price'],
            'project_commition'=>$this->session->userdata['project_commition'],
            'category_name'=>$this->session->userdata['posted_project_details']['category_name'],
           
            'project_purpose'=>$this->session->userdata['posted_project_details']['project_purpose'],
            'other_detail'=>$this->session->userdata['posted_project_details']['other_detail'],
            'project_color'=>$this->session->userdata['posted_project_details']['project_color'],
            'contact_name'=>$this->session->userdata['posted_project_details']['contact_name'],
            'contact_number'=>$this->session->userdata['posted_project_details']['contact_number'],
            'files'=>time().'_'.$imgdata,
            'fld_project_date'=>strtotime(date("Y-m-d h:i:s", strtotime(date("Y-m-d h:i:s"))) . " +14 days"),
            'fld_date'=>time()
             );
           
           
            $file = file_get_contents("assets/temp/".$this->session->userdata['posted_project_details']['name']);
            file_put_contents("assets/project_doc/".time().'_'.$imgdata, $file);       
           $this->db->insert('posted_project',$data);
           $projectid=$this->db->insert_id();
           $data1=array('fld_project_id'=>$projectid,'fld_project_title'=>$this->session->userdata['posted_project_details']['project_name'],'fld_project_amount'=>$this->session->userdata['project_price'],'fld_credit'=>$this->session->userdata['project_price'],'project_commition'=>$this->session->userdata['project_commition'],'fld_debit'=>'0','transaction_message'=>'Deposit fee for project <font color="#00CCCC">'.$this->session->userdata['posted_project_details']['project_name'].'</font> (USD)','fld_payment_date'=>time(),
           'fld_user_id'=>$this->session->userdata('user_id'));
           $this->db->insert('project_payment',$data1);
          
            $this->db->where('designer', 'designer');
            $querys = $this->db->get("user");
            foreach ($querys->result() as $row)
            {   
            $data5=array('sender_id'=>$this->session->userdata('user_id'),'type_of_notification'=>'project base','recipient_id'=>$row->id,'project_title'=>$this->session->userdata['posted_project_details']['project_name'],'notification_message'=>'A new project submit by user.The project name is <b>'.$this->session->userdata['posted_project_details']['project_name'].'.</b> For More Detalis <a href='.base_url().'browsproject/browseprjectsingle>Click Here</a>');
           $this->db->insert('notification_messages',$data5);   
            }

          
           unlink("assets/temp/".$this->session->userdata['posted_project_details']['name']);
           $this->session->unset_userdata('posted_project_details');
           $this->session->unset_userdata('project_price');
      
           redirect(base_url().'project_start/start_project3?suc=suc');
          
}

public function do_payment()
{
   
      
            $config['business']             = 'business@gmail.com';
            $config['cpp_header_image']     = ''; //Image header url [750 pixels wide by 90 pixels high]
            $config['return']                 = base_url().'payments/successful_payment';
            $config['cancel_return']         = base_url().'payments/cancel_payment';
            $config['notify_url']             = 'process_payment.php'; //IPN Post
            $config['production']             = FALSE; //Its false by default and will use sandbox
            $config["invoice"]                = random_string('numeric',8); //The invoice id
           
           
            $this->load->library('paypal',$config);
           
            $this->paypal->add($this->session->userdata['new_project_data']['project_name'],$this->session->userdata['new_project_data']['project_price']+$this->session->userdata['new_project_data']['project_commition']+$this->session->userdata['new_project_data']['rush_amount']);
           
            $this->paypal->pay();
       

}


public function successful_payment()
{
    if($this->session->userdata['new_project_data']['img_name']!=''){
        $imgdata=str_replace(" ", "_", $this->session->userdata['new_project_data']['img_name']);
        $imgdata1=time().'_'.$imgdata;
        }
        else{$imgdata1='';}
    if($this->session->userdata['new_project_data']['hdn_cnt_amt']==0){
        $hidden_contest='0';
    }
    else{$hidden_contest='1';}
    $data=array(
            'fld_project_userid'=>$this->session->userdata('user_id'),
            'fld_project_title'=>$this->session->userdata['new_project_data']['project_name'],
            'fld_project_description'=>$this->session->userdata['new_project_data']['project_detail'],
            'fld_project_amount'=>$this->session->userdata['new_project_data']['project_price'],
            'project_commition'=>$this->session->userdata['new_project_data']['project_commition'],
            'category_name'=>$this->session->userdata['new_project_data']['category_name'],
           
            'project_purpose'=>$this->session->userdata['new_project_data']['project_purpose'],
            'other_detail'=>$this->session->userdata['new_project_data']['other_detail'],
            'project_color'=>$this->session->userdata['new_project_data']['project_color'],
            'contact_name'=>$this->session->userdata['new_project_data']['contact_name'],
            'contact_number'=>$this->session->userdata['new_project_data']['contact_number'],
            'files'=>$imgdata1,
            'project_length'=>$this->session->userdata['new_project_data']['project_length'],
            'rush_amount'=>$this->session->userdata['new_project_data']['rush_amount'],
            'rush_contest'=>strtotime(date("Y-m-d h:i:s", strtotime(date("Y-m-d h:i:s"))) . " +".$this->session->userdata['new_project_data']['rush_contest']." days"),
            'fld_project_date'=>strtotime(date("Y-m-d h:i:s", strtotime(date("Y-m-d h:i:s"))) . " +".$this->session->userdata['new_project_data']['project_length']." days"),
            'fld_date'=>time(),
            'hidden_contest'=>$hidden_contest,
            'payment_type'=>'Prepaid',
            'hdn_cnt_amt'=>$this->session->userdata['new_project_data']['hdn_cnt_amt']
             );
           
            if($this->session->userdata['new_project_data']['img_name']!=''){
            $file = file_get_contents("assets/temp/".$this->session->userdata['new_project_data']['img_name']);
            file_put_contents("assets/project_doc/".time().'_'.$imgdata, $file);                     }
           $this->db->insert('posted_project',$data);
           /*---------------for new contest-----------------------------------------------*/
          $to = $this->user_model->get_notification_email_id('2');
          $subject = "New Contest Entry";   
          $message =$this->user_model->get_email_template('2');
          $headers = "MIME-Version: 1.0" . "\r\n";
          $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
          $headers .= 'From: <info@'.$_SERVER['HTTP_HOST'].'>' . "\r\n";
          mail($to,$subject,$message,$headers);
            unlink("assets/temp/".$this->session->userdata['new_project_data']['img_name']);
          
           $filter = $this->session->userdata('new_project_data');
$index = array_search($i, $filter);
unset($filter[$index]);
$this->session->set_userdata('new_project_data', $filter);

 $filter1 = $this->session->userdata('posted_project_details');
$index1 = array_search($i, $filter1);
unset($filter1[$index1]);
$this->session->set_userdata('posted_project_details', $filter1);

 $filter2 = $this->session->userdata('project_data');
$index2 = array_search($i, $filter2);
unset($filter2[$index2]);
$this->session->set_userdata('project_data', $filter2);

redirect(base_url().'project_start/start_project3?suc=suc');
   
}

public function demo_contest(){
   
    if($this->session->userdata['new_project_data']['img_name']!=''){
        $imgdata=str_replace(" ", "_", $this->session->userdata['new_project_data']['img_name']);
        $imgdata1=time().'_'.$imgdata;
        }
        else{$imgdata1='';}
    if($this->session->userdata['new_project_data']['hdn_cnt_amt']==0){
        $hidden_contest='0';
    }
    else{$hidden_contest='1';}
    $data=array(
            'fld_project_userid'=>$this->session->userdata('user_id'),
            'fld_project_title'=>$this->session->userdata['new_project_data']['project_name'],
            'fld_project_description'=>$this->session->userdata['new_project_data']['project_detail'],
            'fld_project_amount'=>$this->session->userdata['new_project_data']['project_price'],
            'project_commition'=>$this->session->userdata['new_project_data']['project_commition'],
            'category_name'=>$this->session->userdata['new_project_data']['category_name'],
           
            'project_purpose'=>$this->session->userdata['new_project_data']['project_purpose'],
            'other_detail'=>$this->session->userdata['new_project_data']['other_detail'],
            'project_color'=>$this->session->userdata['new_project_data']['project_color'],
            'contact_name'=>$this->session->userdata['new_project_data']['contact_name'],
            'contact_number'=>$this->session->userdata['new_project_data']['contact_number'],
            'files'=>$imgdata1,
            'project_length'=>$this->session->userdata['new_project_data']['project_length'],
            'rush_amount'=>$this->session->userdata['new_project_data']['rush_amount'],
            'rush_contest'=>strtotime(date("Y-m-d h:i:s", strtotime(date("Y-m-d h:i:s"))) . " +".$this->session->userdata['new_project_data']['rush_contest']." days"),
            'fld_project_date'=>strtotime(date("Y-m-d h:i:s", strtotime(date("Y-m-d h:i:s"))) . " +".$this->session->userdata['new_project_data']['project_length']." days"),
            'fld_date'=>time(),
            'contest_type'=>'Demo Contest',
            'hidden_contest'=>$hidden_contest,
            'hdn_cnt_amt'=>$this->session->userdata['new_project_data']['hdn_cnt_amt']
             );
           
            if($this->session->userdata['new_project_data']['img_name']!=''){
            $file = file_get_contents("assets/temp/".$this->session->userdata['new_project_data']['img_name']);
            file_put_contents("assets/project_doc/".time().'_'.$imgdata, $file);                     }
           $this->db->insert('posted_project',$data);
           /*---------------for new contest-----------------------------------------------*/
          $to = $this->user_model->get_notification_email_id('2');
          $subject = "New Contest Entry";   
          $message =$this->user_model->get_email_template('2');
          $headers = "MIME-Version: 1.0" . "\r\n";
          $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
          $headers .= 'From: <info@'.$_SERVER['HTTP_HOST'].'>' . "\r\n";
          mail($to,$subject,$message,$headers);
            unlink("assets/temp/".$this->session->userdata['new_project_data']['img_name']);
          
           $filter = $this->session->userdata('new_project_data');
$index = array_search($i, $filter);
unset($filter[$index]);
$this->session->set_userdata('new_project_data', $filter);

 $filter1 = $this->session->userdata('posted_project_details');
$index1 = array_search($i, $filter1);
unset($filter1[$index1]);
$this->session->set_userdata('posted_project_details', $filter1);

 $filter2 = $this->session->userdata('project_data');
$index2 = array_search($i, $filter2);
unset($filter2[$index2]);
$this->session->set_userdata('project_data', $filter2);

redirect(base_url().'project_start/start_project3?suc=suc');
   
}

/*Cancel payment*/
public function cancel_payment(){
//$received_data=print_r($this->input->post(),true);
    //echo "<pre>".$received_data."</pre>";
    echo "<h1>Your Payment is Cancel</h1>";
    echo '<META HTTP-EQUIV=REFRESH CONTENT="1; URL='.base_url().'>';
}

===================================
application/view/payment_type.php
======================================
<?php
$data=$this->session->userdata('new_project_data');
//print_r($data);
$fld_project_amount=$this->session->userdata['new_project_data']['project_price'];
$project_commition=$this->session->userdata['new_project_data']['project_commition'];
$rush_amount=$this->session->userdata['new_project_data']['rush_amount'];
$hdn_cnt_amt=$this->session->userdata['new_project_data']['hdn_cnt_amt'];

$total_amount=$fld_project_amount+$rush_amount+$project_commition+$hdn_cnt_amt;
$cat_name=$this->page_model->get_cat_name($this->session->userdata['new_project_data']['category_name']);
?>
<style>
.selected {
    border-color:#F00 !important;
  }
  .f1{width: 100%;
  float: left;
  height: 100px;}
  .f2{float: left;
  margin: 10px 10px 0 70px;
  width: 50%;}
  .f3{float: right;
  margin: 10px 0 0 4px;
  width: 30%;}
</style>
<script>

</script>
<section class="fl row gry">
  <div class="container">
    <div class="cv_row">
      <div class="cv_row_header">
        <link href="<?php echo HTTP_CSS_PATH; ?>artist.css" rel="stylesheet" type="text/css" media="all" />
        <h1><span><a href="<?php echo base_url()?>">Home</a> / Start a Project</span></h1>
      </div>
    </div>
    <div class="side-col-layout">
      <div class="full">
        <div class="head">
          <h3>Start A Project</h3>
        </div>
         <?php  if($this->session->userdata('logged_in')==FALSE && $this->session->userdata('username')!=''){?><div class="form-content text" style="text-align:center;"><h1><?php echo "Please Verify Your Account!";?></h1></div><?php }?>
        <div class="process_bar">
          <ul>
            <li class="num done"><a href="<?php echo base_url(); ?>project_start/start_project"></a><span>Choose a category</span></li>
            <li class="bar done"></li>
            <li class="num done"><a href="<?php echo base_url(); ?>project_start/start_project1?first=<?=$this->session->userdata('cat_id');?>"></a><span>Give us details</span></li>
            <li class="bar select"></li>
            <li class="num select"><a href="javascript://">3</a><span>Decide on a budget</span></li>
            <li class="bar"></li>
            <li class="num"><a href="javascript://">4</a><span>Launch your project</span></li>
          </ul>
          <div class="clr"></div>
        </div>
        <div class="form-content">
          <h1><?php echo $cat_name;?> Contest for <?php echo $this->session->userdata['new_project_data']['project_name'];?><br></h1>
          <hr />
          <div class="f1">
          <?php if($rush_amount!='0' || $hdn_cnt_amt!='0'){?>
          <div class="f2">Listing fee &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Prize&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Upgrades<br /><h3>$<?php echo $project_commition;?> &nbsp;&nbsp;+ &nbsp;&nbsp;$<?php echo $fld_project_amount;?>&nbsp;&nbsp;+&nbsp;&nbsp;$<?php echo $rush_amount+$hdn_cnt_amt;?></h3></div>
          <?php } else {?>
          <div class="f2">Listing fee &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Prize<br /><h3>$<?php echo $project_commition;?> &nbsp;&nbsp;+ &nbsp;&nbsp;$<?php echo $fld_project_amount;?></h3></div>
          <?php } ?>
         
           <div class="f3">Total due now<br /> <h3>$<?php echo $total_amount;?> USD</h3></div>
                                                 
         </div>
         <hr />
           <!--- <form action="payments/do_purchase" method="post">------------>
            <?php
            echo form_open('payments/do_payment');
          
            ?>
           
            
              
            <p> Click here to pay with
                <input type="image" id="paypal" src="<?php echo base_url()?>assets/images/paypal.png" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
              </p>
         <?php echo form_close();?>
          <p class="dollar">OR</p>
          <p><img width="32" height="32" alt="" src="<?php echo base_url()?>assets/images/mastercard.png" id="u20282_img" class="block">
            <!-- image -->
            &nbsp;&nbsp;<img width="32" height="32" alt="" src="<?php echo base_url()?>assets/images/visa.png" id="u20292_img" class="block">&nbsp;&nbsp;
            <!-- image -->
            <img width="32" height="32" alt="" src="<?php echo base_url()?>assets/images/amex.png" id="u20272_img" class="block">&nbsp;&nbsp;
            <!-- image -->
            <img width="32" height="32" alt="" src="<?php echo base_url()?>assets/images/discover.png" id="u20277_img" class="block"> </p>
         
        </div>
        <div class="clr"></div>
      </div>
    </div>
  </div>
</section>

================ End =================================