/**
  * Checks if this is a fastcheckout notification
  */
 public function isFCONotification($transId)
 {
     $storeId = Mage::app()->getStore()->getStoreId();
     $config = Mage::getStoreConfig('mspcheckout/settings', $storeId);
     $msp = new MultiSafepay();
     $msp->test = $config["test_api"] == 'test';
     $msp->merchant['account_id'] = $config["account_id"];
     $msp->merchant['site_id'] = $config["site_id"];
     $msp->merchant['site_code'] = $config["secure_code"];
     $msp->transaction['id'] = $transId;
     if ($msp->getStatus() == false) {
         //Mage::log("Error while getting status.", null, "multisafepay.log");
     } else {
         //Mage::log("Got status: ".$msp->details['ewallet']['fastcheckout'], null, "multisafepay.log");
         return $msp->details['ewallet']['fastcheckout'] == "YES";
     }
 }
 /**
  * Status notification
  */
 public function notificationAction($return = false)
 {
     $orderId = $this->getRequest()->getQuery('transactionid');
     $initial = $this->getRequest()->getQuery('type') == 'initial' ? true : false;
     $transactionid = $this->getRequest()->getQuery('transactionid');
     // Check if this is a fastcheckout notification and redirect
     //check if FCO transaction
     $storeId = Mage::app()->getStore()->getStoreId();
     $config = Mage::getStoreConfig('mspcheckout' . "/settings", $storeId);
     if (isset($config["account_id"])) {
         $msp = new MultiSafepay();
         $msp->test = $config["test_api"] == 'test';
         $msp->merchant['account_id'] = $config["account_id"];
         $msp->merchant['site_id'] = $config["site_id"];
         $msp->merchant['site_code'] = $config["secure_code"];
         $msp->transaction['id'] = $transactionid;
         if ($msp->getStatus() == false) {
             //Mage::log("Error while getting status.", null, "multisafepay.log");
         } else {
             if ($msp->details['ewallet']['fastcheckout'] == "YES") {
                 $transactionid = $this->getRequest()->getQuery('transactionid');
                 $initial = $this->getRequest()->getQuery('type') == 'initial' ? true : false;
                 $checkout = Mage::getModel("msp/checkout");
                 $done = $checkout->notification($transactionid, $initial);
                 if ($initial) {
                     $returnUrl = Mage::getUrl("msp/checkout/return", array("_secure" => true)) . '?transactionid=' . $transactionid;
                     $storeId = Mage::getModel('sales/quote')->load($transactionid)->getStoreId();
                     $storeName = Mage::app()->getGroup($storeId)->getName();
                     // display return message
                     echo 'Return to <a href="' . $returnUrl . '?transactionid=' . $orderId . '">' . $storeName . '</a>';
                 } else {
                     if ($done) {
                         echo 'ok';
                     } else {
                         echo 'ng';
                     }
                 }
                 exit;
             }
         }
     }
     $paymentModel = Mage::getSingleton("msp/" . $this->getGatewayModel());
     $done = $paymentModel->notification($orderId, $initial);
     if (!$return) {
         if ($initial) {
             $returnUrl = $paymentModel->getReturnUrl();
             $order = Mage::getSingleton('sales/order')->loadByIncrementId($orderId);
             $storename = $order->getStoreGroupName();
             // display return message
             $this->getResponse()->setBody('Return to <a href="' . $returnUrl . '?transactionid=' . $orderId . '">' . $storename . '</a>');
         } else {
             if ($done) {
                 $this->getResponse()->setBody('ok');
             } else {
                 $this->getResponse()->setBody('ng');
             }
         }
     } else {
         return true;
     }
 }
 function handle_multisafepay_ipn()
 {
     ob_end_clean();
     ini_set('display_errors', false);
     include 'MultiSafepay.combined.php';
     $msp = new MultiSafepay();
     // transaction id (same as the transaction->id given in the transaction request)
     $transactionid = isset($_GET['transactionid']) ? $_GET['transactionid'] : false;
     if (!$transactionid) {
         send_error('No MultiSafepay transaction ID');
     }
     $multisafepay_bits = explode("|", $transactionid);
     $user_id = $multisafepay_bits[0];
     $payment_id = (int) $multisafepay_bits[1];
     $invoice_id = (int) $multisafepay_bits[2];
     //send_error('bad?');
     //send_error($payment_id.' multisafepay IPN check started',var_export($_REQUEST,true));
     if ($payment_id && $invoice_id) {
         $hash = $this->multisafepay_custom($user_id, $payment_id, $invoice_id);
         if ($hash != $transactionid) {
             send_error("Multisafepay IPN Error (incorrect hash)");
             exit;
         }
         $user_id = (int) $user_id;
         // sometimes userid is ''
         $paymetn_history = get_single('invoice_payment', 'invoice_payment_id', $payment_id);
         if (!$paymetn_history) {
             send_error("Unknown Multisafe Payment - maybe a history was deleted?");
             exit;
         }
         // (notify.php?type=initial is used as notification_url and should output a link)
         $initial = isset($_GET['type']) && $_GET['type'] == "initial";
         /*
          * Merchant Settings
          */
         //        $msp->test                         = MSP_TEST_API;
         //        $msp->merchant['account_id']       = MSP_ACCOUNT_ID;
         //        $msp->merchant['site_id']          = MSP_SITE_ID;
         //        $msp->merchant['site_code']        = MSP_SITE_CODE;
         $msp->test = self::is_sandbox();
         $msp->merchant['account_id'] = module_config::c('payment_method_multisafepay_account', '');
         $msp->merchant['site_id'] = module_config::c('payment_method_multisafepay_site_id', '');
         $msp->merchant['site_code'] = module_config::c('payment_method_multisafepay_side_code', '');
         /*
          * Transaction Details
          */
         $msp->transaction['id'] = $transactionid;
         // returns the status
         $status = $msp->getStatus();
         if ($msp->error && !$initial) {
             // only show error if we dont need to display the link
             echo "Error " . $msp->error_code . ": " . $msp->error;
             exit;
         }
         //send_error($payment_id.' MultiSafepay Status of '.$status,var_export($_REQUEST,true));
         $payment_history_data = isset($paymetn_history['data']) && strlen($paymetn_history['data']) ? unserialize($paymetn_history['data']) : array();
         if (!is_array($payment_history_data)) {
             $payment_history_data = array();
         }
         if (!isset($payment_history_data['log'])) {
             $payment_history_data['log'] = array();
         }
         $payment_history_data['log'][] = 'Payment ' . $status . ' at ' . print_date(time(), true);
         update_insert("invoice_payment_id", $payment_id, "invoice_payment", array('data' => serialize($payment_history_data)));
         switch ($status) {
             case "initialized":
                 // waiting
                 break;
             case "completed":
                 // payment complete
                 update_insert("invoice_payment_id", $payment_id, "invoice_payment", array('date_paid' => date('Y-m-d'), 'method' => 'MultiSafepay'));
                 module_invoice::save_invoice($invoice_id, array());
                 break;
             case "uncleared":
                 // waiting (credit cards or direct debit)
                 break;
             case "void":
                 // canceled
                 break;
             case "declined":
                 // declined
                 break;
             case "refunded":
                 // refunded
                 send_error("Multisafepay Error! The payment {$payment_id} has been refunded or reversed! BAD BAD! You have to follup up customer for money manually now.");
                 break;
             case "expired":
                 // expired
                 break;
             default:
         }
         if ($initial) {
             // displayed at the last page of the transaction proces (if no redirect_url is set)
             echo '<a href="' . module_invoice::link_public($invoice_id) . '">Return to Invoice</a>';
         } else {
             // link to notify.php for MultiSafepay back-end (for delayed payment notifications)
             // backend expects an "ok" if no error occurred
             echo "ok";
         }
     } else {
         send_error('No bits in transaction id');
     }
     exit;
     $multisafepay_bits = explode("|", $_REQUEST['custom']);
     $user_id = (int) $multisafepay_bits[0];
     $payment_id = (int) $multisafepay_bits[1];
     $invoice_id = (int) $multisafepay_bits[2];
     //send_error('bad?');
     if ($user_id && $payment_id && $invoice_id) {
         $hash = $this->multisafepay_custom($user_id, $payment_id, $invoice_id);
         if ($hash != $_REQUEST['custom']) {
             send_error("Multisafepay IPN Error (incorrect hash)");
             exit;
         }
         $sql = "SELECT * FROM `" . _DB_PREFIX . "user` WHERE user_id = '{$user_id}' LIMIT 1";
         $res = qa($sql);
         if ($res) {
             $user = array_shift($res);
             if ($user && $user['user_id'] == $user_id) {
                 // check for payment exists
                 $payment = module_invoice::get_invoice_payment($payment_id);
                 $invoice = module_invoice::get_invoice($invoice_id);
                 if ($payment && $invoice) {
                     $invoice_currency = module_config::get_currency($invoice['currency_id']);
                     $invoice_currency_code = $invoice_currency['code'];
                     // check correct business
                     if (!$_REQUEST['business'] && $_REQUEST['receiver_email']) {
                         $_REQUEST['business'] = $_REQUEST['receiver_email'];
                     }
                     if ($_REQUEST['business'] != module_config::c('payment_method_multisafepay_email', _ERROR_EMAIL)) {
                         send_error('Multisafepay error! Paid the wrong business name. ' . $_REQUEST['business'] . ' instead of ' . module_config::c('payment_method_multisafepay_email', _ERROR_EMAIL));
                         exit;
                     }
                     // check correct currency
                     if ($invoice_currency_code && $_REQUEST['mc_currency'] != $invoice_currency_code) {
                         send_error('Multisafepay error! Paid the wrong currency code. ' . $_REQUEST['mc_currency'] . ' instead of ' . $invoice_currency_code);
                         exit;
                     }
                     if ($_REQUEST['payment_status'] == "Canceled_Reversal" || $_REQUEST['payment_status'] == "Refunded") {
                         // funky refund!! oh noes!!
                         // TODO: store this in the database as a negative payment... should be easy.
                         // populate $_REQUEST vars then do something like $payment_history_id = update_insert("payment_history_id","new","payment_history");
                         send_error("Multisafepay Error! The payment {$payment_id} has been refunded or reversed! BAD BAD! You have to follup up customer for money manually now.");
                     } else {
                         if ($_REQUEST['payment_status'] == "Completed") {
                             // payment is completed! yeye getting closer...
                             switch ($_REQUEST['txn_type']) {
                                 case "web_accept":
                                     // running in multisafepay sandbox or not?
                                     //$sandbox = (self::is_sandbox())?"sandbox.":'';
                                     // quick check we're not getting a fake payment request.
                                     $url = 'https://www.' . (self::is_sandbox() ? 'sandbox.' : '') . 'multisafepay.com/cgi-bin/webscr';
                                     $result = self::fsockPost($url, $_POST);
                                     //send_error('multisafepay sock post: '.$url."\n\n".var_export($result,true));
                                     if (eregi("VERIFIED", $result)) {
                                         // finally have everything.
                                         // mark the payment as completed.
                                         update_insert("invoice_payment_id", $payment_id, "invoice_payment", array('date_paid' => date('Y-m-d'), 'amount' => $_REQUEST['mc_gross'], 'method' => 'Multisafepay (IPN)'));
                                         module_invoice::save_invoice($invoice_id, array());
                                         echo "Successful Payment!";
                                     } else {
                                         send_error("Multisafepay IPN Error (multisafepay rejected the payment!) " . var_export($result, true));
                                     }
                                     break;
                                 case "subscr_signup":
                                 default:
                                     // TODO: support different payment methods later? like a monthly hosting fee..
                                     send_error("Multisafepay IPN Error (we dont currently support this payment method: " . $_REQUEST['txn_type'] . ")");
                                     break;
                             }
                         } else {
                             send_error("Multisafepay info: This payment is not yet completed, this usually means it's an e-cheque, follow it up in a few days if you dont hear anything. This also means you may have to login to multisafepay and 'Accept' the payment. So check there first.");
                         }
                     }
                 } else {
                     send_error("Multisafepay IPN Error (no payment found in database!)");
                 }
             } else {
                 send_error("Multisafepay IPN Error (error with user that was found in database..)");
             }
         } else {
             send_error("Multisafepay IPN Error (no user found in database #1)");
         }
     } else {
         send_error("Multisafepay IPN Error (no user id found)");
     }
     exit;
 }