public function __construct($config = array()) { parent::__construct($config); $this->app = JFactory::getApplication(); // Get project id. $this->projectId = $this->input->getUint('pid'); // Prepare log object $registry = Joomla\Registry\Registry::getInstance('com_crowdfunding'); /** @var $registry Joomla\Registry\Registry */ $fileName = $registry->get('logger.file'); $tableName = $registry->get('logger.table'); $file = JPath::clean($this->app->get('log_path') . DIRECTORY_SEPARATOR . $fileName); $this->log = new Prism\Log\Log(); $this->log->addAdapter(new Prism\Log\Adapter\Database(JFactory::getDbo(), $tableName)); $this->log->addAdapter(new Prism\Log\Adapter\File($file)); // Create an object that contains a data used during the payment process. $this->paymentProcessContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $this->projectId; $this->paymentProcess = $this->app->getUserState($this->paymentProcessContext); // Prepare context $filter = new JFilterInput(); $paymentService = JString::trim(JString::strtolower($this->input->getCmd('payment_service'))); $paymentService = $filter->clean($paymentService, 'ALNUM'); $this->context = JString::strlen($paymentService) > 0 ? 'com_crowdfunding.notify.' . $paymentService : 'com_crowdfunding.notify'; // Prepare params $this->params = JComponentHelper::getParams('com_crowdfunding'); }
protected function preparePayment(&$paymentSession) { // If missing the flag "step1", redirect to first step. if (!$paymentSession->step1) { $this->returnToStep1($paymentSession, JText::_("COM_CROWDFUNDING_ERROR_INVALID_AMOUNT")); } // Check for both user states. The user must have only one state - registered user or anonymous user. $userId = JFactory::getUser()->get("id"); $aUserId = $this->app->getUserState("auser_id"); if (!empty($userId) and !empty($aUserId) or empty($userId) and empty($aUserId)) { // Reset anonymous hash user ID and redirect to first step. $this->app->setUserState("auser_id", ""); $this->returnToStep1($paymentSession); } if (!$this->item->days_left) { $this->returnToStep1($paymentSession, JText::_("COM_CROWDFUNDING_ERROR_PROJECT_COMPLETED")); } // Validate reward $this->reward = null; $keys = array("id" => $paymentSession->rewardId, "project_id" => $this->item->id); $this->reward = new Crowdfunding\Reward(JFactory::getDbo()); $this->reward->load($keys); if ($this->reward->getId()) { if ($this->reward->isLimited() and !$this->reward->getAvailable()) { $this->returnToStep1($paymentSession, JText::_("COM_CROWDFUNDING_ERROR_REWARD_NOT_AVAILABLE")); } } // Set the amount that will be displayed in the view. $this->paymentAmount = $paymentSession->amount; // Validate the amount. if (!$this->paymentAmount) { $this->returnToStep1($paymentSession, JText::_("COM_CROWDFUNDING_ERROR_INVALID_AMOUNT")); } // Events $item = new stdClass(); $item->id = $this->item->id; $item->title = $this->item->title; $item->slug = $this->item->slug; $item->catslug = $this->item->catslug; $item->rewardId = $paymentSession->rewardId; $item->amount = $paymentSession->amount; $item->currencyCode = $this->currency->getCode(); $item->amountFormated = $this->amount->setValue($item->amount)->format(); $item->amountCurrency = $this->amount->setValue($item->amount)->formatCurrency(); $this->item->event = new stdClass(); // onBeforePaymentAuthorize JPluginHelper::importPlugin('crowdfundingpayment'); $dispatcher = JEventDispatcher::getInstance(); $results = $dispatcher->trigger('onBeforePaymentAuthorize', array('com_crowdfunding.before.payment.authorize', &$item, &$this->amount, &$this->params)); if (!empty($results)) { $this->item->event->onBeforePaymentAuthorize = trim(implode("\n", $results)); } else { // onProjectPayment $results = $dispatcher->trigger('onProjectPayment', array('com_crowdfunding.payment', &$item, &$this->params)); $this->item->event->onProjectPayment = trim(implode("\n", $results)); } }
/** * Check for duplication of session ID. * If the session ID exists, generate new one. * * @param object $item */ protected function prepareSessionId(&$item) { // Get the payment session object and session ID. $paymentSessionContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $item->id; $paymentSession = $this->app->getUserState($paymentSessionContext); $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select("COUNT(*)")->from($db->quoteName("#__cfdata_records", "a"))->where("a.session_id = " . $db->quote($paymentSession->session_id)); $db->setQuery($query, 0, 1); $result = $db->loadResult(); if (!empty($result)) { // Create payment session ID. $sessionId = new Prism\String(); $sessionId->generateRandomString(32); $paymentSession->session_id = (string) $sessionId; $this->app->setUserState($paymentSessionContext, $paymentSession); } }
/** * Disconnect user from payment gateway. * * @param string $context * @param Joomla\Registry\Registry $params * * @return null|array */ public function onPayoutsDeauthorize($context, $params) { if (strcmp('com_crowdfundingfinance.payouts.deauthorize.stripeconnect', $context) !== 0) { return null; } if ($this->app->isAdmin()) { return null; } $doc = JFactory::getDocument(); /** @var $doc JDocumentHtml */ // Check document type $docType = $doc->getType(); if (strcmp('html', $docType) !== 0) { return null; } // Prepare output data. $output = array('redirect_url' => '', 'message' => ''); $errorOutput = array('redirect_url' => JRoute::_(CrowdfundingHelperRoute::getDiscoverRoute()), 'message' => ''); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_GET_RESPONSE_AUTHORIZE'), $this->debugType, $_GET) : null; $userId = JFactory::getUser()->get('id'); if (!$userId) { $errorOutput['message'] = JText::_($this->textPrefix . '_ERROR_NOT_REGISTERED_USER'); return $errorOutput; } // Get token $state = $this->app->input->get('state'); if (!$state) { $errorOutput['message'] = JText::_($this->textPrefix . '_ERROR_INVALID_AUTHORIZATION_DATA'); return $errorOutput; } // Get project ID and redirect URL from the session. $stateData = $this->app->getUserState($state); if (count($stateData) === 0 or (!$stateData['redirect_url'] or !$stateData['project_id'])) { $errorOutput['message'] = JText::_($this->textPrefix . '_ERROR_INVALID_AUTHORIZATION_DATA'); return $errorOutput; } $cfFinanceParams = JComponentHelper::getParams('com_crowdfundingfinance'); $apiKeys = Crowdfundingfinance\Stripe\Helper::getKeys($cfFinanceParams); if (!$apiKeys['client_id'] or !$apiKeys['secret_key']) { $errorOutput['message'] = JText::_($this->textPrefix . '_ERROR_CONFIGURATION'); return $errorOutput; } $payout = new Crowdfundingfinance\Payout(JFactory::getDbo()); $payout->setSecretKey($this->app->get('secret')); $payout->load(array('project_id' => (int) $stateData['project_id'])); if (!$payout->getId()) { $errorOutput['message'] = JText::_($this->textPrefix . '_ERROR_INVALID_PAYOUT'); return $errorOutput; } $alias = !$apiKeys['test'] ? 'production' : 'test'; $stripeData = $payout->getStripe(); if (!$stripeData->get('stripeconnect.' . $alias . '.account_id')) { $errorOutput['message'] = JText::_($this->textPrefix . '_ERROR_NOT_CONNECTED'); return $errorOutput; } Crowdfundingfinance\Stripe\Helper::deauthorize($apiKeys, $stripeData->get('stripeconnect.' . $alias . '.account_id')); $stripeData->set('stripeconnect.' . $alias . '.access_token', ''); $stripeData->set('stripeconnect.' . $alias . '.refresh_token', ''); $stripeData->set('stripeconnect.' . $alias . '.account_id', ''); $stripeData->set('stripeconnect.' . $alias . '.expires', 0); $payout->setStripe($stripeData); $payout->storeStripe(); // Get next URL. $output['redirect_url'] = base64_decode($stateData['redirect_url']); return $output; }
protected function preparePayment(&$paymentSession) { // If missing the flag "step1", redirect to first step. if (!$paymentSession->step1) { $this->app->enqueueMessage(JText::_("COM_CROWDFUNDING_ERROR_INVALID_AMOUNT"), "notice"); $this->app->redirect(JRoute::_(CrowdFundingHelperRoute::getBackingRoute($this->item->slug, $this->item->catslug), false)); } // Check for both user states. The user must have only one state, registered or anonymous. $userId = JFactory::getUser()->get("id"); $aUserId = $this->app->getUserState("auser_id"); if (!empty($userId) and !empty($aUserId) or empty($userId) and empty($aUserId)) { // Reset anonymous hash user ID and redirect to first step. $this->app->setUserState("auser_id", ""); // Reset the flag for step 1 $paymentSession->step1 = false; $this->app->setUserState($this->paymentSessionContext, $paymentSession); $this->app->redirect(JRoute::_(CrowdFundingHelperRoute::getBackingRoute($this->item->slug, $this->item->catslug), false)); } if (!$this->item->days_left) { // Reset the flag for step 1 $paymentSession->step1 = false; $this->app->setUserState($this->paymentSessionContext, $paymentSession); $this->app->enqueueMessage(JText::_("COM_CROWDFUNDING_ERROR_PROJECT_COMPLETED"), "notice"); $this->app->redirect(JRoute::_(CrowdFundingHelperRoute::getBackingRoute($this->item->slug, $this->item->catslug), false)); } // Validate reward $this->reward = null; $keys = array("id" => $paymentSession->rewardId, "project_id" => $this->item->id); jimport("crowdfunding.reward"); $this->reward = new CrowdFundingReward(JFactory::getDbo()); $this->reward->load($keys); if ($this->reward->getId()) { if ($this->reward->isLimited() and !$this->reward->getAvailable()) { // Reset the flag for step 1 $paymentSession->step1 = false; $this->app->setUserState($this->paymentSessionContext, $paymentSession); $this->app->enqueueMessage(JText::_("COM_CROWDFUNDING_ERROR_REWARD_NOT_AVAILABLE"), "notice"); $this->app->redirect(JRoute::_(CrowdFundingHelperRoute::getBackingRoute($this->item->slug, $this->item->catslug), false)); } } // Validate amount $this->amount = $paymentSession->amount; if (!$this->amount) { // Reset the flag for step 1 $paymentSession->step1 = false; $this->app->setUserState($this->paymentSessionContext, $paymentSession); $this->app->enqueueMessage(JText::_("COM_CROWDFUNDING_ERROR_INVALID_AMOUNT"), "notice"); $this->app->redirect(JRoute::_(CrowdFundingHelperRoute::getBackingRoute($this->item->slug, $this->item->catslug), false)); } $item = new stdClass(); $item->id = $this->item->id; $item->title = $this->item->title; $item->slug = $this->item->slug; $item->catslug = $this->item->catslug; $item->rewardId = $paymentSession->rewardId; $item->amount = $paymentSession->amount; $item->currencyCode = $this->currency->getAbbr(); // Events JPluginHelper::importPlugin('crowdfundingpayment'); $dispatcher = JEventDispatcher::getInstance(); $results = $dispatcher->trigger('onProjectPayment', array('com_crowdfunding.payment', &$item, &$this->params)); $this->item->event = new stdClass(); $this->item->event->onProjectPayment = trim(implode("\n", $results)); }
/** * This method prepares a payment gateway - buttons, forms,... * That gateway will be displayed on the summary page as a payment option. * * @param string $context This string gives information about that where it has been executed the trigger. * @param object $item A project data. * @param Joomla\Registry\Registry $params The parameters of the component * * @return null|string */ public function onPaymentExtras($context, &$item, &$params) { if (strcmp("com_crowdfunding.payment.step2", $context) != 0) { return null; } if ($this->app->isAdmin()) { return null; } $doc = JFactory::getDocument(); /** @var $doc JDocumentHtml */ // Check document type $docType = $doc->getType(); if (strcmp("html", $docType) != 0) { return null; } // Get user ID. $userId = JFactory::getUser()->get("id"); // Display login form if (!$userId) { // Get the form. JForm::addFormPath(JPATH_COMPONENT . '/models/forms'); JForm::addFieldPath(JPATH_COMPONENT . '/models/fields'); $form = JForm::getInstance('com_users.login', 'login', array('load_data' => false), false, false); $this->loginForm = $form; $this->returnUrl = CrowdfundingHelperRoute::getBackingRoute($item->slug, $item->catslug); // Get the path for the layout file $path = JPluginHelper::getLayoutPath('crowdfundingpayment', 'login'); // Render the login form. ob_start(); include $path; $html = ob_get_clean(); } else { // Redirect to step "Payment". $componentParams = JComponentHelper::getParams("com_crowdfunding"); /** @var $componentParams Joomla\Registry\Registry */ // Get the payment process object and // store the selected data from the user. $paymentProcessContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $item->id; $paymentSession = $this->app->getUserState($paymentProcessContext); $this->rewardId = $paymentSession->rewardId; $this->amount = $paymentSession->amount; $this->terms = $paymentSession->terms; // Get the path for the layout file $path = JPluginHelper::getLayoutPath('crowdfundingpayment', 'login', 'redirect'); // Render the login form. ob_start(); include $path; $html = ob_get_clean(); // Include JavaScript code to redirect user to next step. $processUrl = JUri::base() . "index.php?option=com_crowdfunding&task=backing.process&id=" . (int) $item->id . "&rid=" . (int) $this->rewardId . "&amount=" . rawurldecode($this->amount) . "&" . JSession::getFormToken() . "=1"; // Set the value of terms of use condition. if ($componentParams->get("backing_terms", 0) and !empty($this->terms)) { $processUrl .= "&terms=1"; } $filter = JFilterInput::getInstance(); $processUrl = $filter->clean($processUrl); $js = ' jQuery(document).ready(function() { window.location.replace("' . $processUrl . '"); });'; $doc->addScriptDeclaration($js); } return $html; }
/** * This method prepares a payment gateway - buttons, forms,... * That gateway will be displayed on the summary page as a payment option. * * @param string $context This string gives information about that where it has been executed the trigger. * @param object $item A project data. * @param Joomla\Registry\Registry $params The parameters of the component * * @return string */ public function onProjectPayment($context, &$item, &$params) { if (strcmp("com_crowdfunding.payment", $context) != 0) { return null; } if ($this->app->isAdmin()) { return null; } $doc = JFactory::getDocument(); /** @var $doc JDocumentHtml */ // Check document type $docType = $doc->getType(); if (strcmp("html", $docType) != 0) { return null; } // This is a URI path to the plugin folder $pluginURI = "plugins/crowdfundingpayment/paypal"; $notifyUrl = $this->getCallbackUrl(); $returnUrl = $this->getReturnUrl($item->slug, $item->catslug); $cancelUrl = $this->getCancelUrl($item->slug, $item->catslug); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_NOTIFY_URL"), $this->debugType, $notifyUrl) : null; JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_RETURN_URL"), $this->debugType, $returnUrl) : null; JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_CANCEL_URL"), $this->debugType, $cancelUrl) : null; $html = array(); $html[] = '<div class="well">'; $html[] = '<h4><img src="' . $pluginURI . '/images/paypal_icon.png" width="36" height="32" alt="PayPal" />' . JText::_($this->textPrefix . "_TITLE") . '</h4>'; // Prepare payment receiver. $paymentReceiverOption = $this->params->get("paypal_payment_receiver", "site_owner"); $paymentReceiverInput = $this->preparePaymentReceiver($paymentReceiverOption, $item->id); if (is_null($paymentReceiverInput)) { $html[] = $this->generateSystemMessage(JText::_($this->textPrefix . "_ERROR_PAYMENT_RECEIVER_MISSING")); return implode("\n", $html); } // Display additional information. $html[] = '<p>' . JText::_($this->textPrefix . "_INFO") . '</p>'; // Start the form. if ($this->params->get('paypal_sandbox', 1)) { $html[] = '<form action="' . Joomla\String\String::trim($this->params->get('paypal_sandbox_url')) . '" method="post">'; } else { $html[] = '<form action="' . Joomla\String\String::trim($this->params->get('paypal_url')) . '" method="post">'; } $html[] = $paymentReceiverInput; $html[] = '<input type="hidden" name="cmd" value="_xclick" />'; $html[] = '<input type="hidden" name="charset" value="utf-8" />'; $html[] = '<input type="hidden" name="currency_code" value="' . $item->currencyCode . '" />'; $html[] = '<input type="hidden" name="amount" value="' . $item->amount . '" />'; $html[] = '<input type="hidden" name="quantity" value="1" />'; $html[] = '<input type="hidden" name="no_shipping" value="1" />'; $html[] = '<input type="hidden" name="no_note" value="1" />'; $html[] = '<input type="hidden" name="tax" value="0" />'; // Title $title = JText::sprintf($this->textPrefix . "_INVESTING_IN_S", htmlentities($item->title, ENT_QUOTES, "UTF-8")); $html[] = '<input type="hidden" name="item_name" value="' . $title . '" />'; // Get payment session $paymentSessionContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $item->id; $paymentSessionLocal = $this->app->getUserState($paymentSessionContext); $paymentSession = $this->getPaymentSession(array("session_id" => $paymentSessionLocal->session_id)); // Prepare custom data $custom = array("payment_session_id" => $paymentSession->getId(), "gateway" => "PayPal"); $custom = base64_encode(json_encode($custom)); $html[] = '<input type="hidden" name="custom" value="' . $custom . '" />'; // Set a link to logo $imageUrl = Joomla\String\String::trim($this->params->get('paypal_image_url')); if ($imageUrl) { $html[] = '<input type="hidden" name="image_url" value="' . $imageUrl . '" />'; } // Set URLs $html[] = '<input type="hidden" name="cancel_return" value="' . $cancelUrl . '" />'; $html[] = '<input type="hidden" name="return" value="' . $returnUrl . '" />'; $html[] = '<input type="hidden" name="notify_url" value="' . $notifyUrl . '" />'; $this->prepareLocale($html); // End the form. $html[] = '<img alt="" border="0" width="1" height="1" src="https://www.paypal.com/en_US/i/scr/pixel.gif" >'; $html[] = '</form>'; // Display a sticky note if the extension works in sandbox mode. if ($this->params->get('paypal_sandbox', 1)) { $html[] = '<div class="bg-info p-10-5"><span class="glyphicon glyphicon-info-sign"></span> ' . JText::_($this->textPrefix . "_WORKS_SANDBOX") . '</div>'; } $html[] = '</div>'; return implode("\n", $html); }
/** * @param JApplicationSite $app */ protected function prepareInformation($app) { if ($this->params->get("debug_payment_disabled", 0)) { $app->redirect(JRoute::_('index.php?option=com_virtualcurrency&view=payment', false)); } $paymentSessionData = $app->getUserState("payment.data"); $itemId = $paymentSessionData["item_id"]; $this->amount = $paymentSessionData["amount"]; jimport("virtualcurrency.currency"); $this->item = new VirtualCurrencyCurrency(JFactory::getDbo()); $this->item->load($itemId); // Calculate total amount that should be paid. jimport("itprism.math"); $total = new ITPrismMath(); $total->calculateTotal(array($this->amount, $this->item->getParam("amount"))); $this->total = (string) $total; // Get real currency $realCurrencyId = $this->params->get("payments_currency_id"); jimport("virtualcurrency.realcurrency"); $this->realCurrency = VirtualCurrencyRealCurrency::getInstance(JFactory::getDbo(), $realCurrencyId, $this->params); }
/** * Process payment transaction. * * @param string $context * @param object $item * @param Joomla\Registry\Registry $params * * @return null|array */ public function onPaymentsCheckout($context, &$item, &$params) { if (strcmp("com_crowdfunding.payments.checkout.paypal", $context) != 0) { return null; } if ($this->app->isAdmin()) { return null; } $doc = JFactory::getDocument(); /** @var $doc JDocumentHtml */ // Check document type $docType = $doc->getType(); if (strcmp("html", $docType) != 0) { return null; } $output = array(); $cancelUrl = $this->getCancelUrl($item->slug, $item->catslug); $returnUrl = $this->getDoCheckoutUrl($item->id); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_CANCEL_URL"), $this->debugType, $cancelUrl) : null; JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_RETURN_URL"), $this->debugType, $returnUrl) : null; // Get country and locale code. $countryId = $this->params->get("paypal_country"); $country = new Crowdfunding\Country(JFactory::getDbo()); $country->load($countryId); $localeCode = $country->getCode4(); // Create transport object. $options = new Joomla\Registry\Registry(); /** @var $options Joomla\Registry\Registry */ $transport = new JHttpTransportCurl($options); $http = new JHttp($options, $transport); // Create payment object. $options = new Joomla\Registry\Registry(); /** @var $options Joomla\Registry\Registry */ $options->set("urls.return", $returnUrl); $options->set("urls.cancel", $cancelUrl); $this->prepareCredentials($options); $options->set("locale.code", $localeCode); $options->set("style.logo_image", Joomla\String\String::trim($this->params->get("paypal_image_url"))); $options->set("payment.action", "Order"); $options->set("payment.amount", $item->amount); $options->set("payment.currency", $item->currencyCode); $title = JText::sprintf($this->textPrefix . "_INVESTING_IN_S", htmlentities($item->title, ENT_QUOTES, "UTF-8")); $options->set("payment.description", $title); // Get payment session. $paymentSessionContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $item->id; $paymentSessionLocal = $this->app->getUserState($paymentSessionContext); $paymentSession = $this->getPaymentSession(array("session_id" => $paymentSessionLocal->session_id)); // Prepare custom data $custom = array("payment_session_id" => $paymentSession->getId(), "gateway" => "PayPal"); $custom = base64_encode(json_encode($custom)); $options->set("payment.custom", $custom); // Get API url. $apiUrl = $this->getApiUrl(); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_EXPRESS_CHECKOUT_OPTIONS"), $this->debugType, $options->toArray()) : null; $express = new Prism\Payment\PayPal\Express($apiUrl, $options); $express->setTransport($http); $response = $express->setExpressCheckout(); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_EXPRESS_CHECKOUT_RESPONSE"), $this->debugType, $response) : null; $token = Joomla\Utilities\ArrayHelper::getValue($response, "TOKEN"); if (!$token) { return null; } // Store token to the payment session. $paymentSession->setUniqueKey($token); $paymentSession->storeUniqueKey(); // Get PayPal checkout URL. if ($this->params->get('paypal_sandbox', 1)) { $output["redirect_url"] = $this->params->get("paypal_sandbox_url", "https://www.sandbox.paypal.com/cgi-bin/webscr") . "?cmd=_express-checkout&useraction=commit&token=" . rawurlencode($token); } else { $output["redirect_url"] = $this->params->get("paypal_url", "https://www.paypal.com/cgi-bin/webscr") . "?cmd=_express-checkout&useraction=commit&token=" . rawurlencode($token); } return $output; }
/** * Process payment transaction. * * @param string $context * @param object $item * @param Joomla\Registry\Registry $params * * @return null|array */ public function onPaymentsCheckout($context, &$item, &$params) { if (strcmp("com_crowdfunding.payments.checkout.paypal", $context) != 0) { return null; } if ($this->app->isAdmin()) { return null; } $doc = JFactory::getDocument(); /** @var $doc JDocumentHtml */ // Check document type $docType = $doc->getType(); if (strcmp("html", $docType) != 0) { return null; } $output = array(); $notifyUrl = $this->getCallbackUrl(); $cancelUrl = $this->getCancelUrl($item->slug, $item->catslug); $returnUrl = $this->getReturnUrl($item->slug, $item->catslug); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_NOTIFY_URL"), $this->debugType, $notifyUrl) : null; JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_RETURN_URL"), $this->debugType, $returnUrl) : null; JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_CANCEL_URL"), $this->debugType, $cancelUrl) : null; // Get country and locale code. $countryId = $this->params->get("paypal_country"); $country = new Crowdfunding\Country(JFactory::getDbo()); $country->load($countryId); // Create transport object. $options = new Joomla\Registry\Registry(); /** @var $options Joomla\Registry\Registry */ $transport = new JHttpTransportCurl($options); $http = new JHttp($options, $transport); // Create payment object. $options = new Joomla\Registry\Registry(); /** @var $options Joomla\Registry\Registry */ $options->set("urls.cancel", $cancelUrl); $options->set("urls.return", $returnUrl); $options->set("urls.notify", $notifyUrl); $this->prepareCredentials($options); // Get server IP address. /*$serverIP = $this->app->input->server->get("SERVER_ADDR"); $options->set("credentials.ip_address", $serverIP);*/ // Prepare starting and ending date. if (!$this->params->get("paypal_starting_date", 0)) { // End date of the campaign. $startingDate = new JDate(); // Today $startingDate->setTime(0, 0, 0); // At 00:00:00 } else { $startingDate = new JDate($item->ending_date); $startingDate->modify("+1 day"); $startingDate->setTime(0, 0, 0); // At 00:00:00 } $endingDate = new JDate($item->ending_date); $endingDate->modify("+10 days"); $options->set("payment.starting_date", $startingDate->format(DATE_ATOM)); $options->set("payment.ending_date", $endingDate->format(DATE_ATOM)); $options->set("payment.max_amount", $item->amount); $options->set("payment.max_total_amount", $item->amount); $options->set("payment.number_of_payments", 1); $options->set("payment.currency_code", $item->currencyCode); $options->set("payment.fees_payer", $this->params->get("paypal_fees_payer")); $options->set("payment.ping_type", "NOT_REQUIRED"); $title = JText::sprintf($this->textPrefix . "_INVESTING_IN_S", htmlentities($item->title, ENT_QUOTES, "UTF-8")); $options->set("payment.memo", $title); $options->set("request.envelope", $this->envelope); // Get payment session. $paymentSessionContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $item->id; $paymentSessionLocal = $this->app->getUserState($paymentSessionContext); $paymentSession = $this->getPaymentSession(array("session_id" => $paymentSessionLocal->session_id)); // Get API url. $apiUrl = $this->getApiUrl(); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_PAYPAL_ADAPTIVE_OPTIONS"), $this->debugType, $options->toArray()) : null; $adaptive = new Prism\Payment\PayPal\Adaptive($apiUrl, $options); $adaptive->setTransport($http); $response = $adaptive->doPreppproval(); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_PAYPAL_ADAPTIVE_RESPONSE"), $this->debugType, $response) : null; $preapprovalKey = $response->getPreApprovalKey(); if (!$preapprovalKey) { return null; } // Store token to the payment session. $paymentSession->setUniqueKey($preapprovalKey); $paymentSession->storeUniqueKey(); // Get paypal checkout URL. if (!$this->params->get('paypal_sandbox', 1)) { $output["redirect_url"] = $this->params->get("paypal_url") . "?cmd=_ap-preapproval&preapprovalkey=" . rawurlencode($preapprovalKey); } else { $output["redirect_url"] = $this->params->get("paypal_sandbox_url") . "?cmd=_ap-preapproval&preapprovalkey=" . rawurlencode($preapprovalKey); } return $output; }
/** * This method performs the transaction. * * @param string $context * @param Joomla\Registry\Registry $params * * @return null|array */ public function onPaymentNotify($context, &$params) { if (strcmp("com_crowdfunding.notify.banktransfer", $context) != 0) { return null; } if ($this->app->isAdmin()) { return null; } $doc = JFactory::getDocument(); /** @var $doc JDocumentHtml */ // Check document type $docType = $doc->getType(); if (strcmp("raw", $docType) != 0) { return null; } $projectId = $this->app->input->getInt("pid"); $amount = $this->app->input->getFloat("amount"); // Prepare the array that will be returned by this method $result = array("project" => null, "reward" => null, "transaction" => null, "payment_session" => null, "redirect_url" => null, "message" => null); // Get project $project = new Crowdfunding\Project(JFactory::getDbo()); $project->load($projectId); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_PROJECT_OBJECT"), $this->debugType, $project->getProperties()) : null; // Check for valid project if (!$project->getId()) { // Log data in the database $this->log->add(JText::_($this->textPrefix . "_ERROR_INVALID_PROJECT"), $this->debugType, array("PROJECT OBJECT" => $project->getProperties(), "REQUEST METHOD" => $this->app->input->getMethod(), "_REQUEST" => $_REQUEST)); return null; } $currencyId = $params->get("project_currency"); $currency = Crowdfunding\Currency::getInstance(JFactory::getDbo(), $currencyId, $params); // Prepare return URL $result["redirect_url"] = Joomla\String\String::trim($this->params->get('return_url')); if (!$result["redirect_url"]) { $filter = JFilterInput::getInstance(); $uri = JUri::getInstance(); $domain = $filter->clean($uri->toString(array("scheme", "host"))); $result["redirect_url"] = $domain . JRoute::_(CrowdfundingHelperRoute::getBackingRoute($project->getSlug(), $project->getCatslug(), "share"), false); } // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_RETURN_URL"), $this->debugType, $result["redirect_url"]) : null; // Payment Session $userId = JFactory::getUser()->get("id"); $aUserId = $this->app->getUserState("auser_id"); // Reset anonymous user hash ID, // because the payment session based in it will be removed when transaction completes. if (!empty($aUserId)) { $this->app->setUserState("auser_id", ""); } $paymentSessionContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $project->getId(); $paymentSessionLocal = $this->app->getUserState($paymentSessionContext); $paymentSession = $this->getPaymentSession(array("session_id" => $paymentSessionLocal->session_id)); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_PAYMENT_SESSION_OBJECT"), $this->debugType, $paymentSession->getProperties()) : null; // Validate payment session record. if (!$paymentSession->getId()) { // Log data in the database $this->log->add(JText::_($this->textPrefix . "_ERROR_INVALID_PAYMENT_SESSION"), $this->debugType, $paymentSession->getProperties()); // Send response to the browser $response = array("success" => false, "title" => JText::_($this->textPrefix . "_FAIL"), "text" => JText::_($this->textPrefix . "_ERROR_INVALID_PROJECT")); return $response; } // Validate a reward and update the number of distributed ones. // If the user is anonymous, the system will store 0 for reward ID. // The anonymous users can't select rewards. $rewardId = $paymentSession->isAnonymous() ? 0 : (int) $paymentSession->getRewardId(); if (!empty($rewardId)) { $validData = array("reward_id" => $rewardId, "project_id" => $projectId, "txn_amount" => $amount); $reward = $this->updateReward($validData); // Validate the reward. if (!$reward) { $rewardId = 0; } } // Prepare transaction data $transactionId = new Prism\String(); $transactionId->generateRandomString(12, "BT"); $transactionId = Joomla\String\String::strtoupper($transactionId); $transactionData = array("txn_amount" => $amount, "txn_currency" => $currency->getCode(), "txn_status" => "pending", "txn_id" => $transactionId, "project_id" => $projectId, "reward_id" => $rewardId, "investor_id" => (int) $userId, "receiver_id" => (int) $project->getUserId(), "service_provider" => "Bank Transfer"); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_TRANSACTION_DATA"), $this->debugType, $transactionData) : null; // Auto complete transaction if ($this->params->get("auto_complete", 0)) { $transactionData["txn_status"] = "completed"; $project->addFunds($amount); $project->storeFunds(); } // Store transaction data $transaction = new Crowdfunding\Transaction(JFactory::getDbo()); $transaction->bind($transactionData); $transaction->store(); // Generate object of data, based on the transaction properties. $properties = $transaction->getProperties(); $result["transaction"] = Joomla\Utilities\ArrayHelper::toObject($properties); // Generate object of data, based on the project properties. $properties = $project->getProperties(); $result["project"] = Joomla\Utilities\ArrayHelper::toObject($properties); // Generate object of data, based on the reward properties. if (!empty($reward)) { $properties = $reward->getProperties(); $result["reward"] = Joomla\Utilities\ArrayHelper::toObject($properties); } // Generate data object, based on the payment session properties. $properties = $paymentSession->getProperties(); $result["payment_session"] = Joomla\Utilities\ArrayHelper::toObject($properties); // Set message to the user. $result["message"] = JText::sprintf($this->textPrefix . "_TRANSACTION_REGISTERED", $transaction->getTransactionId(), $transaction->getTransactionId()); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_RESULT_DATA"), $this->debugType, $result) : null; // Close payment session and remove payment session record. $txnStatus = isset($result["transaction"]->txn_status) ? $result["transaction"]->txn_status : null; $this->closePaymentSession($paymentSession, $txnStatus); return $result; }