Your IP : 216.73.216.93


Current Path : /home/users/unlimited/www/admin.ondemand.codeskitter.site/app/Libraries/
Upload File :
Current File : /home/users/unlimited/www/admin.ondemand.codeskitter.site/app/Libraries/Paypal.php

<?php

namespace App\Libraries;
// if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * PayPal Library for CodeIgniter 3.x
 *
 * Library for PayPal payment gateway. It helps to integrate PayPal payment gateway
 * in the CodeIgniter application.
 *
 * It requires PayPal configuration file and it should be placed in the config directory.
 *
 * @package     CodeIgniter
 * @category    Libraries
 * @author      CodexWorld
 * @license     http://www.codexworld.com/license/
 * @link        http://www.codexworld.com
 * @version     2.0
 */

class Paypal
{
    var $paypal_url;
    var $last_error;
    var $ipn_log;
    var $ipn_log_file;
    var $ipn_response;
    var $ipn_data = array();
    var $fields = array();
    var $submit_btn = '';
    var $button_path = '';
    var $CI;
    protected string $refund_url,$token_url,$paypal_client_key,$paypal_secret_key,$paypal_lib; // Explicitly declare the $refund_url property

    function __construct()
    {
     
        helper('form'); 

        helper('url');

        helper('paypal');
        
        
        $settings = get_settings('payment_gateways_settings', true);
            

        if(!empty($settings['paypal_mode'])){

            $sandbox = ($settings['paypal_mode']==="sandbox")?TRUE:FALSE;
        }else{
            $sandbox =TRUE;
        }
             
     
        $this->paypal_url = ($sandbox == TRUE) ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr';
        $this->refund_url=($sandbox == TRUE) ?"https://api-m.sandbox.paypal.com/v2/payments/captures/":"https://api-m.paypal.com/v2/payments/captures/";
        $this->token_url=($sandbox == TRUE) ?"https://api.sandbox.paypal.com/v1/oauth2/token":"   ";

        
        if(!empty($settings['paypal_mode'])){
            $this->paypal_client_key=$settings['paypal_client_key'];
           
        }else{
            $this->paypal_client_key="";
        }
        

        if(!empty($settings['paypal_mode'])){
            $this->paypal_secret_key=$settings['paypal_secret_key'];
           
        }else{
            $this->paypal_secret_key="";
        }
        
        
        $this->last_error = '';
        $this->ipn_response = '';

        $this->ipn_log_file = config('paypal_lib_ipn_log_file');
        $this->ipn_log = config('paypal_lib_ipn_log');

        $this->button_path = config('paypal_lib_button_path');

        // populate $fields array with a few default values.


        if(!empty($settings['paypal_mode'])){
            $businessEmail = $settings['paypal_business_email'];
        }else{
           $businessEmail="";
        }
        
       
        $this->add_field('business', $businessEmail);
        $this->add_field('rm', '2');
        $this->add_field('cmd', '_xclick');

        if(!empty($settings['paypal_mode'])){
       
            $this->add_field('currency_code', $settings['paypal_currency_code']);
        }else{
            $this->add_field('currency_code', "USD");
        }


        $this->add_field('quantity', '1');
        $this->button('Pay Now!');
    }



    
    function button($value)
    {
        // changes the default caption of the submit button
        $this->submit_btn = form_submit('pp_submit', $value, 'class="btn btn-primary"');
    }

    function image($file)
    {
        $this->submit_btn = '<input type="image" name="add" src="' . base_url(rtrim($this->button_path, '/') . '/' . $file) . '" border="0" />';
    }

    function add_field($field, $value)
    {
        // adds a key=>value pair to the fields array
        $this->fields[$field] = $value;
    }

    function paypal_auto_form()
    {
        // form with hidden elements which is submitted to paypal
        $this->button('Click here if you\'re not automatically redirected...');

        echo '<html>' . "\n";
        echo '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Processing Payment.. Please wait.. | Telefoniim.com</title>
        <link href="' . base_url('assets/img/favicon.png') . '" rel="shortcut icon" type="image/ico" />
        <link href="' . base_url('assets/css/bootstrap.min.css') . '" rel="stylesheet" type="text/css" />
        </head>' . "\n";
        echo '<body style="text-align:center; font-size:3em;" onLoad="document.forms[\'paypal_auto_form\'].submit();">' . "\n";
        echo '<p style="text-align:center;">Please wait, your order is being processed and you will be redirected to the paypal website.</p>' . "\n";
        echo $this->paypal_form('paypal_auto_form');
        echo '</body></html>';
    }

    function paypal_form($form_name = 'paypal_form')
    {
        $str = '';
        $str .= '<form method="post" action="' . $this->paypal_url . '" name="' . $form_name . '"/>' . "\n";
        // $str .= '<input type="hidden" name="paymentaction" value="authorization" />';
        foreach ($this->fields as $name => $value)  
            $str .= form_hidden($name, $value) . "\n";
        $str .= '<p><img src="' . base_url('public/frontend/retro/load.gif') . '" alt="Please wait.. Loading" title="Please wait.. Loading.." width="140px" /></p>';
        $str .= '<p>' . $this->submit_btn . '</p>';
        $str .= form_close() . "\n";

        return $str;
    }

    function validate_ipn($paypalReturn)
    {
        $ipn_response = $this->curlPost($this->paypal_url, $paypalReturn);
          log_message('error', '$ipn_response ---'.print_r($paypalReturn));
        if (preg_match("/VERIFIED/i", $ipn_response)) {
            // Valid IPN transaction.
            return true;
        } else {
            // Invalid IPN transaction.  Check the log for details.
            $this->last_error = 'IPN Validation Failed.';
            $this->log_ipn_results(false);
            return false;
        }
    }

    function log_ipn_results($success)
    {
        if (!$this->ipn_log) return;  // is logging turned off?

        // Timestamp
        $text = '[' . date('m/d/Y g:i A') . '] - ';

        // Success or failure being logged?
        if ($success) $text .= "SUCCESS!\n";
        else $text .= 'FAIL: ' . $this->last_error . "\n";

        // Log the POST variables
        $text .= "IPN POST Vars from Paypal:\n";
        foreach ($this->ipn_data as $key => $value)
            $text .= "$key=$value, ";

        // Log the response from the paypal server
        $text .= "\nIPN Response from Paypal Server:\n " . $this->ipn_response;

        // Write to log
        $fp = fopen($this->ipn_log_file, 'a');
        fwrite($fp, $text . "\n\n");

        fclose($fp);  // close file
    }

    function dump()
    {
        // Used for debugging, this function will output all the field/value pairs
        ksort($this->fields);
        echo '<h2>ppal->dump() Output:</h2>' . "\n";
        echo '<code style="font: 12px Monaco, \'Courier New\', Verdana, Sans-serif;  background: #f9f9f9; border: 1px solid #D0D0D0; color: #002166; display: block; margin: 14px 0; padding: 12px 10px;">' . "\n";
        foreach ($this->fields as $key => $value) echo '<strong>' . $key . '</strong>:    ' . urldecode($value) . '<br/>';
        echo "</code>\n";
    }

    function curlPost($paypal_url, $paypal_return_arr)
    {
        
        $req = 'cmd=_notify-validate';
        foreach ($paypal_return_arr as $key => $value) {
            $value = urlencode(stripslashes($value));
            $req .= "&$key=$value";
        }

        $ipn_site_url = $paypal_url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $ipn_site_url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

    // public function refund($txn_id, $amount)
    // {
    //     $amount = ($amount * 100);
    //     $data = array(
    //         'transaction' => $txn_id,
    //         'amount' => $amount,
    //     );
    //     $url = $this->refund_url . '/'.$txn_id.'/refund'; 
    //     $method = 'POST';
    //     $response = $this->curl_request($url, $method, $data);
    //     print_R($url);
    //     die;
    //     if (isset($response['http_code']) && $response['http_code'] == '200') {
    //         $res = json_decode($response['body'], true);
    //         return $res;
    //     } else {
    //         return $response;
    //     }
    // }
    
    public function refund($txn_id, $amount,$currency=null)
    {
        
        
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->refund_url.$txn_id.'/refund',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_USERPWD =>   $this->paypal_client_key . ":" . $this->paypal_secret_key,
            CURLOPT_POSTFIELDS =>'{"amount": {
              "value": "'.$amount.'",
              "currency_code": "USD"
            }}',
            CURLOPT_HTTPHEADER => array(
              'Content-Type: application/json',
            ),
          ));
          $response = curl_exec($curl);
          curl_close($curl);
        
    

        if (isset($response['http_code']) && $response['http_code'] == '200') {
                $res = json_decode($response['body'], true);
                return $res;
        } else {
                return $response;
        }
    
        }
    public function curl_request($end_point, $method, $data = array())
    {
        $this->curl = curl_init();

        $token=$this->generate_token();
        curl_setopt_array($this->curl, array(
            CURLOPT_URL => $end_point,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => strtoupper($method),
            CURLOPT_POSTFIELDS => $data,   /* example array('test_key' => 'test_value_1') */
            CURLOPT_HTTPHEADER => array(
                "Authorization: Bearer " . $token,
                "Accept: application/json",
            ),
            ));
        $response = curl_exec($this->curl);
    
        curl_close($this->curl);
        return $response;
    }

//  https://api-m.sandbox.paypal.com
    // public function generate_token(){
    //     $PAYPAL_CLIENT_ID=$this->paypal_client_key;
    //     $PAYPAL_SECRET=$this->paypal_secret_key;
    //     $curl = curl_init();
    //     curl_setopt_array($curl, array(
    //     CURLOPT_URL => "https://api-m.sandbox.paypal.com/v1/oauth2/token",
    //     CURLOPT_RETURNTRANSFER => true,
    //     CURLOPT_ENCODING => "",
    //     CURLOPT_MAXREDIRS => 10,
    //     CURLOPT_TIMEOUT => 30,
    //     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    //     CURLOPT_CUSTOMREQUEST => "POST",
    //     CURLOPT_USERPWD => $PAYPAL_CLIENT_ID.":".$PAYPAL_SECRET,
    //     CURLOPT_POSTFIELDS => "grant_type=client_credentials",
    //     CURLOPT_HTTPHEADER => array(
    //     "Accept: application/json",
    //     "Accept-Language: en_US"
    //     ),
    //     ));
    
    //     $result= curl_exec($curl);
        
    //     $array=json_decode($result, true); 
    //     $token=$array['access_token'];
    
    //     return    $token;
    // }
    
    public function generate_token() {
    $PAYPAL_CLIENT_ID = $this->paypal_client_key;
    $PAYPAL_SECRET = $this->paypal_secret_key;
    $scopes = "https://uri.paypal.com/services/payments/refund ";

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api-m.sandbox.paypal.com/v1/oauth2/token",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_USERPWD => $PAYPAL_CLIENT_ID . ":" . $PAYPAL_SECRET,
        CURLOPT_POSTFIELDS => "grant_type=client_credentials&scope=" . urlencode($scopes),
        CURLOPT_HTTPHEADER => array(
            "Accept: application/json",
            "Accept-Language: en_US"
        ),
    ));

    $result = curl_exec($curl);
    $array = json_decode($result, true);
   
    $token = $array['access_token'];

    return $token;
}

}