Exemple #1
0
 /**
  * Process payment 
  *
  */
 function processPayment($row, $data)
 {
     $Itemid = JRequest::getint('Itemid');
     $config = OSMembershipHelper::getConfig();
     OSMembershipHelper::sendEmails($row, $config);
     $db = JFactory::getDbo();
     $sql = 'SELECT subscription_complete_url FROM #__osmembership_plans WHERE id=' . $row->plan_id;
     $db->setQuery($sql);
     $subscriptionCompleteURL = $db->loadResult();
     if ($subscriptionCompleteURL) {
         JFactory::getApplication()->redirect($subscriptionCompleteURL);
     } else {
         JFactory::getApplication()->redirect(JRoute::_('index.php?option=com_osmembership&view=complete&act=' . $row->act . '&subscription_code=' . $row->subscription_code . '&Itemid=' . $Itemid, false, false));
     }
 }
Exemple #2
0
 /**
  * Process payment with the posted data
  *
  * @param array $data array
  * @return void
  */
 function processPayment($row, $data)
 {
     $mainframe = JFactory::getApplication();
     $Itemid = JRequest::getInt('Itemid');
     $data['x_description'] = $data['item_name'];
     $data['x_exp_date'] = str_pad($data['exp_month'], 2, '0', STR_PAD_LEFT) . '/' . substr($data['exp_year'], 2, 2);
     $data['amount'] = round($data['amount'], 2);
     $retries = 1;
     $testing = $this->mode ? "FALSE" : "TRUE";
     $cc_num = $this->_ccNumber($data["x_card_num"]);
     //Set more parameters for the payment gateway to user
     $authnetValues = array("x_test_request" => $testing, "x_card_num" => $data['x_card_num'], "x_exp_date" => $data['x_exp_date'], "x_card_code" => $data['x_card_code'], "x_description" => $data['x_description'], "x_amount" => $data['amount'], "x_first_name" => $data['first_name'], "x_last_name" => $data['last_name'], "x_address" => $data['address'], "x_city" => $data['city'], "x_state" => $data['state'], "x_phone" => $data['phone'], "x_zip" => $data['zip'], "x_company" => $data['organization'], "x_email" => $data['email'], "x_country" => $data['country'], "x_ship_to_first_name" => $data['first_name'], "x_ship_to_last_name" => $data['last_name'], "x_ship_to_address" => $data['address'], "x_ship_to_city" => $data['city'], "x_ship_to_state" => $data['state'], "x_ship_to_country" => $data['country'], "x_ship_to_zip" => $data['zip'], "x_ship_to_phone" => $data['phone'], "x_ship_to_email" => $data['email'], "cc_number" => $cc_num, "cc_expdate" => $data['x_exp_date'], "cc_emailid" => $data['email']);
     foreach ($authnetValues as $key => $value) {
         $this->setParameter($key, $value);
     }
     $this->_prepareParameters();
     $ch = curl_init($this->url);
     $count = 0;
     while ($count < $retries) {
         curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim($this->fields, "& "));
         //Uncomment this line if you get no response from payment gateway
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
         //If you are using goodaddy hosting, please uncomment the two below lines
         //curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
         //curl_setopt ($ch, CURLOPT_PROXY,"http://proxy.shr.secureserver.net:3128");
         $this->response = curl_exec($ch);
         $this->_parseResults();
         if ($this->getResultResponseFull() == "Approved") {
             $this->approved = true;
             $this->declined = false;
             $this->error = false;
             break;
         } else {
             if ($this->getResultResponseFull() == "Declined") {
                 $this->approved = false;
                 $this->declined = true;
                 $this->error = false;
                 break;
             }
         }
         $count++;
     }
     curl_close($ch);
     if ($this->approved) {
         $config = OSMembershipHelper::getConfig();
         $row->transaction_id = $this->getTransactionID();
         $row->payment_date = date('Y-m-d H:i:s');
         $row->published = 1;
         $row->store();
         if ($row->act == 'upgrade') {
             OSMembershipHelper::processUpgradeMembership($row);
         }
         JPluginHelper::importPlugin('osmembership');
         $dispatcher = JDispatcher::getInstance();
         $dispatcher->trigger('onMembershipActive', array($row));
         OSMembershipHelper::sendEmails($row, $config);
         $db = JFactory::getDbo();
         $sql = 'SELECT subscription_complete_url FROM #__osmembership_plans WHERE id=' . $row->plan_id;
         $db->setQuery($sql);
         $subscriptionCompleteURL = $db->loadResult();
         if ($subscriptionCompleteURL) {
             $mainframe->redirect($subscriptionCompleteURL);
         } else {
             $mainframe->redirect(JRoute::_('index.php?option=com_osmembership&view=complete&act=' . $row->act . '&subscription_code=' . $row->subscription_code . '&Itemid=' . $Itemid, false, false));
         }
         return true;
     } else {
         $_SESSION['reason'] = $this->getResponseText();
         $mainframe->redirect(JRoute::_('index.php?option=com_osmembership&view=failure&id=' . $row->id . '&Itemid=' . $Itemid, false, false));
         return false;
     }
 }
 /**
  * Processs payment 
  *
  * @param string $data
  * @return unknown
  */
 function processRecurringPayment($row, $data)
 {
     $app = JFactory::getApplication();
     $db = JFactory::getDbo();
     $Itemid = JRequest::getInt('Itemid');
     $sql = 'SELECT * FROM #__osmembership_plans WHERE id=' . $row->plan_id;
     $db->setQuery($sql);
     $rowPlan = $db->loadObject();
     $frequency = $rowPlan->subscription_length_unit;
     $length = $rowPlan->subscription_length;
     switch ($frequency) {
         case 'D':
             $unit = 'days';
             break;
         case 'W':
             $unit = 'days';
             break;
         case 'M':
             $unit = 'months';
             break;
         case 'Y':
             $length = 12;
             $unit = 'months';
             break;
     }
     $this->setParameter('refID', $row->subscription_code);
     $this->setParameter('subscrName', $row->first_name . ' ' . $row->last_name);
     $this->setParameter('interval_length', $length);
     $this->setParameter('interval_unit', $unit);
     $this->setParameter('expirationDate', str_pad($data['exp_month'], 2, '0', STR_PAD_LEFT) . '/' . substr($data['exp_year'], 2, 2));
     $this->setParameter('cardNumber', $data['x_card_num']);
     $this->setParameter('firstName', $row->first_name);
     $this->setParameter('lastName', $row->last_name);
     $this->setParameter('address', $row->address);
     $this->setParameter('city', $row->city);
     $this->setParameter('state', $row->state);
     $this->setParameter('zip', $row->zip);
     $this->setParameter('amount', round($data['regular_price'], 2));
     if ($rowPlan->number_payments >= 2) {
         $totalOccurences = $rowPlan->number_payments;
     } else {
         $totalOccurences = 9999;
     }
     $this->setParameter('totalOccurrences', $totalOccurences);
     if ($rowPlan->trial_duration) {
         $this->setParameter('trialAmount', round($data['trial_amount'], 2));
         $this->setParameter('trialOccurrences', $rowPlan->trial_duration);
     }
     $this->createAccount();
     if ($this->success) {
         $config = OSMembershipHelper::getConfig();
         $row->transaction_id = $this->getSubscriberID();
         $row->payment_date = date('Y-m-d H:i:s');
         $row->payment_made = 1;
         $row->published = true;
         $row->store();
         JPluginHelper::importPlugin('osmembership');
         $dispatcher = JDispatcher::getInstance();
         $dispatcher->trigger('onMembershipActive', array($row));
         OSMembershipHelper::sendEmails($row, $config);
         $db = JFactory::getDbo();
         $sql = 'SELECT subscription_complete_url FROM #__osmembership_plans WHERE id=' . $row->plan_id;
         $db->setQuery($sql);
         $subscriptionCompleteURL = $db->loadResult();
         if ($subscriptionCompleteURL) {
             $app->redirect($subscriptionCompleteURL);
         } else {
             $app->redirect(JRoute::_('index.php?option=com_osmembership&view=complete&act=' . $row->act . '&subscription_code=' . $row->subscription_code . '&Itemid=' . $Itemid, false, false));
         }
         return true;
     } else {
         $_SESSION['reason'] = $this->text;
         $app->redirect(JRoute::_('index.php?option=com_osmembership&view=failure&id=' . $row->id . '&Itemid=' . $Itemid, false));
         return false;
     }
 }
Exemple #4
0
 /**
  * Verify recrrung payment
  *
  */
 function verifyRecurringPayment()
 {
     $ret = $this->_validate();
     if ($ret) {
         $config = OSMembershipHelper::getConfig();
         $id = $this->_data['custom'];
         $transactionId = $this->_data['txn_id'];
         $amount = $this->_data['mc_gross'];
         $txnType = $this->_data['txn_type'];
         $subscrId = $this->_data['subscr_id'];
         if ($amount < 0) {
             return false;
         }
         $row = JTable::getInstance('OsMembership', 'Subscriber');
         switch ($txnType) {
             case 'subscr_signup':
                 $row->load($id);
                 if (!$row->id) {
                     return false;
                 }
                 $published = $row->published;
                 if (!$published) {
                     $row->transaction_id = $transactionId;
                     $row->payment_date = date('Y-m-d H:i:s');
                     $row->published = 1;
                     $row->store();
                     OSMembershipHelper::sendEmails($row, $config);
                     JPluginHelper::importPlugin('osmembership');
                     $dispatcher = JDispatcher::getInstance();
                     $dispatcher->trigger('onMembershipActive', array($row));
                 }
                 break;
             case 'subscr_payment':
                 $row->load($id);
                 if (!$row->id) {
                     return false;
                 }
                 $db = JFactory::getDbo();
                 $sql = 'SELECT * FROM #__osmembership_plans WHERE id=' . $row->plan_id;
                 $db->setQuery($sql);
                 $rowPlan = $db->loadObject();
                 $row->payment_made = $row->payment_made + 1;
                 $row->store();
                 if ($rowPlan->trial_duration && $rowPlan->trial_amount == 0 || $row->payment_made > 1) {
                     $process = true;
                 } else {
                     $process = false;
                 }
                 if ($process) {
                     $row->id = 0;
                     $row->created_date = JFactory::getDate()->toSql();
                     $row->invoice_number = 0;
                     $price = $rowPlan->price;
                     $maxDate = null;
                     if ($row->user_id > 0) {
                         $sql = 'SELECT MAX(to_date) FROM #__osmembership_subscribers WHERE user_id=' . $row->user_id . ' AND plan_id=' . $row->plan_id . ' AND published=1';
                         $db->setQuery($sql);
                         $maxDate = $db->loadResult();
                     }
                     if ($maxDate) {
                         $date = JFactory::getDate($maxDate);
                         $row->from_date = $date->add(new DateInterval('P1D'))->toSql();
                     } else {
                         $date = JFactory::getDate();
                         $row->from_date = $date->toSql();
                     }
                     $row->to_date = $date->add(new DateInterval('P' . $rowPlan->subscription_length . $rowPlan->subscription_length_unit))->toSql();
                     $row->act = 'renew';
                     $row->amount = $price;
                     //Calculate coupon discount
                     if ($row->coupon_id) {
                         $sql = 'SELECT * FROM #__osmembership_coupons WHERE id=' . $row->coupon_id;
                         $db->setQuery($sql);
                         $coupon = $db->loadObject();
                         if ($coupon) {
                             if ($coupon->coupon_type == 0) {
                                 $row->discount_amount = $price * $coupon->discount / 100;
                             } else {
                                 $row->discount_amount = min($coupon->discount, $price);
                             }
                         }
                     } else {
                         $row->discount_amount = 0;
                     }
                     if ($rowPlan->tax_rate > 0) {
                         $row->tax_amount = round(($price - $row->discount_amount) * $rowPlan->tax_rate / 100, 2);
                     } else {
                         $row->tax_amount = 0;
                     }
                     $row->gross_amount = $row->amount - $row->discount_amount + $row->tax_amount;
                     $row->published = 1;
                     $row->store();
                     $sql = "INSERT INTO #__osmembership_field_value(field_id, field_value, subscriber_id)" . " SELECT  field_id,field_value, {$row->id}" . " FROM #__osmembership_field_value WHERE subscriber_id={$id}";
                     $db->setQuery($sql);
                     $db->execute();
                     JPluginHelper::importPlugin('osmembership');
                     $dispatcher = JDispatcher::getInstance();
                     $dispatcher->trigger('onMembershipActive', array($row));
                     OSMembershipHelper::sendEmails($row, $config);
                 }
                 break;
         }
         return true;
     } else {
         return false;
     }
 }
Exemple #5
0
 /**
  * Helper function to extend subscription of a user when a recurring payment happens
  *
  * @param $id
  *
  * @return bool
  */
 public static function extendRecurringSubscription($id)
 {
     $config = OSMembershipHelper::getConfig();
     $row = JTable::getInstance('OsMembership', 'Subscriber');
     $row->load($id);
     if (!$row->id) {
         return false;
     }
     $db = JFactory::getDbo();
     $query = $db->getQuery(true);
     $query->select('*')->from('#__osmembership_plans')->where('id = ' . (int) $row->plan_id);
     $db->setQuery($query);
     $rowPlan = $db->loadObject();
     $row->payment_made = $row->payment_made + 1;
     $row->store();
     if ($rowPlan->trial_duration && $rowPlan->trial_amount == 0 || $row->payment_made > 1) {
         $process = true;
     } else {
         $process = false;
     }
     if ($process) {
         $row->id = 0;
         $row->created_date = JFactory::getDate()->toSql();
         $row->invoice_number = 0;
         $price = $rowPlan->price;
         $maxDate = null;
         if ($row->user_id > 0) {
             $sql = 'SELECT MAX(to_date) FROM #__osmembership_subscribers WHERE user_id=' . $row->user_id . ' AND plan_id=' . $row->plan_id . ' AND published=1';
             $db->setQuery($sql);
             $maxDate = $db->loadResult();
         }
         if ($maxDate) {
             $date = JFactory::getDate($maxDate);
             $row->from_date = $date->add(new DateInterval('P1D'))->toSql();
         } else {
             $date = JFactory::getDate();
             $row->from_date = $date->toSql();
         }
         $row->to_date = $date->add(new DateInterval('P' . $rowPlan->subscription_length . $rowPlan->subscription_length_unit))->toSql();
         $row->act = 'renew';
         $row->amount = $price;
         //Calculate coupon discount
         if ($row->coupon_id) {
             $sql = 'SELECT * FROM #__osmembership_coupons WHERE id=' . $row->coupon_id;
             $db->setQuery($sql);
             $coupon = $db->loadObject();
             if ($coupon) {
                 if ($coupon->coupon_type == 0) {
                     $row->discount_amount = $price * $coupon->discount / 100;
                 } else {
                     $row->discount_amount = min($coupon->discount, $price);
                 }
             }
         } else {
             $row->discount_amount = 0;
         }
         if ($rowPlan->tax_rate > 0) {
             $row->tax_amount = round(($price - $row->discount_amount) * $rowPlan->tax_rate / 100, 2);
         } else {
             $row->tax_amount = 0;
         }
         $row->gross_amount = $row->amount - $row->discount_amount + $row->tax_amount;
         $row->published = 1;
         $row->store();
         $sql = "INSERT INTO #__osmembership_field_value(field_id, field_value, subscriber_id)" . " SELECT  field_id,field_value, {$row->id}" . " FROM #__osmembership_field_value WHERE subscriber_id={$id}";
         $db->setQuery($sql);
         $db->execute();
         JPluginHelper::importPlugin('osmembership');
         $dispatcher = JDispatcher::getInstance();
         $dispatcher->trigger('onMembershipActive', array($row));
         OSMembershipHelper::sendEmails($row, $config);
     }
 }
Exemple #6
0
 function processPayment($row, $data)
 {
     $app = JFactory::getApplication();
     $Itemid = JRequest::getInt('Itemid');
     $this->setCustomerFirstname($row->first_name);
     $this->setCustomerLastname($row->last_name);
     $this->setCustomerEmail($row->email);
     $this->setCustomerAddress($row->address);
     $this->setCustomerPostcode($row->zip);
     $this->setCustomerInvoiceDescription($data['item_name']);
     $this->setCustomerInvoiceRef($row->id);
     $this->setCardHoldersName($data['card_holder_name']);
     $this->setCardNumber($data['x_card_num']);
     $this->setCardExpiryMonth(str_pad($data['exp_month'], 2, '0', STR_PAD_LEFT));
     $this->setCardExpiryYear(substr($data['exp_year'], 2, 2));
     $this->setCardCVN($data['x_card_code']);
     $this->setTrxnNumber($row->transaction_id);
     $this->setTotalAmount($data['amount'] * 100);
     $xmlRequest = "<ewaygateway>" . "<ewayCustomerID>" . htmlentities($this->myCustomerID) . "</ewayCustomerID>" . "<ewayTotalAmount>" . htmlentities($this->myTotalAmount) . "</ewayTotalAmount>" . "<ewayCustomerFirstName>" . htmlentities($this->myCustomerFirstname) . "</ewayCustomerFirstName>" . "<ewayCustomerLastName>" . htmlentities($this->myCustomerLastname) . "</ewayCustomerLastName>" . "<ewayCustomerEmail>" . htmlentities($this->myCustomerEmail) . "</ewayCustomerEmail>" . "<ewayCustomerAddress>" . htmlentities($this->myCustomerAddress) . "</ewayCustomerAddress>" . "<ewayCustomerPostcode>" . htmlentities($this->myCustomerPostcode) . "</ewayCustomerPostcode>" . "<ewayCustomerInvoiceDescription>" . htmlentities($this->myCustomerInvoiceDescription) . "</ewayCustomerInvoiceDescription>" . "<ewayCustomerInvoiceRef>" . htmlentities($this->myCustomerInvoiceRef) . "</ewayCustomerInvoiceRef>" . "<ewayCardHoldersName>" . htmlentities($this->myCardName) . "</ewayCardHoldersName>" . "<ewayCardNumber>" . htmlentities($this->myCardNumber) . "</ewayCardNumber>" . "<ewayCardExpiryMonth>" . htmlentities($this->myCardExpiryMonth) . "</ewayCardExpiryMonth>" . "<ewayCardExpiryYear>" . htmlentities($this->myCardExpiryYear) . "</ewayCardExpiryYear>" . "<ewayTrxnNumber>" . htmlentities($this->myTrxnNumber) . "</ewayTrxnNumber>" . "<ewayOption1>" . htmlentities($this->myOption1) . "</ewayOption1>" . "<ewayOption2>" . htmlentities($this->myOption2) . "</ewayOption2>" . "<ewayOption3>" . htmlentities($this->myOption3) . "</ewayOption3>" . "<ewayCVN>" . htmlentities($this->myCardCVN) . "</ewayCVN>" . "</ewaygateway>";
     /* Use CURL to execute XML POST and write output into a string */
     $ch = curl_init($this->myGatewayURL);
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlRequest);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_TIMEOUT, 240);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
     $xmlResponse = curl_exec($ch);
     //exit;
     // Check whether the curl_exec worked.
     if (curl_errno($ch) == CURLE_OK) {
         // It worked, so setup an XML parser for the result.
         $this->parser = xml_parser_create();
         // Disable XML tag capitalisation (Case Folding)
         xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, FALSE);
         // Define Callback functions for XML Parsing
         xml_set_object($this->parser, $this);
         xml_set_element_handler($this->parser, "epXmlElementStart", "epXmlElementEnd");
         xml_set_character_data_handler($this->parser, "epXmlData");
         // Parse the XML response
         xml_parse($this->parser, $xmlResponse, TRUE);
         if (xml_get_error_code($this->parser) == XML_ERROR_NONE) {
             // Get the result into local variables.
             $this->myResultTrxnStatus = $this->xmlData['ewayTrxnStatus'];
             $this->myResultTrxnNumber = $this->xmlData['ewayTrxnNumber'];
             $this->myResultTrxnOption1 = $this->xmlData['ewayTrxnOption1'];
             $this->myResultTrxnOption2 = $this->xmlData['ewayTrxnOption2'];
             $this->myResultTrxnOption3 = $this->xmlData['ewayTrxnOption3'];
             $this->myResultTrxnReference = $this->xmlData['ewayTrxnReference'];
             $this->myResultAuthCode = $this->xmlData['ewayAuthCode'];
             $this->myResultReturnAmount = $this->xmlData['ewayReturnAmount'];
             $this->myResultTrxnError = $this->xmlData['ewayTrxnError'];
             $this->myError = 0;
             $this->myErrorMessage = '';
         } else {
             // An XML error occured. Return the error message and number.
             $this->myError = xml_get_error_code($this->parser) + EWAY_XML_ERROR_OFFSET;
             $this->myErrorMessage = xml_error_string($myError);
         }
         // Clean up our XML parser
         xml_parser_free($this->parser);
     } else {
         // A CURL Error occured. Return the error message and number. (offset so we can pick the error apart)
         $this->myError = curl_errno($ch) + EWAY_CURL_ERROR_OFFSET;
         $this->myErrorMessage = curl_error($ch);
     }
     // Clean up CURL, and return any error.
     curl_close($ch);
     $result = $this->getError();
     if ($result == EWAY_TRANSACTION_OK) {
         $config = OSMembershipHelper::getConfig();
         $row->transaction_id = $this->getTrxnNumber();
         $row->payment_date = date('Y-m-d H:i:s');
         $row->published = 1;
         $row->store();
         if ($row->act == 'upgrade') {
             OSMembershipHelper::processUpgradeMembership($row);
         }
         JPluginHelper::importPlugin('osmembership');
         $dispatcher = JDispatcher::getInstance();
         $dispatcher->trigger('onMembershipActive', array($row));
         OSMembershipHelper::sendEmails($row, $config);
         $db = JFactory::getDbo();
         $sql = 'SELECT subscription_complete_url FROM #__osmembership_plans WHERE id=' . $row->plan_id;
         $db->setQuery($sql);
         $subscriptionCompleteURL = $db->loadResult();
         if ($subscriptionCompleteURL) {
             $app->redirect($subscriptionCompleteURL);
         } else {
             $app->redirect(JRoute::_('index.php?option=com_osmembership&view=complete&act=' . $row->act . '&subscription_code=' . $row->subscription_code . '&Itemid=' . $Itemid, false, false));
         }
         return true;
     } else {
         $_SESSION['reason'] = $this->myResultTrxnError;
         $app->redirect(JRoute::_('index.php?option=com_osmembership&view=failure&id=' . $row->id . '&Itemid=' . $Itemid, false, false));
         return false;
     }
 }
Exemple #7
0
 /**
  * Process Subscription 
  *
  * @param array $data
  */
 function processSubscription($data)
 {
     jimport('joomla.user.helper');
     $db = JFactory::getDbo();
     $row = JTable::getInstance('OsMembership', 'Subscriber');
     $query = $db->getQuery(true);
     $config = OSMembershipHelper::getConfig();
     $user = JFactory::getUser();
     $userId = $user->get('id');
     $nullDate = $db->getNullDate();
     $fieldSuffix = OSMembershipHelper::getFieldSuffix();
     if (!$userId && $config->registration_integration) {
         //Store user account into Joomla users database
         if ($config->create_account_when_membership_active !== '1') {
             $userId = OSMembershipHelper::saveRegistration($data);
         } else {
             //Encrypt the password and store into  #__osmembership_subscribers table and create the account layout
             $privateKey = md5(JFactory::getConfig()->get('secret'));
             $key = new JCryptKey('simple', $privateKey, $privateKey);
             $crypt = new JCrypt(new JCryptCipherSimple(), $key);
             $data['user_password'] = $crypt->encrypt($data['password1']);
         }
     }
     $data['transaction_id'] = strtoupper(JUserHelper::genRandomPassword(16));
     $row->bind($data);
     $row->published = 0;
     $row->created_date = JFactory::getDate()->toSql();
     $row->user_id = $userId;
     while (true) {
         $subscriptionCode = JUserHelper::genRandomPassword(10);
         $query->select('COUNT(*)')->from('#__osmembership_subscribers')->where('subscription_code=' . $db->quote($subscriptionCode));
         $db->setQuery($query);
         $total = $db->loadResult();
         if (!$total) {
             break;
         }
     }
     $row->subscription_code = $subscriptionCode;
     $query->clear();
     $query->select('id')->from('#__osmembership_subscribers')->where("is_profile=1 AND ((user_id={$userId} AND user_id>0) OR email='{$row->email}')");
     $db->setQuery($query);
     $profileId = $db->loadResult();
     if ($profileId) {
         $row->is_profile = 0;
         $row->profile_id = $profileId;
     } else {
         $row->is_profile = 1;
     }
     $row->language = JFactory::getLanguage()->getTag();
     $query->clear();
     $query->select('*, title' . $fieldSuffix . ' AS title')->from('#__osmembership_plans')->where('id=' . (int) $data['plan_id']);
     $db->setQuery($query);
     $rowPlan = $db->loadObject();
     $rowFields = OSMembershipHelper::getProfileFields($row->plan_id, false);
     $form = new RADForm($rowFields);
     $form->setData($data)->bindData(true);
     $fees = OSMembershipHelper::calculateSubscriptionFee($rowPlan, $form, $data, $config, $row->payment_method);
     $action = $data['act'];
     if ($action == 'renew') {
         $renewOptionId = (int) $data['renew_option_id'];
         if ($renewOptionId == OSM_DEFAULT_RENEW_OPTION_ID) {
             $dateIntervalSpec = 'P' . $rowPlan->subscription_length . $rowPlan->subscription_length_unit;
         } else {
             $query->clear();
             $query->select('number_days')->from('#__osmembership_renewrates')->where('id=' . (int) $data['renew_option_id']);
             $db->setQuery($query);
             $numberDays = (int) $db->loadResult();
             $dateIntervalSpec = 'P' . $numberDays . 'D';
         }
     } elseif ($action == 'upgrade') {
         $dateIntervalSpec = 'P' . $rowPlan->subscription_length . $rowPlan->subscription_length_unit;
     } else {
         if ($rowPlan->recurring_subscription && $rowPlan->trial_duration) {
             $dateIntervalSpec = 'P' . $rowPlan->trial_duration . $rowPlan->trial_duration_unit;
         } else {
             $dateIntervalSpec = 'P' . $rowPlan->subscription_length . $rowPlan->subscription_length_unit;
         }
     }
     $maxDate = null;
     if ($row->user_id > 0) {
         //Subscriber, user existed
         $query->clear();
         $query->select('MAX(to_date)')->from('#__osmembership_subscribers')->where('user_id=' . $row->user_id . ' AND plan_id=' . $row->plan_id . ' AND (published=1 OR (published = 0 AND payment_method LIKE "os_offline%"))');
         $db->setQuery($query);
         $maxDate = $db->loadResult();
     }
     if ($maxDate) {
         $date = JFactory::getDate($maxDate);
         $row->from_date = $date->add(new DateInterval('P1D'))->toSql();
     } else {
         $date = JFactory::getDate();
         $row->from_date = $date->toSql();
     }
     if ($rowPlan->expired_date && $rowPlan->expired_date != $nullDate) {
         $expiredDate = JFactory::getDate($rowPlan->expired_date);
         $expiredDate->setTime(0, 0, 0);
         $startDate = clone $date;
         $startDate->setTime(0, 0, 0);
         if ($startDate >= $expiredDate) {
             $date->setDate($date->year + 1, $expiredDate->month, $expiredDate->day);
             $row->to_date = $date->toSql();
         } else {
             $row->to_date = $rowPlan->expired_date;
         }
     } else {
         if ($rowPlan->lifetime_membership) {
             $row->to_date = '2099-12-31 23:59:59';
         } else {
             $row->to_date = $date->add(new DateInterval($dateIntervalSpec))->toSql();
         }
     }
     $couponCode = JRequest::getVar('coupon_code', '');
     $couponId = 0;
     if ($couponCode && $fees['coupon_valid']) {
         $query->clear();
         $query->select('id')->from('#__osmembership_coupons')->where('code=' . $db->quote($couponCode));
         $db->setQuery($query);
         $couponId = (int) $db->loadResult();
         $query->clear();
         $query->update('#__osmembership_coupons')->set('used=used+1')->where('id=' . $couponId);
         $db->setQuery($query);
         $db->execute();
     }
     $row->amount = $fees['amount'];
     $row->discount_amount = $fees['discount_amount'];
     $row->tax_amount = $fees['tax_amount'];
     $row->payment_processing_fee = $fees['payment_processing_fee'];
     $row->coupon_id = $couponId;
     $row->gross_amount = $fees['gross_amount'];
     $row->store();
     if (!$row->profile_id) {
         $row->profile_id = $row->id;
         $row->store();
     }
     $data['amount'] = $fees['gross_amount'];
     //Store custom field data
     $form->storeData($row->id, $data);
     //Syncronize profile data for other records
     OSMembershipHelper::syncronizeProfileData($row, $data);
     JPluginHelper::importPlugin('osmembership');
     $dispatcher = JDispatcher::getInstance();
     $dispatcher->trigger('onAfterStoreSubscription', array($row));
     $data['regular_price'] = $fees['regular_gross_amount'];
     $data['trial_amount'] = $fees['trial_gross_amount'];
     if ($data['amount'] > 0 || $rowPlan->recurring_subscription) {
         switch ($action) {
             case 'renew':
                 $itemName = JText::_('OSM_PAYMENT_FOR_RENEW_SUBSCRIPTION');
                 $itemName = str_replace('[PLAN_TITLE]', $rowPlan->title, $itemName);
                 break;
             case 'upgrade':
                 $itemName = JText::_('OSM_PAYMENT_FOR_UPGRADE_SUBSCRIPTION');
                 $itemName = str_replace('[PLAN_TITLE]', $rowPlan->title, $itemName);
                 //Get from Plan Title
                 $query->clear();
                 $query->select('a.title')->from('#__osmembership_plans AS a')->innerJoin('#__osmembership_upgraderules AS b ON a.id=b.from_plan_id')->where('b.id=' . $row->upgrade_option_id);
                 $db->setQuery($query);
                 $fromPlanTitle = $db->loadResult();
                 $itemName = str_replace('[FROM_PLAN_TITLE]', $fromPlanTitle, $itemName);
                 break;
             default:
                 $itemName = JText::_('OSM_PAYMENT_FOR_SUBSCRIPTION');
                 $itemName = str_replace('[PLAN_TITLE]', $rowPlan->title, $itemName);
                 break;
         }
         $data['item_name'] = $itemName;
         $paymentMethod = $data['payment_method'];
         require_once JPATH_COMPONENT . '/plugins/' . $paymentMethod . '.php';
         $query->clear();
         $query->select('params, support_recurring_subscription')->from('#__osmembership_plugins')->where('name=' . $db->quote($paymentMethod));
         $db->setQuery($query);
         $plugin = $db->loadObject();
         $params = $plugin->params;
         $supportRecurring = $plugin->support_recurring_subscription;
         $params = new JRegistry($params);
         $paymentClass = new $paymentMethod($params);
         if ($rowPlan->recurring_subscription && $supportRecurring) {
             if ($paymentMethod == 'os_authnet') {
                 $paymentMethod = 'os_authnet_arb';
                 require_once JPATH_COMPONENT . '/plugins/' . $paymentMethod . '.php';
                 $paymentClass = new $paymentMethod($params);
             }
             $paymentClass->processRecurringPayment($row, $data);
         } else {
             $paymentClass->processPayment($row, $data);
         }
     } else {
         $Itemid = JRequest::getInt('Itemid');
         $row->published = 1;
         $row->store();
         if ($row->act == 'upgrade') {
             OSMembershipHelper::processUpgradeMembership($row);
         }
         OSMembershipHelper::sendEmails($row, $config);
         JPluginHelper::importPlugin('osmembership');
         $dispatcher = JDispatcher::getInstance();
         $dispatcher->trigger('onMembershipActive', array($row));
         $query->clear();
         $query->select('subscription_complete_url')->from('#__osmembership_plans')->where('id=' . $row->plan_id);
         //Get subscription complete UR
         $db->setQuery($query);
         $subscriptionCompleteURL = $db->loadResult();
         if ($subscriptionCompleteURL) {
             JFactory::getApplication()->redirect($subscriptionCompleteURL);
         } else {
             JFactory::getApplication()->redirect(JRoute::_('index.php?option=com_osmembership&view=complete&act=' . $row->act . '&subscription_code=' . $row->subscription_code . '&Itemid=' . $Itemid, false));
         }
     }
 }