function chkPayment()
 {
     $db =& JFactory::getDBO();
     $vm_pid = $_POST["virtuemart_paymentmethod_id"];
     $amount = floatval($_POST["pm_amount"]) * 100;
     $q = "SELECT payment_params FROM #__virtuemart_paymentmethods WHERE virtuemart_paymentmethod_id = " . $vm_pid;
     $db->setQuery($q);
     $vm_params = $db->loadResult();
     //GET PRIVATE KEY
     $key = explode("|", $vm_params);
     $pat = '/\\"([^\\"]*?)\\"/';
     preg_match($pat, $key[11], $matches);
     $private_key = $matches[1];
     //define vars
     define('API_HOST', 'https://api.paymill.com/v2/');
     define('API_KEY', $private_key);
     set_include_path(implode(PATH_SEPARATOR, array(realpath(realpath(dirname(__FILE__)) . '/lib'), get_include_path())));
     $token = $_POST['paymillToken'];
     if ($token) {
         require "components/com_paymillapi/lib/Services/Paymill/Transactions.php";
         $transactionsObject = new Services_Paymill_Transactions(API_KEY, API_HOST);
         $params = array('amount' => $amount, 'currency' => 'eur', 'token' => $token, 'description' => $_POST['pm_email']);
         $transaction = $transactionsObject->create($params);
         $email = $transaction['description'];
         $status = $transaction['status'];
         $q = "INSERT INTO #__paymill (token, status, email, created) VALUES ('" . $token . "', '" . $status . "', '" . $email . "', NOW())";
         $db->setQuery($q);
         $db->query();
         return var_dump($transaction, true);
     }
 }
function validateNotification($notification)
{
    $result = false;
    if (isNotificationFormatValid($notification) && $notification['event_type'] === 'refund.succeeded') {
        $transaction_object = new Services_Paymill_Transactions(Configuration::get('PIGMBH_PAYMILL_PRIVATEKEY'), 'https://api.paymill.com/v2/');
        $id = $notification['event_resource']['transaction']['id'];
        $transaction_result = $transaction_object->getOne($id);
        $result = isset($transaction_result['id']) && $transaction_result['id'] === $id;
    }
    return $result;
}
 /**
  * Tests Services_Paymill_Refunds->create()
  */
 public function testRefundWithLessAmount()
 {
     $transactionParams = array('amount' => 4200, 'currency' => 'eur', 'description' => 'Deuterium Cartridge', 'token' => $this->getToken());
     $transaction = $this->_transactions->create($transactionParams);
     $params = array('transactionId' => $transaction['id'], 'params' => array('amount' => 3200));
     $refund = $this->_refunds->create($params);
     $this->assertEquals($refund['data']['transaction']['id'], $transaction['id']);
     $this->assertEquals($refund['data']['transaction']['amount'], 1000);
     $this->assertEquals($refund['data']['transaction']['status'], 'partial_refunded');
     $transactionId = $transaction['id'];
     return $transactionId;
 }
 /**
  * Tests Services_Paymill_Transactions->create()
  * @depends testCreate
  */
 public function testCreateTransaction($preauthorizationId)
 {
     $params = array('amount' => 30, 'currency' => 'gbp', 'description' => 'Lancashire Cheese', 'preauthorization' => $preauthorizationId);
     $transaction = $this->_transaction->create($params);
     $this->assertInternalType('array', $transaction);
     $this->assertArrayHasKey('id', $transaction);
     $this->assertNotEmpty($transaction['id']);
     $this->assertEquals($transaction['amount'], 30);
     $this->assertEquals($transaction['description'], 'Lancashire Cheese');
     $transactionId = $transaction['id'];
     return $transactionId;
 }
 /**
  * Validates the requested refund
  * 
  * @param array $notification
  * @return boolean
  */
 private function isNotificationValid($notification)
 {
     if ($this->isStructureValid($notification) && $notification['event']['event_type'] == 'refund.succeeded') {
         $id = $notification['event']['event_resource']['transaction']['id'];
         $privateKey = trim($this->config->get('privateKey'));
         $transactionObject = new Services_Paymill_Transactions($privateKey, 'https://api.paymill.com/v2/');
         $result = $transactionObject->getOne($id);
         $this->logging->log('validate transaction-id for refund', var_export($result['id'] === $id, true));
         return $result['id'] === $id;
     }
     return false;
 }
 private function _validateRequest($data)
 {
     $valid = false;
     if (!is_null($data) && isset($data->event) && isset($data->event->event_resource) && isset($data->event->event_resource->transaction)) {
         $transactionObject = new Services_Paymill_Transactions(trim($this->_getPaymentConfig('PRIVATE_API_KEY')), Util::$apiUrl);
         $transaction = $transactionObject->getOne($data->event->event_resource->transaction->id);
         // Validate data
         if (isset($transaction['id']) && $transaction['id'] === $data->event->event_resource->transaction->id) {
             $valid = true;
         }
     }
     return $valid;
 }
Example #7
0
 private function validateRequest($data)
 {
     $valid = false;
     // check structure
     if (!is_null($data) && isset($data->event) && isset($data->event->event_resource) && isset($data->event->event_resource->transaction)) {
         $transactionObject = new Services_Paymill_Transactions(trim(oxRegistry::getConfig()->getShopConfVar('PAYMILL_PRIVATEKEY')), paymill_util::API_ENDPOINT);
         $transaction = $transactionObject->getOne($data->event->event_resource->transaction->id);
         // Validate data
         if (isset($transaction['id']) && $transaction['id'] === $data->event->event_resource->transaction->id) {
             $valid = true;
         }
     }
     $this->log("Webhook Validation", var_export($valid, true));
     return $valid;
 }
 private function _validateRequest($data)
 {
     $valid = false;
     if (!is_null($data) && isset($data['event']) && isset($data['event']['event_resource'])) {
         $transactionId = $data['event']['event_resource']['id'];
         if (substr($transactionId, 0, 4) !== 'tran') {
             $transactionId = $data['event']['event_resource']['transaction']['id'];
         }
         $transactionObject = new Services_Paymill_Transactions(trim(Mage::helper('paymill/optionHelper')->getPrivateKey()), Mage::helper('paymill')->getApiUrl());
         $transaction = $transactionObject->getOne($transactionId);
         if (isset($transaction['id']) && $transaction['id'] === $transactionId) {
             $valid = true;
         }
     }
     return $valid;
 }
function validateNotification($notification)
{
    if (isset($notification) && !empty($notification)) {
        // Check eventtype
        if (isset($notification['event']['event_type'])) {
            if ($notification['event']['event_type'] == 'refund.succeeded') {
                $id = null;
                if (isset($notification['event']['event_resource']['transaction']['id'])) {
                    $id = $notification['event']['event_resource']['transaction']['id'];
                }
                $transactionObject = new Services_Paymill_Transactions(Configuration::get('PIGMBH_PAYMILL_PRIVATEKEY'), 'https://api.paymill.com/v2/');
                $result = $transactionObject->getOne($id);
                return $result['id'] === $id;
            }
        }
    }
    return false;
}
 /**
  * Tests Services_Paymill_Transaction->delete()
  */
 public function testDelete()
 {
     try {
         $this->_transaction->delete();
     } catch (Exception $e) {
         $this->assertInstanceOf('Services_Paymill_Exception', $e);
         $this->assertEquals(404, $e->getCode());
     }
 }
 private function _success()
 {
     global $db;
     $preauthId = null;
     $transactionId = null;
     if (array_key_exists('paymillTransactionId', $_SESSION)) {
         $transactionId = $_SESSION['paymillTransactionId'];
         unset($_SESSION['paymillTransactionId']);
     } elseif (array_key_exists('paymillPreauthId', $_SESSION)) {
         $preauthId = $_SESSION['paymillPreauthId'];
         unset($_SESSION['paymillPreauthId']);
     }
     if (!is_null($transactionId)) {
         $this->_transactions->update(array('id' => $_SESSION['paymillTransactionId'], 'description' => ' OrderID: ' . $_SESSION['success_order_id'] . ' ' . _STORE_NAME));
     }
     if (!is_null($transactionId) || !is_null($preauthId)) {
         $db->Execute('INSERT INTO `pi_paymill_transaction` ' . '(`order_id`, `transaction_id`, `preauth_id`) ' . 'VALUES(' . '"' . $_SESSION['success_order_id'] . '", ' . '"' . $transactionId . '", ' . '"' . $preauthId . '"' . ')');
     }
 }
 private function proceedRefund($transactionId)
 {
     $result = false;
     $this->init();
     $this->load->model('sale/order');
     $orderId = $this->getPost('orderId', 0);
     $transaction = $this->paymillTransaction->getOne($transactionId);
     $this->log('Transaction used for Refund', var_export($transaction, true));
     if (is_array($transaction)) {
         try {
             $result = $this->paymillRefund->create(array('transactionId' => $transactionId, 'params' => array('amount' => $transaction['origin_amount'])));
             $this->log('Refund resulted in', var_export($result, true));
             $this->log('Refund successfully', $transaction['id']);
             $orderStatusId = $this->db->query('SELECT `order_status_id` FROM `' . DB_PREFIX . 'order_status` WHERE `name`= "Refunded"')->row['order_status_id'];
             $this->model_sale_order->addOrderHistory($orderId, array('order_status_id' => $orderStatusId, 'notify' => true, 'comment' => ''));
         } catch (Exception $ex) {
             $result = false;
         }
     }
     return $result;
 }
Example #13
0
 private function validateNotification($notification)
 {
     if (isset($notification) && !empty($notification)) {
         // Check eventtype
         if (isset($notification['event']['event_type'])) {
             if ($notification['event']['event_type'] == 'refunded.succeeded') {
                 $id = null;
                 if (isset($notification['event']['event_resource']['transaction']['id'])) {
                     $id = $notification['event']['event_resource']['transaction']['id'];
                 }
                 $privateKey = trim($this->config->get($this->getPaymentName() . '_privatekey'));
                 $transactionObject = new Services_Paymill_Transactions($privateKey, 'https://api.paymill.com/v2/');
                 $result = $transactionObject->getOne($id);
                 return $result['id'] === $id;
             }
         }
     }
     return false;
 }
 function process_payment($cart)
 {
     global $tc;
     $this->maybe_start_session();
     $this->save_cart_info();
     if (isset($_POST['paymillToken'])) {
         $_SESSION['paymillToken'] = $_POST['paymillToken'];
     }
     if (!isset($_SESSION['paymillToken'])) {
         $_SESSION['tc_gateway_error'] = __('The Paymill Token was not generated correctly.', 'tc');
         wp_redirect($tc->get_payment_slug(true));
         tc_js_redirect($tc->get_payment_slug(true));
         exit;
         return false;
     }
     define('PAYMILL_API_HOST', 'https://api.paymill.com/v2/');
     define('PAYMILL_API_KEY', $this->get_option('private_key'));
     $token = $_SESSION['paymillToken'];
     if ($token) {
         require "paymill/lib/Services/Paymill/Transactions.php";
         $transactionsObject = new Services_Paymill_Transactions(PAYMILL_API_KEY, PAYMILL_API_HOST);
         $order_id = $tc->generate_order_id();
         try {
             $params = array('amount' => $this->total() * 100, 'currency' => strtolower($this->currency), 'token' => $token, 'description' => $this->cart_items());
             $charge = $transactionsObject->create($params);
             if ($charge['status'] == 'closed') {
                 //setup our payment details
                 $payment_info = array();
                 $payment_info['method'] = sprintf(__('%1$s Card ending in %2$s - Expires %3$s', 'tc'), ucfirst($charge['payment']['card_type']), $charge['payment']['last4'], $charge['payment']['expire_month'] . '/' . $charge['payment']['expire_year']);
                 $payment_info['transaction_id'] = $charge['id'];
                 $payment_info = $this->save_payment_info();
                 $paid = true;
                 $order = $tc->create_order($order_id, $this->cart_contents(), $this->cart_info(), $payment_info, $paid);
                 wp_redirect($tc->get_confirmation_slug(true, $order_id));
                 tc_js_redirect($tc->get_confirmation_slug(true, $order_id));
                 exit;
             }
         } catch (Exception $e) {
             unset($_SESSION['paymillToken']);
             $_SESSION['tc_gateway_error'] = sprintf(__('There was an error processing your card: "%s".', 'tc'), $e->getMessage());
             wp_redirect($tc->get_payment_slug(true));
             tc_js_redirect($tc->get_payment_slug(true));
             exit;
             return false;
         }
     }
 }
 /**
  * This method updates the description of the current transaction by adding the order number
  * @param $orderNumber
  * @param $paymentProcessor
  * @param $loggingManager
  */
 private function _updateTransaction($orderNumber, $paymentProcessor)
 {
     //Update Transaction
     require_once dirname(__FILE__) . '/../../lib/Services/Paymill/Transactions.php';
     $user = Shopware()->Session()->sOrderVariables['sUserData'];
     $swConfig = Shopware()->Plugins()->Frontend()->PaymPaymentCreditcard()->Config();
     $privateKey = trim($swConfig->get("privateKey"));
     $apiUrl = "https://api.paymill.com/v2/";
     $transaction = new Services_Paymill_Transactions($privateKey, $apiUrl);
     $description = $orderNumber . " " . $user['additional']['user']['email'] . " " . Shopware()->Config()->get('shopname');
     $description = substr($description, 0, 128);
     $updateResponse = $transaction->update(array('id' => $paymentProcessor->getTransactionId(), 'description' => $description));
     if ($updateResponse['response_code'] === 20000) {
         $this->logging->log("Successfully updated the description of " . $paymentProcessor->getTransactionId(), $description);
     } else {
         $this->logging->log("There was an error updating the description of " . $paymentProcessor->getTransactionId(), $description);
     }
 }
 /**
  * Eventhandler for chargeback actions
  */
 public function chargebackAction()
 {
     $type = $this->_request['type'];
     $transactionId = $this->_request['event_resource']['id'];
     $this->requireTransactions();
     $transactions = new Services_Paymill_Transactions($this->_privateKey, $this->_apiUrl);
     $transaction = $transactions->getOne($transactionId);
     if ($this->getWebhookState($type) && isset($transaction['id'])) {
         $this->_request['action'] = 'Chargeback';
         $this->updateOrderStatus();
     } else {
         $this->successAction();
     }
 }
 function onTP_Processpayment($data, $vars = array())
 {
     $isValid = true;
     $error = array();
     $error['code'] = '';
     $error['desc'] = '';
     $trxnstatus = '';
     //API HOST KEY
     define('PAYMILL_API_HOST', 'https://api.paymill.com/v2/');
     //FROM PAYMILL PLUGIN BACKEND
     define('PAYMILL_API_KEY', $this->private_key);
     set_include_path(implode(PATH_SEPARATOR, array(realpath(realpath(dirname(__FILE__)) . '/lib'), get_include_path())));
     //CREATED TOKEN
     $token = $data["token"];
     $session = JFactory::getSession();
     if ($token) {
         // access lib folder
         require "paymill/lib/Services/Paymill/Transactions.php";
         //pass api key and private key to Services_Paymill_Transactions function
         $transactionsObject = new Services_Paymill_Transactions(PAYMILL_API_KEY, PAYMILL_API_HOST);
         $params = array('amount' => $session->get('amount') * 100, 'currency' => $session->set('currency_code'), 'token' => $token, 'description' => 'Test Transaction');
         $transaction = $transactionsObject->create($params);
         if ($transaction['error']) {
             $error['code'] = '';
             $error['desc'] = $transaction['error'];
             $result = array('transaction_id' => '', 'order_id' => $data["order_id"], 'status' => 'E', 'total_paid_amt' => '0', 'raw_data' => '', 'error' => $transaction['error'], 'return' => $data['return']);
             return $result;
         } else {
             //if error not find
             //$status varible
             // amount check // response amount in cent
             $gross_amt = (double) ($transaction['origin_amount'] / 100);
             if ($isValid) {
                 if (!empty($vars)) {
                     // Check that the amount is correct
                     $order_amount = (double) $vars->amount;
                     $retrunamount = (double) $gross_amt;
                     $epsilon = 0.01;
                     if ($order_amount - $retrunamount > $epsilon) {
                         $trxnstatus = 'failed';
                         // change response status to ERROR FOR AMOUNT ONLY
                         $isValid = false;
                         $error['desc'] .= " ORDER_AMOUNT_MISTMATCH - order amount= " . $order_amount . ' response order amount = ' . $retrunamount;
                     }
                 }
             }
             if ($trxnstatus == 'failed') {
                 $status = $this->translateResponse($ttrxnstatus);
             } else {
                 $status = $this->translateResponse($transaction['status']);
             }
             //array pass to translate function
             $result = array('transaction_id' => $transaction['id'], 'order_id' => $data["order_id"], 'status' => $status, 'total_paid_amt' => $transaction['origin_amount'], 'raw_data' => json_encode($transaction), 'error' => $error, 'return' => $data['return']);
             return $result;
         }
     } else {
         $result = array('transaction_id' => '', 'order_id' => $data["order_id"], 'status' => 'E', 'total_paid_amt' => '0', 'raw_data' => '', 'error' => $transaction['error'], 'return' => $data['return']);
         return $result;
     }
     //end if token
 }
Example #18
0
 function setup_payment($response, $paymentType, $order)
 {
     //$this->alert('ok');
     if ($paymentType == 'PAYMILL') {
         $order_pay = $order->generate_data_to_pay();
         $token = $_POST['token'];
         $job_id = $order_pay['product_id'];
         $description = $_POST['description'];
         $paymill_api = $this->get_api();
         try {
             $params = array('token' => $token);
             $apiKey = $paymill_api['secret_key'];
             $apiEndpoint = self::$api_endpoint;
             $paymill = new Services_Paymill_Transactions($apiKey, $apiEndpoint);
             //$creditcard = $paymentsObject->create($params);
             //$Paymill->update();
             //Paymill::setApiKey($paymill['secret_key']);
             $order_pay = $order->generate_data_to_pay();
             $charge = $paymill->create(array('amount' => $order_pay['total'] * 100, 'currency' => $order_pay['currencyCodeType'], 'token' => $token, 'description' => $description));
             $response = array('success' => false, 'msg' => $charge, 'paymentType' => 'paymill');
             //return $response;
             $id = $charge['id'];
             $token = md5($id);
             $order->set_payment_code($token);
             $order->set_payer_id($id);
             $order->update_order();
             $returnURL = et_get_page_link('process-payment', array('paymentType' => 'paymill', 'token' => $token));
             $response = array('success' => true, 'data' => array('url' => $returnURL), 'paymentType' => 'paymill');
         } catch (Exception $e) {
             $value = $e->getJsonBody();
             $response = array('success' => false, 'msg' => $value['error']['message'], 'paymentType' => 'paymill');
         }
     }
     return $response;
 }
Example #19
0
 public function onAKPaymentCallback($paymentmethod, $data)
 {
     JLoader::import('joomla.utilities.date');
     // Check if we're supposed to handle this
     if ($paymentmethod != $this->ppName) {
         return false;
     }
     $isValid = true;
     // Load the relevant subscription row
     $id = $data['sid'];
     $subscription = null;
     // CHECK: Is this a valid subscription record?
     if ($id > 0) {
         $subscription = F0FModel::getTmpInstance('Subscriptions', 'AkeebasubsModel')->setId($id)->getItem();
         if ($subscription->akeebasubs_subscription_id <= 0 || $subscription->akeebasubs_subscription_id != $id) {
             $subscription = null;
             $isValid = false;
         }
     } else {
         $isValid = false;
     }
     if (!$isValid) {
         $data['akeebasubs_failure_reason'] = 'The subscription ID is invalid';
     }
     // CHECK: Is the amount correct?
     $isPartialRefund = false;
     if ($isValid) {
         $mc_gross = $data['amount'];
         // Remember: the amount is in cents, e.g. 400 means 4.00 Euros
         $gross = (int) ($subscription->gross_amount * 100);
         $isValid = $gross - $mc_gross < 0.01;
         if (!$isValid) {
             $data['akeebasubs_failure_reason'] = 'Paid amount does not match the subscription amount';
         }
     }
     // CHECK: Is this transaction valid?
     // Log the IPN data
     $this->logIPN($data, $isValid, 'CALLBACK');
     // Fraud attempt? Do nothing more!
     if (!$isValid) {
         $level = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel')->setId($subscription->akeebasubs_level_id)->getItem();
         $error_url = 'index.php?option=' . JRequest::getCmd('option') . '&view=level&slug=' . $level->slug . '&layout=' . JRequest::getCmd('layout', 'default');
         $error_url = JRoute::_($error_url, false);
         JFactory::getApplication()->redirect($error_url, $data['akeebasubs_failure_reason'], 'error');
         return false;
     }
     // ACTION: Initialise common variables
     if ($isValid) {
         $apiKey = $this->getPrivateKey();
         $apiEndpoint = 'https://api.paymill.de/v2/';
         $db = JFactory::getDbo();
     }
     // CHECK: Do we have a user already defined in PayMill?
     $user = JFactory::getUser($subscription->user_id);
     $clientsObject = new Services_Paymill_Clients($apiKey, $apiEndpoint);
     $filters = array('email' => $user->email);
     $clients = $clientsObject->get($filters);
     // ACTION: Get the client ID or create and save a new user in PayMill if necessary
     if (count($clients)) {
         $clientRecord = array_pop($clients);
     } else {
         $params = array('email' => $user->email, 'description' => $user->name . ' [' . $user->username . ']');
         try {
             $clientRecord = $clientsObject->create($params);
         } catch (Exception $exc) {
             $isValid = false;
             $params['akeebasubs_failure_reason'] = $exc->getMessage();
         }
         if (!array_key_exists('id', $clientRecord) || empty($clientRecord['id'])) {
             // Apparently the client creation failed
             $isValid = false;
             $params['akeebasubs_failure_reason'] = JText::_('PLG_AKPAYMENT_PAYMILL_ERROR_CLIENT');
         }
         // Log the user creation data
         $this->logIPN($data, $isValid, 'USER');
         // Fraud attempt? Do nothing more!
         if (!$isValid) {
             $level = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel')->setId($subscription->akeebasubs_level_id)->getItem();
             $error_url = 'index.php?option=' . JRequest::getCmd('option') . '&view=level&slug=' . $level->slug . '&layout=' . JRequest::getCmd('layout', 'default');
             $error_url = JRoute::_($error_url, false);
             JFactory::getApplication()->redirect($error_url, $params['akeebasubs_failure_reason'], 'error');
             return false;
         }
     }
     $client = $clientRecord['id'];
     // CHECK: Do we already have a payment for this subscription?
     // -- Load the processor key from database. This prevents race conditions.
     $query = $db->getQuery(true)->select($db->qn('processor_key'))->from('#__akeebasubs_subscriptions')->where($db->qn('akeebasubs_subscription_id') . ' = ' . $db->q($subscription->akeebasubs_subscription_id));
     $db->setQuery($query);
     $payment_id = $db->loadResult();
     // ACTION: Create and save a new payment for this subscription if there is no payment or transaction yet
     if (substr($payment_id, 0, 4) != 'pay_' && substr($payment_id, 0, 5) != 'tran_') {
         $params = array('client' => $client, 'token' => $data['token']);
         $paymentsObject = new Services_Paymill_Payments($apiKey, $apiEndpoint);
         try {
             $creditcard = $paymentsObject->create($params);
         } catch (Exception $exc) {
             $isValid = false;
             $params['akeebasubs_failure_reason'] = $exc->getMessage();
         }
         if (!array_key_exists('id', $creditcard) || empty($creditcard['id'])) {
             // Apparently the credit card capture creation failed
             $isValid = false;
             $params['akeebasubs_failure_reason'] = JText::_('PLG_AKPAYMENT_PAYMILL_ERROR_CC') . '<br/>Tech info: <tt>' . htmlentities($creditcard['error']) . '</tt>';
         }
         // Log the payment creation data
         $this->logIPN($data, $isValid, 'PAYMENT');
         // Fraud attempt? Do nothing more!
         if (!$isValid) {
             $level = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel')->setId($subscription->akeebasubs_level_id)->getItem();
             $error_url = 'index.php?option=' . JRequest::getCmd('option') . '&view=level&slug=' . $level->slug . '&layout=' . JRequest::getCmd('layout', 'default');
             $error_url = JRoute::_($error_url, false);
             JFactory::getApplication()->redirect($error_url, $params['akeebasubs_failure_reason'], 'error');
             return false;
         }
         $subscription->processor_key = $creditcard['id'];
         $payment_id = $creditcard['id'];
         // Save the payment information WITHOUT using the table (skips the plugins)
         // This prevents double payments from being recorded
         $oUpdate = (object) array('akeebasubs_subscription_id' => $subscription->akeebasubs_subscription_id, 'processor_key' => $subscription->processor_key, 'state' => 'P');
         JFactory::getDbo()->updateObject('#__akeebasubs_subscriptions', $oUpdate, 'akeebasubs_subscription_id');
     }
     // CHECK: Do we already have a transaction for this subscription?
     // -- Load the processor key from database. This prevents race conditions.
     $query = $db->getQuery(true)->select($db->qn('processor_key'))->from('#__akeebasubs_subscriptions')->where($db->qn('akeebasubs_subscription_id') . ' = ' . $db->q($subscription->akeebasubs_subscription_id));
     $db->setQuery($query);
     $payment_id = $db->loadResult();
     // ACTION: Create a transaction if necessary
     if (substr($payment_id, 0, 5) != 'tran_') {
         // First update the object with a fake transaction
         $subscription->processor_key = 'tran_in_progress';
         // Save the payment information WITHOUT using the table (skips the plugins)
         // This prevents double payments from being recorded
         $oUpdate = (object) array('akeebasubs_subscription_id' => $subscription->akeebasubs_subscription_id, 'processor_key' => $subscription->processor_key, 'state' => 'P');
         JFactory::getDbo()->updateObject('#__akeebasubs_subscriptions', $oUpdate, 'akeebasubs_subscription_id');
         // Create the transaction
         $params = array('amount' => $data['amount'], 'currency' => $data['currency'], 'client' => $client, 'payment' => $payment_id, 'description' => $data['description']);
         try {
             $transactionsObject = new Services_Paymill_Transactions($apiKey, $apiEndpoint);
             $transaction = $transactionsObject->create($params);
         } catch (Exception $exc) {
             $isValid = false;
             $params['akeebasubs_failure_reason'] = $exc->getMessage();
         }
         if (!array_key_exists('id', $transaction) || empty($transaction['id'])) {
             // Apparently the transaction creation failed
             $isValid = false;
             $params['akeebasubs_failure_reason'] = JText::_('PLG_AKPAYMENT_PAYMILL_ERROR_TRANS');
         }
         // Log the payment creation data
         $this->logIPN($data, $isValid, 'TRANSACTION');
         if (!$isValid) {
             $transaction_id = $payment_id;
         } else {
             $transaction_id = $transaction['id'];
         }
         // First update the object
         $subscription->processor_key = $transaction_id;
         // Save the payment information WITHOUT using the table (skips the plugins)
         // This prevents double payments from being recorded
         $oUpdate = (object) array('akeebasubs_subscription_id' => $subscription->akeebasubs_subscription_id, 'processor_key' => $subscription->processor_key);
         JFactory::getDbo()->updateObject('#__akeebasubs_subscriptions', $oUpdate, 'akeebasubs_subscription_id');
         // Fraud attempt? Do nothing more!
         if (!$isValid) {
             $level = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel')->setId($subscription->akeebasubs_level_id)->getItem();
             $error_url = 'index.php?option=' . JRequest::getCmd('option') . '&view=level&slug=' . $level->slug . '&layout=' . JRequest::getCmd('layout', 'default');
             $error_url = JRoute::_($error_url, false);
             JFactory::getApplication()->redirect($error_url, $params['akeebasubs_failure_reason'], 'error');
             return false;
         }
     } else {
         // ACTION: If no transaction is necessary, show an error
         $level = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel')->setId($subscription->akeebasubs_level_id)->getItem();
         $error_url = 'index.php?option=' . JRequest::getCmd('option') . '&view=level&slug=' . $level->slug . '&layout=' . JRequest::getCmd('layout', 'default');
         $error_url = JRoute::_($error_url, false);
         JFactory::getApplication()->redirect($error_url, 'Cannot process the transaction twice. Wait to receive your subscription confirmation email and do not retry submitting the payment form again.', 'error');
         return false;
     }
     if ($isValid) {
         if ($this->params->get('sandbox') == $transaction['livemode']) {
             $isValid = false;
             $data['akeebasubs_failure_reason'] = "Transaction done in wrong mode.";
         }
     }
     // Payment status
     // Check the payment_status
     switch ($transaction['status']) {
         case 'closed':
         case 'partial_refunded':
             $newStatus = 'C';
             break;
         case 'open':
         case 'pending':
         case 'preauthorize':
             $newStatus = 'P';
             break;
         case 'failed':
         case 'refunded':
             $newStatus = 'X';
             break;
     }
     // Update subscription status (this also automatically calls the plugins)
     $updates = array('akeebasubs_subscription_id' => $id, 'processor_key' => $transaction_id, 'state' => $newStatus, 'enabled' => 0);
     JLoader::import('joomla.utilities.date');
     if ($newStatus == 'C') {
         $this->fixDates($subscription, $updates);
     }
     $subscription->save($updates);
     // Run the onAKAfterPaymentCallback events
     JLoader::import('joomla.plugin.helper');
     JPluginHelper::importPlugin('akeebasubs');
     $app = JFactory::getApplication();
     $jResponse = $app->triggerEvent('onAKAfterPaymentCallback', array($subscription));
     // Redirect the user to the "thank you" page
     $level = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel')->setId($subscription->akeebasubs_level_id)->getItem();
     $thankyouUrl = JRoute::_('index.php?option=com_akeebasubs&view=message&slug=' . $level->slug . '&layout=order&subid=' . $subscription->akeebasubs_subscription_id, false);
     JFactory::getApplication()->redirect($thankyouUrl);
     return true;
 }
Example #20
0
 function plgVmOnPaymentNotification()
 {
     $virtuemart_paymentmethod_id = JRequest::getInt('pm', 0);
     $order_number = JRequest::getInt('on', 0);
     if (!($method = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) {
         return null;
         // Another method was selected, do nothing
     }
     if (!$this->selectedThisElement($method->payment_element)) {
         return false;
     }
     if (!class_exists('VirtueMartModelOrders')) {
         require JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php';
     }
     $virtuemart_order_id = VirtueMartModelOrders::getOrderIdByOrderNumber($order_number);
     $this->logInfo('plgVmOnPaymentNotification: virtuemart_order_id  found ' . $virtuemart_order_id, 'message');
     if (!$virtuemart_order_id) {
         $this->_debug = true;
         // force debug here
         $this->logInfo('plgVmOnPaymentNotification: virtuemart_order_id not found ', 'ERROR');
         // send an email to admin, and ofc not update the order status: exit  is fine
         //$this->sendEmailToVendorAndAdmins(JText::_('VMPAYMENT_PAYMILL_ERROR_EMAIL_SUBJECT'), JText::_('VMPAYMENT_PAYMILL_UNKNOW_ORDER_ID'));
         exit;
     }
     $vendorId = 0;
     $payment = $this->getDataByOrderId($virtuemart_order_id);
     $method = $this->getVmPluginMethod($payment->virtuemart_paymentmethod_id);
     if (!$this->selectedThisElement($method->payment_element)) {
         return false;
     }
     $this->_debug = $method->debug;
     if (!$payment) {
         $this->logInfo('getDataByOrderId payment not found: exit ', 'ERROR');
         return null;
     }
     $new_status = 'C';
     $new_comment = 'Paymill - Geld ist eingegangen.';
     $this->logInfo('plgVmOnPaymentNotification return new_status:' . $new_status, 'message');
     if ($virtuemart_order_id) {
         // send the email only if payment has been accepted
         if (!class_exists('VirtueMartModelOrders')) {
             require JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php';
         }
         $modelOrder = new VirtueMartModelOrders();
         $order['order_status'] = $new_status;
         $order['comments'] = $new_comment;
         $order['virtuemart_order_id'] = $virtuemart_order_id;
         $order['customer_notified'] = 0;
         // TOKEN FROM SESSION
         $session = JFactory::getSession();
         $pm_token = $session->get('pm_token');
         //define NEW PM_VARS
         define('API_HOST', 'https://api.paymill.com/v2/');
         define('API_KEY', $method->private_key);
         if ($pm_token) {
             require "components/com_paymillapi/lib/Services/Paymill/Transactions.php";
             $transactionsObject = new Services_Paymill_Transactions(API_KEY, API_HOST);
             $params = array('amount' => $totalInPaymentCurrency * 100, 'currency' => 'eur', 'token' => $pm_token, 'description' => $address->email);
             $transaction = $transactionsObject->create($params);
             $pm_status = $transaction['status'];
             $q = "UPDATE #__paymill SET status = '" . $pm_status . "', email = '" . $address->email . "' WHERE token = '" . $pm_token . "'";
             $db->setQuery($q);
             $db->query();
             $new_status = 'C';
             $modelOrder->updateStatusForOneOrder($virtuemart_order_id, $order, true);
         } else {
             echo "Ihre Kreditkartenzahlung war leider fehlerhaft. Bitte überprüfen Sie Ihre Eingabe.<br /><br /><a href='" . JURI::root() . "/component/virtuemart/cart/editpayment?Itemid=0'>Zurück zur Bezahlung</a>";
         }
         // END NEW PM_VARS
         //$modelOrder->updateStatusForOneOrder($virtuemart_order_id, $order, true);
     }
     return true;
 }
 /**
  * Updates the description of target transaction by adding the prefix 'OrderID: ' followed by the order id
  * @param String $id
  * @param String $orderId
  */
 function updateTransaction($id, $orderId)
 {
     $this->log('Updating transaction description', '');
     require_once DIR_FS_CATALOG . 'ext/modules/payment/paymill/lib/Services/Paymill/Transactions.php';
     $transactions = new Services_Paymill_Transactions($this->privateKey, $this->apiUrl);
     $transaction = $transactions->getOne($id);
     $description = substr('OrderID: ' . $orderId . ' ' . $transaction['description'], 0, 128);
     $transactions->update(array('id' => $id, 'description' => $description));
 }
 /**
  * Updates the description of target transaction by adding the prefix 'OrderID: ' followed by the order id
  * @param String $id
  * @param String $orderId
  */
 function updateTransaction($id, $orderId)
 {
     $transactions = new Services_Paymill_Transactions($this->privateKey, $this->apiUrl);
     $transaction = $transactions->getOne($id);
     $description = substr('OrderID: ' . $orderId . ' ' . $transaction['description'], 0, 128);
     $transactions->update(array('id' => $id, 'description' => $description));
 }
 private function updatePaymillTransaction($transactionID, $description)
 {
     $transactionObject = new Services_Paymill_Transactions(Configuration::get('PIGMBH_PAYMILL_PRIVATEKEY'), "https://api.paymill.com/v2/");
     $transactionObject->update(array('id' => $transactionID, 'description' => $description));
 }
Example #24
0
function ae_paymill_setup_payment($response, $paymentType, $order)
{
    if ($paymentType == 'PAYMILL') {
        $order_pay = $order->generate_data_to_pay();
        $token = $_POST['token'];
        $job_id = $order_pay['product_id'];
        $paymill_api = ae_get_option('paymill');
        $description = isset($_POST['description']) ? $_POST['description'] : '';
        global $user_email;
        try {
            $params = array('token' => $token);
            $apiKey = $paymill_api['private_key'];
            $apiEndpoint = 'https://api.paymill.com/v2.1/';
            $paymill = new Services_Paymill_Transactions($apiKey, $apiEndpoint);
            //$creditcard = $paymentsObject->create($params);
            //$Paymill->update();
            //Paymill::setApiKey($paymill['secret_key']);
            $order_pay = $order->generate_data_to_pay();
            $charge = $paymill->create(array('amount' => $order_pay['total'] * 100, 'currency' => $order_pay['currencyCodeType'], 'token' => $token, 'description' => $description));
            $returnURL = et_get_page_link('process-payment', array('paymentType' => 'paymill'));
            if (isset($charge['error']) || !isset($charge['id'])) {
                $response = array('success' => false, 'msg' => __('Transaction was not completed successfully!', ET_DOMAIN), 'data' => array('url' => $returnURL), 'paymentType' => 'paymill', 'charge' => $charge);
            } else {
                if (isset($charge['id'])) {
                    $id = $charge['id'];
                    $token = md5($id);
                    $order->set_payment_code($id);
                    $order->set_payer_id($id);
                    $order->update_order();
                    $returnURL .= '&token=' . $token;
                    $response = array('success' => true, 'data' => array('url' => $returnURL, 'msg' => __('Transaction completed successfull!', ET_DOMAIN)), 'paymentType' => 'paymill');
                }
            }
        } catch (Exception $e) {
            $value = $e->getJsonBody();
            $response = array('success' => false, 'msg' => $value['error']['message'], 'paymentType' => 'paymill');
        }
    }
    return $response;
}
 /**
  * Action Listener to execute the capture for applicable transactions
  *
  */
 public function refundAction()
 {
     $result = false;
     $code = null;
     require_once dirname(__FILE__) . '/../../lib/Services/Paymill/Transactions.php';
     require_once dirname(__FILE__) . '/../../lib/Services/Paymill/Refunds.php';
     $swConfig = Shopware()->Plugins()->Frontend()->PaymPaymentCreditcard()->Config();
     $refund = new Services_Paymill_Refunds(trim($swConfig->get("privateKey")), 'https://api.paymill.com/v2/');
     $transactionObject = new Services_Paymill_Transactions(trim($swConfig->get("privateKey")), 'https://api.paymill.com/v2/');
     $modelHelper = new Shopware_Plugins_Frontend_PaymPaymentCreditcard_Components_ModelHelper();
     $orderNumber = $modelHelper->getOrderNumberById($this->Request()->getParam("orderId"));
     $transactionId = $modelHelper->getPaymillTransactionId($orderNumber);
     $transactionResult = $transactionObject->getOne($transactionId);
     //Create Transaction
     $parameter = array('transactionId' => $transactionId, 'params' => array('amount' => $transactionResult['amount'], 'description' => $transactionResult['client']['email'] . " " . Shopware()->Config()->get('shopname')));
     $response = $refund->create($parameter);
     if (isset($response['response_code'])) {
         $code = $response['response_code'];
     }
     //Validate result and prepare feedback
     if ($this->_validateRefundResponse($response)) {
         $result = true;
         $modelHelper->setPaymillRefund($orderNumber, $response['id']);
         $this->_updatePaymentStatus(20, $this->Request()->getParam("orderId"));
     }
     $this->View()->assign(array('success' => $result, 'code' => $code));
 }
Example #26
0
 /**
  * Use this to do the final payment. Create the order then process the payment. If
  *  you know the payment is successful right away go ahead and change the order status
  *  as well.
  *  Call $mp->cart_checkout_error($msg, $context); to handle errors. If no errors
  *  it will redirect to the next step.
  *
  * @param array $cart. Contains the cart contents for the current blog, global cart if $mp->global_cart is true
  * @param array $shipping_info. Contains shipping info and email in case you need it
  */
 function process_payment($cart, $shipping_info)
 {
     global $mp;
     $settings = get_option('mp_settings');
     //make sure token is set at this point
     if (!isset($_SESSION['paymillToken'])) {
         $mp->cart_checkout_error(__('The Paymill Token was not generated correctly. Please go back and try again.', 'mp'));
         return false;
     }
     define('PAYMILL_API_HOST', 'https://api.paymill.com/v2/');
     define('PAYMILL_API_KEY', $settings['gateways']['paymill']['private_key']);
     $token = $_SESSION['paymillToken'];
     if ($token) {
         require "paymill-files/lib/Services/Paymill/Transactions.php";
         $transactionsObject = new Services_Paymill_Transactions(PAYMILL_API_KEY, PAYMILL_API_HOST);
         $totals = array();
         $coupon_code = $mp->get_coupon_code();
         foreach ($cart as $product_id => $variations) {
             foreach ($variations as $variation => $data) {
                 $price = $mp->coupon_value_product($coupon_code, $data['price'] * $data['quantity'], $product_id);
                 $totals[] = $price;
             }
         }
         $total = array_sum($totals);
         //shipping line
         if ($shipping_price = $mp->shipping_price()) {
             $total += $shipping_price;
         }
         //tax line
         if ($tax_price = $mp->tax_price()) {
             $total += $tax_price;
         }
         $order_id = $mp->generate_order_id();
         try {
             $params = array('amount' => $total * 100, 'currency' => strtolower($this->currency), 'token' => $token, 'description' => sprintf(__('%s Store Purchase - Order ID: %s, Email: %s', 'mp'), get_bloginfo('name'), $order_id, $_SESSION['mp_shipping_info']['email']));
             $charge = $transactionsObject->create($params);
             if ($charge['status'] == 'closed') {
                 //setup our payment details
                 $payment_info = array();
                 $payment_info['gateway_public_name'] = $this->public_name;
                 $payment_info['gateway_private_name'] = $this->admin_name;
                 $payment_info['method'] = sprintf(__('%1$s Card ending in %2$s - Expires %3$s', 'mp'), ucfirst($charge['payment']['card_type']), $charge['payment']['last4'], $charge['payment']['expire_month'] . '/' . $charge['payment']['expire_year']);
                 $payment_info['transaction_id'] = $charge['id'];
                 $timestamp = time();
                 $payment_info['status'][$timestamp] = __('Paid', 'mp');
                 $payment_info['total'] = $total;
                 $payment_info['currency'] = $this->currency;
                 $order = $mp->create_order($order_id, $cart, $_SESSION['mp_shipping_info'], $payment_info, true);
                 unset($_SESSION['paymillToken']);
                 $mp->set_cart_cookie(array());
             }
         } catch (Exception $e) {
             unset($_SESSION['paymillToken']);
             $mp->cart_checkout_error(sprintf(__('There was an error processing your card: "%s". Please <a href="%s">go back and try again</a>.', 'mp'), $e->getMessage(), mp_checkout_step_url('checkout')));
             return false;
         }
     }
 }