Beispiel #1
0
 public function content()
 {
     # Displays the page
     global $style, $db, $main, $invoice, $server;
     if ($_GET['invoiceID']) {
         require_once "../includes/paypal/paypal.class.php";
         $paypal = new paypal_class();
         if ($paypal->validate_ipn()) {
             $invoice->set_paid(mysql_real_escape_string($_GET['invoiceID']));
             $main->errors("Your invoice has been paid!");
             $client = $db->fetch_array($db->query("SELECT * FROM `<PRE>user_packs` WHERE `userid` = '{$_SESSION['cuser']}'"));
             if ($client['status'] == '2') {
                 $server->unsuspend($client['id']);
             }
         } else {
             $main->errors("Your invoice hasn't been paid!");
         }
     }
     // List invoices. :)
     $query = $db->query("SELECT * FROM `<PRE>invoices` WHERE `uid` = '{$_SESSION['cuser']}' ORDER BY `id` ASC");
     $userdata = mysql_fetch_row($db->query("SELECT `user`,`firstname`,`lastname` FROM `<PRE>users` WHERE `id` = {$_SESSION['cuser']}"));
     $domain = mysql_fetch_row($db->query("SELECT `domain` FROM `<PRE>user_packs` WHERE `userid` = {$_SESSION['cuser']}"));
     $extra = array("userinfo" => "{$userdata['2']}, {$userdata['1']} ({$userdata['0']})", "domain" => $domain[0]);
     $array2['list'] = "";
     while ($array = $db->fetch_array($query)) {
         $array['due'] = strftime("%D", $array['due']);
         $array["paid"] = $array["is_paid"] == 1 ? "<span style='color:green;font-size:20px;'>Paid</span>" : "<span style='color:red;font-size:20px;'>Unpaid</span>";
         $array["pay"] = $array["is_paid"] == 0 ? '<input type="button" name="pay" id="pay" value="Pay Now" onclick="doswirl(\'' . $array['id'] . '\')" />' : '';
         $array['amount'] = $array['amount'] . " " . $db->config("currency");
         $array2['list'] .= $style->replaceVar("tpl/invoices/invoice-list-item.tpl", array_merge($array, $extra));
     }
     $array2['num'] = mysql_num_rows($query);
     echo $style->replaceVar("tpl/invoices/client-page.tpl", $array2);
 }
Beispiel #2
0
 public function ValidateNotification($txn_id = null)
 {
     parent::ValidateNotification($txn_id);
     $paypal = new paypal_class();
     $paypal->paypal_mail = $config['account'];
     $result = $paypal->validate_ipn();
     return $result;
 }
 public function load()
 {
     $AppConfig = $GLOBALS['AppConfig'];
     $p = new paypal_class();
     $m = new PaymentModel();
     if (!isset($_GET['action']) || empty($_GET['action'])) {
         $GLOBALS['_GET']['action'] = "process";
     }
     switch ($_GET['action']) {
         case "process":
             return;
         case "success":
             if ($this->isPost()) {
                 echo "<html><head><title>Success</title></head><body><h3>Thank you for your order.</h3>";
                 $m->dispose();
                 echo "</body></html>";
             }
             break;
         case "cancel":
             echo "<html><head><title>Canceled</title></head><body><h3>The order was canceled.</h3>";
             echo "</body></html>";
             break;
         case "ipn":
             if ($p->validate_ipn()) {
                 break;
             }
             $subject = "Instant Payment Notification - Recieved Payment";
             $to = $AppConfig['system']['email'];
             $body = "An instant payment notification was successfully recieved\n";
             $body .= "from " . $p->ipn_data['payer_email'] . " on " . date("m/d/Y");
             $body .= " at " . date("g:i A") . "\n\nDetails:\n";
             foreach ($p->ipn_data as $key => $value) {
                 $body .= "\n{$key}: {$value}";
             }
             @mail($to, $subject, $body);
             $usedPackage = NULL;
             foreach ($AppConfig['plus']['packages'] as $package) {
                 if ($package['cost'] == $p->ipn_data['payment_gross']) {
                     $usedPackage = $package;
                 }
             }
             $Player = base64_decode($p->ipn_data['custom']);
             $m = new PaymentModel();
             $m->incrementPlayerGold($Player, $usedPackage);
             $m->dispose();
     }
 }
 function get_response($action = null)
 {
     // pr($action);die;
     //require_once('paypal.class.php');
     $p = new paypal_class();
     if (Configure::read('Payment.paypal_sandbox')) {
         $p->paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
     } else {
         $p->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
     }
     //$this_script = 'MYDOMAIN.COM/paypal.php';
     $this_script = Configure::read('App.Siteurl') . 'payments/paypal_response/';
     switch ($action) {
         case 'ipn':
             $this->test_log();
             if ($p->validate_ipn()) {
             }
             break;
     }
 }
Beispiel #5
0
<?php

include "../../_setup.php";
include "classes/donate-paypalclass.php";
include "classes/donation.php";
include "classes/campaign.php";
$donationPlugin = new btPlugin($mysqli);
if ($donationPlugin->selectByName("Donations")) {
    $donationObj = new Donation($mysqli);
    $p = new paypal_class();
    $arrColumns = array("donationcampaign_id", "member_id", "name", "message", "datesent", "amount", "paypalemail", "transaction_id", "response");
    $p->setMode($donationPlugin->getConfigInfo("mode"));
    if ($p->validate_ipn() && $p->ipn_data['payment_status'] != "Failed" && $p->ipn_data['payment_status'] != "Denied") {
        $member = new Member($mysqli);
        $campaignObj = new DonationCampaign($mysqli);
        $arrData = $p->ipn_data;
        $data = json_encode($arrData);
        $customVars = json_decode($arrData['custom'], true);
        if ($campaignObj->select($customVars['campaign_id']) && $member->select($customVars['member_id'])) {
            $campaignName = $campaignObj->get_info_filtered("title");
            $medalID = $campaignObj->get_info("awardmedal");
            $member->awardMedal($medalID, "Donated to " . $campaignName . " campaign");
        }
        $arrValues = array($customVars['campaign_id'], $customVars['member_id'], $customVars['name'], $customVars['message'], time(), $arrData['mc_gross'], $arrData['payer_email'], $arrData['txn_id'], $data);
        $donationObj->addNew($arrColumns, $arrValues);
    } else {
        $data = json_encode($p->ipn_data);
        $data = "ERROR: - " . $p->last_error . " - " . $data;
        $donationObj->logError($data);
    }
}
Beispiel #6
0
        echo "<h1>Transaction Cancelled";
        break;
    case "ipn":
        // IPN case to receive payment information. this case will not displayed in browser. This is server to server communication. PayPal will send the transactions each and every details to this case in secured POST menthod by server to server.
        $trasaction_id = $_POST["txn_id"];
        $payment_status = strtolower($_POST["payment_status"]);
        $invoice = $_POST["invoice"];
        $log_array = print_r($_POST, TRUE);
        $log_query = "SELECT * FROM `paypal_log` WHERE `txn_id` = '{$trasaction_id}'";
        $log_check = mysql_query($log_query);
        if (mysql_num_rows($log_check) <= 0) {
            mysql_query("INSERT INTO `paypal_log` (`txn_id`, `log`, `posted_date`) VALUES ('{$trasaction_id}', '{$log_array}', NOW())");
        } else {
            mysql_query("UPDATE `paypal_log` SET `log` = '{$log_array}' WHERE `txn_id` = '{$trasaction_id}'");
        }
        // Save and update the logs array
        $paypal_log_fetch = mysql_fetch_array(mysql_query($log_query));
        $paypal_log_id = $paypal_log_fetch["id"];
        if ($p->validate_ipn()) {
            // validate the IPN, do the others stuffs here as per your app logic
            mysql_query("UPDATE `purchases` SET `trasaction_id` = '{$trasaction_id} ', `log_id` = '{$paypal_log_id}', `payment_status` = '{$payment_status}' WHERE `invoice` = '{$invoice}'");
            $subject = 'Instant Payment Notification - Recieved Payment';
            $p->send_report($subject);
            // Send the notification about the transaction
        } else {
            $subject = 'Instant Payment Notification - Payment Fail';
            $p->send_report($subject);
            // failed notification
        }
        break;
}
Beispiel #7
0
 function paypal()
 {
     require_once 'paypal.class.php';
     // include the class file
     if (isset($_POST['sub'])) {
         $plan = explode('##', $_POST['plan']);
         $amt = $plan[0];
         $p_id = $plan[1];
         $this->load->model('Plan_Model');
         $query = $this->Plan_Model->plan($p_id);
         $desc = $query[0]->plan_desc;
         $p = new paypal_class();
         // initiate an instance of the class
         $p->paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
         // testing paypal url
         //$p->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';     // paypal url
         $total_amt = $this->uri->segment(3);
         $total_amt = $this->uri->segment(3);
         $this_script = $this->config->item('base_url');
         if (empty($_GET['action'])) {
             $_GET['action'] = 'process';
         }
         switch ($_GET['action']) {
             case 'process':
                 // Process and order...
                 $p->add_field('business', '*****@*****.**');
                 $p->add_field('return', $this_script . 'payment/thanks');
                 $p->add_field('cancel_return', $this_script . 'payment/cancel');
                 $p->add_field('notify_url', $this_script . 'action=ipn');
                 $p->add_field('item_name', $desc);
                 $p->add_field('custom', '24');
                 $p->add_field('amount', $amt);
                 $p->add_field('currency_code', 'USD');
                 $p->submit_paypal_post();
                 // submit the fields to paypal
                 //$p->dump_fields();      // for debugging, output a table of all the fields
                 break;
             case 'success':
                 // Order was successful...
                 $response = $_POST;
                 echo "<html><head><title>Success</title></head><body><h3>Thank you for your order.</h3>";
                 foreach ($_POST as $key => $value) {
                     print_r($value);
                 }
                 //echo "$key: $value<br>"; }
                 echo "</body></html>";
                 die;
                 break;
             case 'cancel':
                 // Order was canceled...
                 // The order was canceled before being completed.
                 echo "<html><head><title>Canceled</title></head><body><h3>The order was canceled.</h3>";
                 echo "</body></html>";
                 break;
             case 'ipn':
                 // Paypal is calling page for IPN validation...
                 if ($p->validate_ipn()) {
                     $subject = 'Instant Payment Notification - Recieved Payment';
                     $to = '*****@*****.**';
                     //  your email
                     $body = "An instant payment notification was successfully recieved\n";
                     $body .= "from " . $p->ipn_data['payer_email'] . " on " . date('m/d/Y');
                     $body .= " at " . date('g:i A') . "\n\nDetails:\n";
                     foreach ($p->ipn_data as $key => $value) {
                         $body .= "\n{$key}: {$value}";
                     }
                     mail($to, $subject, $body);
                 }
                 break;
         }
     }
     die;
 }
 public function process_payment($form_id, $reg_data, $service, $request)
 {
     //echo "<pre>"; var_dump($_GET); die;
     $payment_fields = array();
     foreach ($request->req as $field_name => $field_value) {
         if (substr($field_name, 0, 5) === 'Price') {
             $payment_fields[$field_name] = $field_value;
         }
     }
     //echo "<br>id= ".explode("_", $field_name)[2];
     //var_dump($payment_fields);
     //die;
     $sandbox = parent::get_setting('paypal_test_mode');
     $paypal_email = parent::get_setting('paypal_email');
     $currency = parent::get_setting('currency');
     $paypal_page_style = parent::get_setting('paypal_page_style');
     require_once plugin_dir_path(plugin_dir_path(__FILE__)) . 'external/PayPal/paypal.php';
     $p = new paypal_class();
     // paypal class
     if ($sandbox == 'yes') {
         $p->toggle_sandbox(true);
     } else {
         $p->toggle_sandbox(false);
     }
     $p->admin_mail = get_option('admin_email');
     // set notification email
     if (isset($request->req['rm_pproc'])) {
         switch ($request->req['rm_pproc']) {
             case 'success':
                 if (isset($request->req['rm_pproc_id'])) {
                     $log_id = $request->req['rm_pproc_id'];
                     $log = RM_DBManager::get_row('PAYPAL_LOGS', $log_id);
                     if ($log) {
                         if ($log->log) {
                             $paypal_log = maybe_unserialize($log->log);
                             $payment_status = $paypal_log['payment_status'];
                             if ($payment_status == 'Completed') {
                                 echo '<div id="rmform">';
                                 echo "<div class='rminfotextfront'>" . RM_UI_Strings::get("MSG_PAYMENT_SUCCESS") . "</br>";
                                 echo '</div></div>';
                                 return 'success';
                             } else {
                                 if ($payment_status == 'Denied' || $payment_status == 'Failed' || $payment_status == 'Refunded' || $payment_status == 'Reversed' || $payment_status == 'Voided') {
                                     echo '<div id="rmform">';
                                     echo "<div class='rminfotextfront'>" . RM_UI_Strings::get("MSG_PAYMENT_FAILED") . "</br>";
                                     echo '</div></div>';
                                     return 'failed';
                                 } else {
                                     if ($payment_status == 'In-Progress' || $payment_status == 'Pending' || $payment_status == 'Processed') {
                                         echo '<div id="rmform">';
                                         echo "<div class='rminfotextfront'>" . RM_UI_Strings::get("MSG_PAYMENT_PENDING") . "</br>";
                                         echo '</div></div>';
                                         return 'pending';
                                     } else {
                                         if ($payment_status == 'Canceled_Reversal') {
                                             return 'canceled_reversal';
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
                 return false;
             case 'cancel':
                 echo '<div id="rmform">';
                 echo "<div class='rminfotextfront'>" . RM_UI_Strings::get("MSG_PAYMENT_CANCEL") . "</br>";
                 echo '</div></div>';
                 return;
             case 'ipn':
                 $trasaction_id = $_POST["txn_id"];
                 $payment_status = $_POST["payment_status"];
                 $cstm = $_POST["custom"];
                 $abcd = explode("|", $cstm);
                 $user_id = (int) $abcd[1];
                 $acbd = explode("|", $cstm);
                 $log_entry_id = (int) $acbd[0];
                 //$_POST["custom"];
                 $log_array = maybe_serialize($_POST);
                 $curr_date = RM_Utilities::get_current_time();
                 // date_i18n(get_option('date_format'));
                 RM_DBManager::update_row('PAYPAL_LOGS', $log_entry_id, array('status' => $payment_status, 'txn_id' => $trasaction_id, 'posted_date' => $curr_date, 'log' => $log_array), array('%s', '%s', '%s', '%s'));
                 if ($p->validate_ipn()) {
                     //IPN is valid, check payment status and process logic
                     if ($payment_status == 'Completed') {
                         if ($user_id) {
                             $gopt = new RM_Options();
                             $this->user_service->activate_user_by_id($user_id);
                         }
                         return 'success';
                     } else {
                         if ($payment_status == 'Denied' || $payment_status == 'Failed' || $payment_status == 'Refunded' || $payment_status == 'Reversed' || $payment_status == 'Voided') {
                             return 'failed';
                         } else {
                             if ($payment_status == 'In-Progress' || $payment_status == 'Pending' || $payment_status == 'Processed') {
                                 return 'pending';
                             } else {
                                 if ($payment_status == 'Canceled_Reversal') {
                                     return 'canceled_reversal';
                                 }
                             }
                         }
                     }
                     //Send mail notifications about payment success.
                     /* $recipients = parent::get_setting('admin_email');
                     
                                               if ($recipients)
                                               {
                                               $recipients = explode(',', $recipients);
                     
                                               foreach ($recipients as $recipient)
                                               {
                                               $p->send_report($recipient);
                                               }
                                               } */
                     return 'unknown';
                 }
                 return 'invalid_ipn';
         }
         //return;
     }
     $paypal_field = new RM_PayPal_Fields();
     $prices = array();
     $item_names = array();
     foreach ($payment_fields as $pf_name => $pf_value) {
         $abe = explode("_", $pf_name);
         $paypal_field->load_from_db((int) $abe[2]);
         switch ($paypal_field->get_type()) {
             case "fixed":
                 $prices[] = $paypal_field->get_value();
                 $item_names[] = $paypal_field->get_name();
                 break;
             case "userdef":
                 if ($pf_value == "") {
                     break;
                 }
                 $prices[] = $pf_value;
                 $item_names[] = $paypal_field->get_name();
                 break;
             case "multisel":
                 $tmp_v = maybe_unserialize($paypal_field->get_option_price());
                 $tmp_l = maybe_unserialize($paypal_field->get_option_label());
                 foreach ($pf_value as $pf_single_val) {
                     $index = (int) substr($pf_single_val, 1);
                     if (!isset($tmp_v[$index])) {
                         continue;
                     }
                     $prices[] = $tmp_v[$index];
                     $item_names[] = $tmp_l[$index];
                 }
                 break;
             case "dropdown":
                 $tmp_v = maybe_unserialize($paypal_field->get_option_price());
                 $tmp_l = maybe_unserialize($paypal_field->get_option_label());
                 //Check whether dropdown was not submitted
                 if (!$pf_value) {
                     break;
                 }
                 $index = (int) substr($pf_value, 1);
                 if (!isset($tmp_v[$index])) {
                     break;
                 }
                 $prices[] = $tmp_v[$index];
                 $item_names[] = $tmp_l[$index];
                 break;
         }
     }
     /*
      echo "<br><br>========  names =============<br><br>";
      var_dump($item_names);
      echo "<br><br>========  prices =============<br><br>";
      var_dump($prices);
      die;
     */
     $this_script = get_permalink();
     $sign = strpos($this_script, '?') ? '&' : '?';
     $i = 1;
     foreach ($item_names as $item_name) {
         $p->add_field('item_name_' . $i, $item_name);
         $i++;
     }
     $i = 1;
     $total_amount = 0.0;
     foreach ($prices as $price) {
         $p->add_field('amount_' . $i, $price);
         $total_amount += floatval($price);
         $i++;
     }
     $invoice = (string) date("His") . rand(1234, 9632);
     $p->add_field('business', $paypal_email);
     // Call the facilitator eaccount
     $p->add_field('cmd', '_cart');
     // cmd should be _cart for cart checkout
     $p->add_field('upload', '1');
     $p->add_field('return', $this_script . $sign . 'rm_pproc=success&rm_pproc_id=');
     // return URL after the transaction got over
     $p->add_field('cancel_return', $this_script . $sign . 'rm_pproc=cancel');
     // cancel URL if the trasaction was cancelled during half of the transaction
     $p->add_field('notify_url', $this_script . $sign . 'rm_pproc=ipn');
     // Notify URL which received IPN (Instant Payment Notification)
     $p->add_field('currency_code', $currency);
     $p->add_field('invoice', $invoice);
     $p->add_field('page_style', $paypal_page_style);
     //Insert into PayPal log table
     $curr_date = RM_Utilities::get_current_time();
     //date_i18n(get_option('date_format'));
     if ($total_amount <= 0.0) {
         $log_entry_id = RM_DBManager::insert_row('PAYPAL_LOGS', array('submission_id' => $reg_data->submission_id, 'form_id' => $form_id, 'invoice' => $invoice, 'status' => 'Completed', 'total_amount' => $total_amount, 'currency' => $currency, 'posted_date' => $curr_date), array('%d', '%d', '%s', '%s', '%f', '%s', '%s'));
         return 'zero_amount';
     } else {
         $log_entry_id = RM_DBManager::insert_row('PAYPAL_LOGS', array('submission_id' => $reg_data->submission_id, 'form_id' => $form_id, 'invoice' => $invoice, 'status' => 'Pending', 'total_amount' => $total_amount, 'currency' => $currency, 'posted_date' => $curr_date), array('%d', '%d', '%s', '%s', '%f', '%s', '%s'));
     }
     $p->add_field('custom', $log_entry_id . "|" . $reg_data->user_id);
     $p->add_field('return', $this_script . $sign . 'rm_pproc=success&rm_pproc_id=' . $log_entry_id);
     // return URL after the transaction got over
     $p->add_field('cancel_return', $this_script . $sign . 'rm_pproc=cancel&rm_pproc_id=' . $log_entry_id);
     // cancel URL if the trasaction was cancelled during half of the transaction
     $p->add_field('notify_url', $this_script . $sign . 'rm_pproc=ipn');
     // Notify URL which received IPN (Instant Payment Notification)
     $p->submit_paypal_post();
     // POST it to paypal
     //$p->dump_fields();
 }
Beispiel #9
0
 function pay($code)
 {
     ini_set('display_errors', 'On');
     $this->load->library('paypal_class');
     $invoice = $this->commonmodel->getByPk($code, 'invoice_new', 'invoice_code');
     $applicant = $this->commonmodel->getByPk(arrIndex($invoice, 'applicant_id'), 'applicants', 'applicant_id');
     $p = new paypal_class();
     // initiate an instance of the class
     $p->paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
     // testing paypal url
     //$p->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';     // paypal url
     $this_script = createUrl('invoice/pay/' . $code);
     $ipn_url = 'http://landlord.webnseo.co.uk/paypal';
     if (empty($_GET['action'])) {
         $_GET['action'] = 'process';
     }
     switch ($_GET['action']) {
         case 'process':
             // Process and order...
             //                e($invoice);
             $paypal_id = getConfig('PAYPAL_MERCHENT_EMAIL');
             $p->add_field('business', '*****@*****.**');
             $p->add_field('return', $this_script . '?action=success');
             $p->add_field('cancel_return', $this_script . '?action=cancel');
             $p->add_field('notify_url', $ipn_url . '?action=ipn&invoice_id=' . $code);
             //$p->add_field('ipn_notification_url', $ipn_url);
             $p->add_field('item_name', 'Paypal Test Transaction');
             $p->add_field('amount', arrIndex($invoice, 'total_amount'));
             $p->add_field('currency_code', 'GBP');
             $p->add_field('custom', $code);
             $p->add_field('invoice_code', $code);
             $p->submit_paypal_post();
             // submit the fields to paypal
             //$p->dump_fields();      // for debugging, output a table of all the fields
             break;
         case 'success':
             // Order was successful...
             $page = array();
             $page['content'] = $this->load->view('thankyou', array(), true);
             $this->load->view($this->default, $page);
             //                foreach ($_POST as $key => $value) {
             //                    echo "$key: $value<br>";
             //                }
             break;
         case 'cancel':
             // Order was canceled...
             // The order was canceled before being completed.
             echo "<html><head><title>Canceled</title></head><body><h3>The order was canceled.</h3>";
             echo "</body></html>";
             break;
         case 'ipn':
             // Paypal is calling page for IPN validation...
             //error_log(json_encode($_REQUEST));
             if ($p->validate_ipn()) {
                 $in_code = $this->input->get('invoice_id', TRUE);
                 $this->db->insert('test', array('value' => json_encode($_REQUEST), 'status' => 1));
             } else {
                 // $this->db->insert('test', array('value' => json_encode($_REQUEST)));
             }
             break;
     }
 }
Beispiel #10
0
<?php

require_once "db_connect.php";
//require_once ("profile.common.php");
require_once 'include/localization.class.php';
require_once "include/astercrm.class.php";
require_once 'include/paypal.class.php';
// include the class file
$locate = new Localization('en', 'US', 'profile');
$p = new paypal_class();
// initiate an instance of the class
$p->paypal_url = $config['epayment']['paypal_payment_url'];
if ($p->validate_ipn($config['epayment']['ipn_log'])) {
    // Payment has been recieved and IPN is verified.  This is where you
    // update your database to activate or process the order, or setup
    // the database with the user's order details, email an administrator,
    // etc.  You can access a slew of information via the ipn_data() array.
    // Check the paypal documentation for specifics on what information
    // is available in the IPN POST variables.  Basically, all the POST vars
    // which paypal sends, which we send back for validation, are now stored
    // in the ipn_data() array.
    // For this example, we'll just email ourselves ALL the data.
    if ($p->ipn_data['custom'] != '') {
        $payer = explode(':', $p->ipn_data['custom']);
        $userid = $payer['0'];
        $uesrtype = $payer['1'];
        $resellerid = $payer['2'];
        $groupid = $payer['3'];
        if ($config['epayment']['ipn_log']) {
            $loghandle = fopen("upload/paypalipn-epayment.log", 'rb');
            $oricontent = fread($loghandle, filesize("upload/paypalipn-epayment.log"));
Beispiel #11
0
function jg_front_end_paypal($atts)
{
    if (session_id() == '' || !isset($_SESSION)) {
        // session isn't started
        session_start();
    }
    ob_start();
    global $current_user;
    global $wp_roles;
    global $wpdb;
    global $error;
    global $js_shortcode_on_front;
    extract(shortcode_atts(array('redirectPaid' => 0, 'display' => true, 'template' => ''), $atts));
    /*
       if ( trim($_SESSION['userEnc']) == '' ){
           $redirectLink = trim(home_url());
           if (intval($redirectLink) != 0)
               $redirectLink = get_permalink($redirectLink);
           else{
               if (!jg_check_missing_http($redirectLink)) $redirectLink = 'http://'. $redirectLink;
           }
           wp_redirect( $redirectLink ); exit;
       }
    */
    $wpjg_generalSettings = get_option('jg_general_settings');
    $result = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}jgusers WHERE `userEnc`='" . trim($_SESSION['userEnc']) . "';", ARRAY_A);
    if (isset($result['paidaccess']) && $wpjg_generalSettings['paidaccess'] == 1 && $result['paidaccess'] == 1) {
        $redirectLink = trim($redirectPaid);
        if (intval($redirectLink) != 0) {
            $redirectLink = get_permalink($redirectLink);
        } else {
            if (!jg_check_missing_http($redirectLink)) {
                $redirectLink = 'http://' . $redirectLink;
            }
        }
        wp_redirect($redirectLink);
        exit;
    }
    if (isset($_REQUEST["action"])) {
        require_once JG_PLUGIN_DIR . "/paypal/paypal_class.php";
        $p = new paypal_class();
        // paypal class
        $p->admin_mail = $wpjg_generalSettings['paypal_email'];
        // set notification email
        $action = $_REQUEST["action"];
        switch ($action) {
            case "process":
                // case process insert the form data in DB and process to the paypal
                $wpdb->update($wpdb->prefix . "jgusers", array('paytoken' => $_POST["invoice"]), array('userEnc' => trim($_SESSION['userEnc'])));
                $this_script = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
                $p->add_field('business', $wpjg_generalSettings['paypal_femail']);
                // Call the facilitator eaccount
                $p->add_field('cmd', $_POST["cmd"]);
                // cmd should be _cart for cart checkout
                $p->add_field('upload', '1');
                $p->add_field('return', $this_script . '?action=success');
                // return URL after the transaction got over
                $p->add_field('cancel_return', $this_script . '?action=cancel');
                // cancel URL if the trasaction was cancelled during half of the transaction
                $p->add_field('notify_url', $this_script . '?action=ipn');
                // Notify URL which received IPN (Instant Payment Notification)
                $p->add_field('currency_code', $_POST["currency_code"]);
                $p->add_field('invoice', $_POST["invoice"]);
                $p->add_field('item_name_1', $_POST["product_name"]);
                $p->add_field('item_number_1', $_POST["product_id"]);
                $p->add_field('quantity_1', $_POST["product_quantity"]);
                $p->add_field('amount_1', $wpjg_generalSettings['payamount']);
                $p->add_field('first_name', $_POST["payer_fname"]);
                $p->add_field('last_name', $_POST["payer_lname"]);
                $p->add_field('address1', $_POST["payer_address"]);
                $p->add_field('city', $_POST["payer_city"]);
                $p->add_field('state', $_POST["payer_state"]);
                $p->add_field('country', $_POST["payer_country"]);
                $p->add_field('zip', $_POST["payer_zip"]);
                $p->add_field('email', $_POST["payer_email"]);
                $p->submit_paypal_post();
                // POST it to paypal
                break;
            case "success":
                $redirectLink = trim($redirectPaid);
                if (intval($redirectLink) != 0) {
                    $redirectLink = get_permalink($redirectLink);
                } else {
                    if (!jg_check_missing_http($redirectLink)) {
                        $redirectLink = 'http://' . $redirectLink;
                    }
                }
                wp_redirect($redirectLink);
                exit;
                break;
            case "ipn":
                if ($p->validate_ipn()) {
                    $wpdb->update($wpdb->prefix . "jgusers", array('paidaccess' => 1, 'txn_id' => $_POST["txn_id"]), array('paytoken' => trim($_POST["invoice"])));
                }
                break;
        }
    }
    require_once JG_PLUGIN_DIR . '/lib/Smarty.class.php';
    $smarty = new Smarty();
    $smarty->template_dir = JG_PLUGIN_DIR . '/smarty/templates/';
    $smarty->compile_dir = JG_PLUGIN_DIR . '/smarty/templates_c/';
    $smarty->config_dir = JG_PLUGIN_DIR . '/smarty/configs/';
    $smarty->cache_dir = JG_PLUGIN_DIR . '/smarty/cache/';
    $smarty->assign('formurl', jg_curpageurl());
    $smarty->assign('Errors', $errors);
    $smarty->assign('Settings', $wpjg_generalSettings);
    $invoice = array('productid' => rand(1111, 99999), 'invoiceid' => date("His") . rand(1234, 9632));
    $smarty->assign('Get', $_GET);
    $smarty->assign('Post', $_POST);
    $smarty->assign('User', $_SESSION);
    $smarty->assign('Invoice', $invoice);
    if ($template != '') {
        $smarty->display($template);
    } else {
        $smarty->display('paypal.html');
    }
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}
Beispiel #12
0
 function pay($code)
 {
     //        echo '<pre>';
     //        print_r($_POST);
     //        exit;
     //        echo base_url() . 'classes/pay/' . $code . '?action=ipn';
     //            exit;
     ini_set('display_errors', 'On');
     $this->load->model('classesmodel');
     $event = $this->classesmodel->getOneEvent($code);
     $this->load->library('paypal_class');
     $desc = $this->input->post('desc', TRUE);
     $p = new paypal_class();
     // initiate an instance of the class
     //$p->paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';   // testing paypal url
     $p->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
     // paypal url
     $this_script = createUrl('classes/pay/' . $code);
     $ipn_url = 'http://www.sew2it.co.uk/classes/pay/' . $code;
     $qty = gParam('qty');
     if (empty($_GET['action'])) {
         $_GET['action'] = 'process';
     }
     switch ($_GET['action']) {
         case 'process':
             // Process and order...
             //                e($invoice);
             //                $paypal_id = getConfig('PAYPAL_MERCHENT_EMAIL');
             $paypal_id = getConfig('PAYPAL_ID');
             $p->add_field('business', $paypal_id);
             $p->add_field('return', $this_script . '?action=success');
             $p->add_field('cancel_return', $this_script . '?action=cancel');
             $p->add_field('notify_url', base_url() . 'classes/pay/' . $code . '?action=ipn&qty=' . $qty . '&user_id=' . curUsrId() . '&id=' . $code);
             //  $p->add_field('ipn_notification_url', $ipn_url);
             $p->add_field('amount', $event['price']);
             $p->add_field('item_name', $desc);
             $p->add_field('quantity', $qty);
             $p->add_field('currency_code', 'GBP');
             $p->add_field('custom', $code);
             $p->add_field('event_id', $event['id']);
             //                echo '<pre>';
             //                print_r($p);
             //                exit;
             $p->submit_paypal_post();
             // submit the fields to paypal
             //$p->dump_fields();      // for debugging, output a table of all the fields
             break;
         case 'success':
             // Order was successful...
             $shell = array();
             $shell['contents'] = $this->load->view('classes-index', array(), true);
             $this->load->view("themes/" . THEME . "/templates/subpage", $shell);
             //                foreach ($_POST as $key => $value) {
             //                    echo "$key: $value<br>";
             //                }
             break;
         case 'cancel':
             // Order was canceled...
             // The order was canceled before being completed.
             // echo "This is Cancelled";
             redirect(base_url() . "booking-cancelled");
             exit;
             //header("Location:http://wwww.sew2it.co.uk/booking-cancelled");
             //                echo "<html><head><title>Canceled</title></head><body><h3>The order was canceled.</h3>";
             //                echo "</body></html>";
             break;
         case 'ipn':
             // Paypal is calling page for IPN validation...
             //error_log(json_encode($_REQUEST),3,'mytest.log');
             if ($p->validate_ipn()) {
                 //                    mail('*****@*****.**', 'subject', 'this is message');
                 $in_code = $this->input->get('id', TRUE);
                 $user_id = $this->input->get('user_id', TRUE);
                 $qty = $this->input->get('qty', TRUE);
                 $this->db->insert('order', array('response' => json_encode($_REQUEST), 'status' => 'Active', 'event_id' => $in_code, 'user_id' => $user_id, 'qty' => $qty));
                 //   echo $this->db->last_query();
             } else {
                 // $this->db->insert('test', array('value' => json_encode($_REQUEST)));
             }
             break;
     }
 }
Beispiel #13
0
 function index()
 {
     $p = new paypal_class();
     // initiate an instance of the class
     $p->paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
     // testing paypal url
     //$p->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';     // paypal url
     // setup a variable for this script (ie: 'http://www.micahcarrick.com/paypal.php')
     //$this_script = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
     $this_script = "http://landlord.webnseo.co.uk/test/paypal.php";
     // if there is not action variable, set the default action of 'process'
     if (empty($_GET['action'])) {
         $_GET['action'] = 'process';
     }
     switch ($_GET['action']) {
         case 'process':
             // Process and order...
             // There should be no output at this point.  To process the POST data,
             // the submit_paypal_post() function will output all the HTML tags which
             // contains a FORM which is submited instantaneously using the BODY onload
             // attribute.  In other words, don't echo or printf anything when you're
             // going to be calling the submit_paypal_post() function.
             // This is where you would have your form validation  and all that jazz.
             // You would take your POST vars and load them into the class like below,
             // only using the POST values instead of constant string expressions.
             // For example, after ensureing all the POST variables from your custom
             // order form are valid, you might have:
             //
             // $p->add_field('first_name', $_POST['first_name']);
             // $p->add_field('last_name', $_POST['last_name']);
             $p->add_field('business', '*****@*****.**');
             //      $p->add_field('business', '*****@*****.**');
             $p->add_field('return', $this_script . '?action=success');
             $p->add_field('cancel_return', $this_script . '?action=cancel');
             $p->add_field('notify_url', $this_script . '?action=ipn');
             $p->add_field('item_name', 'Paypal Test Transaction');
             $p->add_field('amount', '1.99');
             $p->add_field('currency_code', 'USD');
             $p->submit_paypal_post();
             // submit the fields to paypal
             //$p->dump_fields();      // for debugging, output a table of all the fields
             break;
         case 'success':
             // Order was successful...
             // This is where you would probably want to thank the user for their order
             // or what have you.  The order information at this point is in POST
             // variables.  However, you don't want to "process" the order until you
             // get validation from the IPN.  That's where you would have the code to
             // email an admin, update the database with payment status, activate a
             // membership, etc.
             mail("*****@*****.**", "My subject", "<pre>" . $_REQUEST . '</pre>');
             // You could also simply re-direct them to another page, or your own
             // order status page which presents the user with the status of their
             // order based on a database (which can be modified with the IPN code
             // below).
             break;
         case 'cancel':
             // Order was canceled...
             // The order was canceled before being completed.
             echo "<html><head><title>Canceled</title></head><body><h3>The order was canceled.</h3>";
             echo "</body></html>";
             break;
         case 'ipn':
             // Paypal is calling page for IPN validation...
             // It's important to remember that paypal calling this script.  There
             // is no output here.  This is where you validate the IPN data and if it's
             // valid, update your database to signify that the user has payed.  If
             // you try and use an echo or printf function here it's not going to do you
             // a bit of good.  This is on the "backend".  That is why, by default, the
             // class logs all IPN data to a text file.
             if ($p->validate_ipn()) {
                 $in_code = $this->input->get('invoice_id', TRUE);
                 //          error_log('test-'.$in_code);
                 $this->db->where('invoice_code', $in_code);
                 $this->db->update('invoice_new', array('is_paid' => '1', 'response' => json_encode($_REQUEST)));
                 // Payment has been recieved and IPN is verified.  This is where you
                 // update your database to activate or process the order, or setup
                 // the database with the user's order details, email an administrator,
                 // etc.  You can access a slew of information via the ipn_data() array.
                 // Check the paypal documentation for specifics on what information
                 // is available in the IPN POST variables.  Basically, all the POST vars
                 // which paypal sends, which we send back for validation, are now stored
                 // in the ipn_data() array.
                 // For this example, we'll just email ourselves ALL the data.
                 //         $subject = 'Instant Payment Notification - Recieved Payment';
                 //         $to = 'YOUR EMAIL ADDRESS HERE';    //  your email
                 //         $body =  "An instant payment notification was successfully recieved\n";
                 //         $body .= "from ".$p->ipn_data['payer_email']." on ".date('m/d/Y');
                 //         $body .= " at ".date('g:i A')."\n\nDetails:\n";
                 //
                 //         foreach ($p->ipn_data as $key => $value) { $body .= "\n$key: $value"; }
                 // the message
                 //mail("*****@*****.**","My subject", $in_code);
             }
             break;
     }
 }
Beispiel #14
0
 public function paypal()
 {
     $p = new paypal_class();
     // initiate an instance of the class
     $p->paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
     // testing paypal url
     //$p->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';     // paypal url
     // setup a variable for this script (ie: 'http://www.micahcarrick.com/paypal.php')
     $this_script = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
     $string = $_SERVER['HTTP_HOST'];
     $toptal_pos = strpos($string, 'toptals');
     if ($toptal_pos > 0) {
         $first_dot = strpos($string, '.');
         $subdomain = substr($string, 0, $first_dot);
         $organization_query = mysql_query("SELECT * FROM `organization` WHERE `subdomain`='{$subdomain}'");
         $organization = mysql_fetch_array($organization_query);
         $organization_id = $organization['id'];
     }
     // if there is not action variable, set the default action of 'process'
     if (empty($_GET['action'])) {
         $_GET['action'] = 'process';
     }
     switch ($_GET['action']) {
         case 'process':
             // Process and order...
             // There should be no output at this point.  To process the POST data,
             // the submit_paypal_post() function will output all the HTML tags which
             // contains a FORM which is submited instantaneously using the BODY onload
             // attribute.  In other words, don't echo or printf anything when you're
             // going to be calling the submit_paypal_post() function.
             // This is where you would have your form validation  and all that jazz.
             // You would take your POST vars and load them into the class like below,
             // only using the POST values instead of constant string expressions.
             // For example, after ensureing all the POST variables from your custom
             // order form are valid, you might have:
             //
             // $p->add_field('first_name', $_POST['first_name']);
             // $p->add_field('last_name', $_POST['last_name']);
             echo "Please wait while we are redirecting you to the paypal website...";
             $CatDescription = $_REQUEST['CatDescription'];
             $payment = $_REQUEST['payment'];
             $id = $_REQUEST['id'];
             $key = $_REQUEST['key'];
             $p->add_field('business', '*****@*****.**');
             //put the paypal email id where you want to receive payment
             $p->add_field('return', $this_script . '?action=success&organization_id=' . $organization_id);
             $p->add_field('cancel_return', $this_script . '?action=cancel');
             $p->add_field('notify_url', $this_script . '?action=ipn');
             $p->add_field('item_name', $CatDescription);
             $p->add_field('amount', $payment);
             $p->add_field('key', $key);
             $p->add_field('item_number', $id);
             $p->submit_paypal_post();
             // submit the fields to paypal
             //$p->dump_fields();      // for debugging, output a table of all the fields
             break;
         case 'success':
             // Order was successful...
             // This is where you would probably want to thank the user for their order
             // or what have you.  The order information at this point is in POST
             // variables.  However, you don't want to "process" the order until you
             // get validation from the IPN.  That's where you would have the code to
             // email an admin, update the database with payment status, activate a
             // membership, etc.
             $payment_insert_data = array('organization_id' => $_GET['organization_id'], 'owner_email' => $_POST['payer_email'], 'fisrtname' => $_POST['first_name'], 'lastname' => $_POST['last_name'], 'amount' => $_POST['payment_gross'], 'time_stamp' => $_POST['payment_date'], 'correlation_id' => '', 'ack' => 'Success', 'version' => $_POST['notify_version'], 'build' => '', 'avs_code' => 'X', 'ccv_match' => 'M', 'transacton_id' => $_POST['txn_id'], 'date_added' => date('Y-m-d h:i:s'));
             $this->db->insert("credit_card_payment", $payment_insert_data);
             $this->checkout_model->after_payment_insert($_GET['organization_id'], $_POST['payment_gross'], '', 'paypal');
             $this->checkout_model->after_payment_session_insert($_GET['organization_id'], $_POST['payment_gross'], '');
             header('location:http://' . $_SERVER['HTTP_HOST'] . '/index.php/checkout/successForm/' . $_POST['txn_id'] . '/' . $_POST['payment_status']);
             //foreach ($_POST as $key => $value) { $data[$key] .= $value; }
             // You could also simply re-direct them to another page, or your own
             // order status page which presents the user with the status of their
             // order based on a database (which can be modified with the IPN code
             // below).
             break;
         case 'cancel':
             // Order was canceled...
             // The order was canceled before being completed.
             echo "<br/><p><b>The order was canceled!</b></p><br /> Please return to the <a href=\"http://" . $_SERVER['HTTP_HOST'] . "/plan\">plan's page</a>";
             foreach ($_POST as $key => $value) {
                 echo "{$key}: {$value}<br>";
             }
             break;
         case 'ipn':
             // Paypal is calling page for IPN validation...
             // It's important to remember that paypal calling this script.  There
             // is no output here.  This is where you validate the IPN data and if it's
             // valid, update your database to signify that the user has payed.  If
             // you try and use an echo or printf function here it's not going to do you
             // a bit of good.  This is on the "backend".  That is why, by default, the
             // class logs all IPN data to a text file.
             if ($p->validate_ipn()) {
                 // Payment has been recieved and IPN is verified.  This is where you
                 // update your database to activate or process the order, or setup
                 // the database with the user's order details, email an administrator,
                 // etc.  You can access a slew of information via the ipn_data() array.
                 // Check the paypal documentation for specifics on what information
                 // is available in the IPN POST variables.  Basically, all the POST vars
                 // which paypal sends, which we send back for validation, are now stored
                 // in the ipn_data() array.
                 // For this example, we'll just email ourselves ALL the data.
                 $dated = date("D, d M Y H:i:s", time());
                 $subject = 'Instant Payment Notification - Recieved Payment';
                 $to = '*****@*****.**';
                 //  your email
                 $body = "An instant payment notification was successfully recieved\n";
                 $body .= "from " . $p->ipn_data['payer_email'] . " on " . date('m/d/Y');
                 $body .= " at " . date('g:i A') . "\n\nDetails:\n";
                 $headers = "";
                 $headers .= "From: Test Paypal \r\n";
                 $headers .= "Date: {$dated} \r\n";
                 $PaymentStatus = $p->ipn_data['payment_status'];
                 $Email = $p->ipn_data['payer_email'];
                 $id = $p->ipn_data['item_number'];
                 if ($PaymentStatus == 'Completed' or $PaymentStatus == 'Pending') {
                     $PaymentStatus = '2';
                 } else {
                     $PaymentStatus = '1';
                 }
                 /*                                                                           
                  *
                  * 
                  *
                  *      Here you write your quries to make payment received or pending etc. 
                  * 
                  *  
                  * 
                  */
                 foreach ($p->ipn_data as $key => $value) {
                     $body .= "\n{$key}: {$value}";
                 }
                 //fopen("http://www.virtualphoneline.com/admins/TestHMS.php?to=".urlencode($to)."&subject=".urlencode($subject)."&message=".urlencode($body)."&headers=".urlencode($headers)."","r");
             }
             break;
     }
 }
<body>
<div align="center">
<?php 
switch ($_GET['action']) {
    case 'success':
        // Order was successful...
        echo "<div id='form-content'><div class='success'>Thank you for your payment, we will contact you shortly!</div></div>";
        break;
    case 'cancel':
        // Order was canceled...
        echo "<div id='form-content'><div class='cancelled'>The payment was canceled!</div><a href='" . $script_base . "'>Click here</a> to return to terminal</div>";
        break;
    case 'ipn':
        // Paypal is calling page for IPN validation...
        if ($paypal->validate_ipn()) {
            //-----> send notification
            //creating message for sending
            $headers = "MIME-Version: 1.0\n";
            $headers .= "Content-type: text/html; charset=utf-8\n";
            $headers .= "From: '" . $title . "' <" . $store_email . "> \n";
            $subject = "New Payment Received";
            $message = "New payment was successfully recieved through paypal payment terminal \n";
            $message .= "from " . $paypal->pp_data['payer_email'] . " on " . date('m/d/Y');
            $message .= " at " . date('g:i A');
            mail($admin_email, $subject, $message, $headers);
            //-----> send notification end
        }
        break;
}
?>
Beispiel #16
0
            unset($_SESSION['shoopin_cart']);
            ?>
			 <div style="display:none;">
			<script language="javascript" type="text/javascript">
				window.location='<?php 
            _e($paypal);
            ?>
';
			</script>
			</div>
		<?php 
        }
        break;
    case 'ipn':
        // Paypal is calling page for IPN validation...
        $p->validate_ipn();
        if (isset($p->ipn_data["txn_id"]) && isset($p->ipn_data["custom"]) && trim(strtolower($_REQUEST['payment_status'])) == 'completed') {
            $txn_id = $p->ipn_data['txn_id'];
            $order_id = $p->ipn_data['custom'];
            require_once '../../../../wp-config.php';
            global $wpdb;
            $prefix = $wpdb->base_prefix;
            if ($order_id > 0) {
                $sql = "UPDATE `" . $prefix . "order_item` set order_status='C' where order_id='{$order_id}'";
                $result = $wpdb->query($sql);
                $sql = "UPDATE `" . $prefix . "orders` set txn_id='{$txn_id}', order_status='C' where order_id='{$order_id}'";
                $result = $wpdb->query($sql);
                if ($result == 1) {
                    $html = '';
                    $symbal = $currency_symbal;
                    $html .= '<style>
Beispiel #17
0
<?php

include "../../_setup.php";
include "classes/donate-paypalclass.php";
include "classes/donation.php";
include "classes/campaign.php";
$donationPlugin = new btPlugin($mysqli);
if ($donationPlugin->selectByName("Donations")) {
    $donationObj = new Donation($mysqli);
    $p = new paypal_class();
    $arrColumns = array("donationcampaign_id", "member_id", "name", "message", "datesent", "amount", "paypalemail", "transaction_id", "response");
    $p->setMode($donationPlugin->getConfigInfo("mode"));
    if ($p->validate_ipn() && $p->ipn_data['payment_status'] == "Completed") {
        $member = new Member($mysqli);
        $campaignObj = new DonationCampaign($mysqli);
        $arrData = $p->ipn_data;
        $data = json_encode($arrData);
        $customVars = json_decode($arrData['custom'], true);
        if ($campaignObj->select($customVars['campaign_id']) && $member->select($customVars['member_id'])) {
            $campaignName = $campaignObj->get_info_filtered("title");
            $medalID = $campaignObj->get_info("awardmedal");
            $member->awardMedal($medalID, "Donated to " . $campaignName . " campaign");
        }
        $arrValues = array($customVars['campaign_id'], $customVars['member_id'], $customVars['name'], $customVars['message'], time(), $arrData['mc_gross'], $arrData['payer_email'], $arrData['txn_id'], $data);
        $donationObj->addNew($arrColumns, $arrValues);
    } else {
        $data = json_encode($p->ipn_data);
        $data = "ERROR: - " . $p->last_error . " - " . $data;
        $donationObj->logError($data);
    }
}
Beispiel #18
0
function tw_paypal_express_checkout($action = 'process', $product = null, $price = null, $quantity = 1, $additional_fields = array(), $query_args = array())
{
    require_once HM_CORE_PATH . 'paypal/paypal.class.php';
    // include the class file
    $p = new paypal_class();
    // initiate an instance of the class
    $p->paypal_url = get_option('paypal_url');
    //$p->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';     // paypal url
    // setup a variable for this script (ie: 'http://www.micahcarrick.com/paypal.php')
    if (defined('PAYPAL_ORDER_URL')) {
        $paypal_action_url = PAYPAL_ORDER_URL;
    } else {
        $paypal_action_url = HM_CORE_PATH . 'paypal/process.order.php';
    }
    if ($query_args) {
        $paypal_action_url = add_query_arg($query_args, $paypal_action_url);
    }
    if (!is_string($action)) {
        $action = 'process';
    }
    switch ($action) {
        case 'process':
            // Process and order...
            // There should be no output at this point.  To process the POST data,
            // the submit_paypal_post() function will output all the HTML tags which
            // contains a FORM which is submited instantaneously using the BODY onload
            // attribute.  In other words, don't echo or printf anything when you're
            // going to be calling the submit_paypal_post() function.
            // This is where you would have your form validation  and all that jazz.
            // You would take your POST vars and load them into the class like below,
            // only using the POST values instead of constant string expressions.
            // For example, after ensureing all the POST variables from your custom
            // order form are valid, you might have:
            //
            // $p->add_field('first_name', $_POST['first_name']);
            // $p->add_field('last_name', $_POST['last_name']);
            $p->add_field('business', get_option('paypal_business_email'));
            $p->add_field('return', add_query_arg('action', 'success', $paypal_action_url));
            $p->add_field('cancel_return', add_query_arg('action', 'cancel', $paypal_action_url));
            $p->add_field('notify_url', add_query_arg('action', 'ipn', $paypal_action_url));
            $p->add_field('item_name', $product);
            $p->add_field('amount', $price);
            $p->add_field('quantity', $quantity);
            $p->add_field('currency_code', 'GBP');
            foreach ($additional_fields as $key => $value) {
                $p->add_field($key, $value);
            }
            $p->submit_paypal_post();
            // submit the fields to paypal
            //$p->dump_fields();      // for debugging, output a table of all the fields
            break;
        case 'success':
            // Order was successful...
            // This is where you would probably want to thank the user for their order
            // or what have you.  The order information at this point is in POST
            // variables.  However, you don't want to "process" the order until you
            // get validation from the IPN.  That's where you would have the code to
            // email an admin, update the database with payment status, activate a
            // membership, etc.
            return do_action('hm_payment_completed', 'unverified');
            // You could also simply re-direct them to another page, or your own
            // order status page which presents the user with the status of their
            // order based on a database (which can be modified with the IPN code
            // below).
            break;
        case 'cancel':
            // Order was canceled...
            // The order was canceled before being completed.
            return do_action('hm_payment_canceled', 'canceled');
            break;
        case 'ipn':
            // Paypal is calling page for IPN validation...
            // It's important to remember that paypal calling this script.  There
            // is no output here.  This is where you validate the IPN data and if it's
            // valid, update your database to signify that the user has payed.  If
            // you try and use an echo or printf function here it's not going to do you
            // a bit of good.  This is on the "backend".  That is why, by default, the
            // class logs all IPN data to a text file.
            if ($p->validate_ipn()) {
                // Payment has been recieved and IPN is verified.  This is where you
                // update your database to activate or process the order, or setup
                // the database with the user's order details, email an administrator,
                // etc.  You can access a slew of information via the ipn_data() array.
                // Check the paypal documentation for specifics on what information
                // is available in the IPN POST variables.  Basically, all the POST vars
                // which paypal sends, which we send back for validation, are now stored
                // in the ipn_data() array.
                // Does nothing by default, hook in to the filter to run functions.
                do_action('hm_paypal_ipn_verified', $p->ipn_data);
            } else {
                // Payment failed for some reason.
                // Again we don't do anything by default apart from run a filter onto
                // which you can hook your functions.
                do_action('hm_paypal_ipn_failed', $p->ipn_data);
            }
            break;
    }
}
 function index()
 {
     $token = @$_REQUEST['token'];
     $paymentMode = $this->config->item('PayPalMode');
     $p = new paypal_class();
     // paypal class
     $p->admin_mail = $this->config->item('PayerEmailId');
     // set notification email
     $p->currency = $this->config->item('currency');
     // set notification email
     $action = @$_REQUEST["action"];
     //$invoice = date("His").rand(1234, 9632);
     $_REQUEST['cmd'] = '_cart';
     //$cart = json_decode(@$_REQUEST['cart'],true);
     if (isset($action)) {
         switch ($action) {
             case "process":
                 // case process insert the form data in DB and process to the paypal
                 //if(count($cart)>0){
                 //$_REQUEST['invoice'] = $invoice;
                 $curl = curl_init();
                 // Set some options - we are passing in a useragent too here
                 curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => base_url() . 'api/subscription/order/token/' . $token, CURLOPT_USERAGENT => 'Checkout', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $_REQUEST));
                 // Send the request & save response to $resp
                 $resp = curl_exec($curl);
                 // Close request to clear up some resources
                 curl_close($curl);
                 $result = json_decode($resp, true);
                 if ($result['output'] == 1) {
                     $i = 0;
                     //-- get result array--//
                     $cart = json_decode($result['result']['cart'], true);
                     $user_id = $result['result']['user_id'];
                     $cart = array($cart);
                     //-- post form to paypal --//
                     foreach ($cart as $row) {
                         $i++;
                         //-- fields for paypal --//
                         $p->add_field('item_name_' . $i, $row['subscription_name']);
                         $p->add_field('item_number_' . $i, $row['subscription_id']);
                         $p->add_field('amount_' . $i, $row['amount']);
                         //$p->add_field('discount_amount_'.$i,  $_POST["discount_amount_".$i]);
                     }
                     $p->add_field('business', $this->config->item('merchantEmailId'));
                     // Call the facilitator eaccount
                     $p->add_field('cmd', $_REQUEST["cmd"]);
                     // cmd should be _cart for cart checkout
                     $p->add_field('upload', '1');
                     $p->add_field('return', $this->config->item('PayPalReturnURL'));
                     // return URL after the transaction got over
                     $p->add_field('cancel_return', $this->config->item('PayPalCancelURL') . '&invoiceno=' . $_REQUEST["o"]);
                     // cancel URL if the trasaction was cancelled during half of the transaction
                     //$p->add_field('cancel_return', $this->config->item('PayPalCancelURL')); // cancel URL if the trasaction was cancelled during half of the transaction
                     $p->add_field('notify_url', $this->config->item('PayPalIpnURL'));
                     // Notify URL which received IPN (Instant Payment Notification)
                     $p->add_field('currency_code', $this->config->item('PayPalCurrencyCode'));
                     $p->add_field('invoice', $_REQUEST["o"]);
                     //$p->dump_fields();die;
                     $p->submit_paypal_post();
                     // POST it to paypal
                 } else {
                     //echo $result['error'];
                     //echo json_encode(array('code'=>0,'result'=>$result['error']));
                     redirect(base_url() . 'checkout/callback?result=error');
                 }
                 //}
                 //$this->paypal_model->saveData($_POST);
                 //$p->dump_fields(); // Show the posted values for a reference, comment this line before app goes live
                 break;
             case "success":
                 // success case to show the user payment got success
                 //echo json_encode(array('code'=>1)); // 200 being the HTTP response code
                 //echo "<h1>Payment Transaction Done Successfully</h1>";
                 redirect(base_url() . 'checkout/callback?result=success');
                 break;
             case "cancel":
                 // case cancel to show user the transaction was cancelled
                 //echo 'in cancel block';echo "<br/>";
                 //echo '<pre>';print_r($_POST);echo '</pre>';exit;
                 //$invoice_no = $_REQUEST['invoiceno'];
                 //-- post cancel order---//
                 $curl = curl_init();
                 curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => base_url() . 'api/subscription/cancel', CURLOPT_USERAGENT => 'Cancel', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $_REQUEST));
                 //-----------------------//
                 // Send the request & save response to $resp
                 $resp = curl_exec($curl);
                 // Close request to clear up some resources
                 curl_close($curl);
                 $result = json_decode($resp, true);
                 if ($result['output'] == 1) {
                     redirect(base_url() . 'checkout/callback?result=cancel');
                     //  echo json_encode(array('code'=>0,'result'=>'Transaction Cancelled'));
                     //echo "<h2>Transaction Cancelled</h2>";
                 } else {
                     //echo json_encode(array('code'=>0,'result'=>$result['error']));
                     // echo $result['error'];
                     redirect(base_url() . 'checkout/callback?result=cancel');
                 }
                 break;
             case "ipn":
                 // IPN case to receive payment information. this case will not displayed in browser. This is server to server communication. PayPal will send the transactions each and every details to this case in secured POST menthod by server to server.
                 //$trasaction_id  = $_REQUEST["txn_id"];
                 //$payment_status = strtolower($_REQUEST["payment_status"]);
                 // $invoice		= $_REQUEST["invoice"];
                 if ($p->validate_ipn()) {
                     // validate the IPN, do the others stuffs here as per your app logic
                     //-- post paypal ipn ---//
                     $curl = curl_init();
                     curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => base_url() . 'api/subscription/ipn', CURLOPT_USERAGENT => 'Completed', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $_REQUEST));
                     //-----------------------//
                     // Send the request & save response to $resp
                     $resp = curl_exec($curl);
                     // Close request to clear up some resources
                     curl_close($curl);
                     $subject = 'Instant Payment Notification - Recieved Payment';
                     $this->log('paypal_log', $resp . ': ' . $subject);
                     $p->send_report($subject);
                     // Send the notification about the transaction
                 } else {
                     $subject = 'Instant Payment Notification - Payment Fail';
                     $this->log('paypal_log', $resp . ': ' . $subject);
                     $p->send_report($subject);
                     // failed notification
                 }
                 break;
         }
         //$this->load->view('paypal');
     } else {
         //$this->load->view('paypal');
     }
 }