• Main Page
  • Modules
  • Classes
  • Files
  • File List

plugins/paymethod/paypal/PayPalPlugin.inc.php

00001 <?php
00002 
00015 import('classes.plugins.PaymethodPlugin');
00016 
00017 class PayPalPlugin extends PaymethodPlugin {
00021    function PayPalPlugin() {
00022       parent::PaymethodPlugin();
00023    }
00024 
00029    function getName() {
00030       return 'Paypal';
00031    }
00032 
00037    function getDisplayName() {
00038       return __('plugins.paymethod.paypal.displayName');
00039    }
00040 
00045    function getDescription() {
00046       return __('plugins.paymethod.paypal.description');
00047    }   
00048 
00053    function register($category, $path) {
00054       if (parent::register($category, $path)) {
00055          if (!Config::getVar('general', 'installed') || defined('RUNNING_UPGRADE')) return true;
00056          $this->addLocaleData();
00057          $this->import('PayPalDAO');
00058          $payPalDao = new PayPalDAO();
00059          DAORegistry::registerDAO('PayPalDAO', $payPalDao);
00060          return true;
00061       }
00062       return false;
00063    }
00064 
00069    function getSettingsFormFieldNames() {
00070       return array('paypalurl', 'selleraccount');
00071    }
00072 
00077    function isCurlInstalled() {
00078       return (function_exists('curl_init'));
00079    }
00080 
00085    function isConfigured() {
00086       $press =& Request::getPress();
00087       if (!$press) return false;
00088 
00089       // Make sure CURL support is included.
00090       if (!$this->isCurlInstalled()) return false;
00091 
00092       // Make sure that all settings form fields have been filled in
00093       foreach ($this->getSettingsFormFieldNames() as $settingName) {
00094          $setting = $this->getSetting($press->getId(), $settingName);
00095          if (empty($setting)) return false;
00096       }
00097       return true;
00098    }
00099 
00105    function displayPaymentSettingsForm(&$params, &$smarty) {
00106       $smarty->assign('isCurlInstalled', $this->isCurlInstalled());
00107       return parent::displayPaymentSettingsForm($params, $smarty);
00108    }
00109 
00116    function displayPaymentForm($queuedPaymentId, &$queuedPayment, &$request) {
00117       if (!$this->isConfigured()) return false;
00118       $press =& $request->getPress();
00119       $user =& $request->getUser();
00120 
00121       $params = array(
00122          'charset' => Config::getVar('i18n', 'client_charset'),
00123          'business' => $this->getSetting($press->getId(), 'selleraccount'),
00124          'item_name' => $queuedPayment->getName(),
00125          'item_description' => $queuedPayment->getDescription(),  // not a paypal parameter (PayPal uses item_name)
00126          'amount' => sprintf('%.2F', $queuedPayment->getAmount()),
00127          'quantity' => 1,
00128          'no_note' => 1,
00129          'no_shipping' => 1,
00130          'currency_code' => $queuedPayment->getCurrencyCode(),
00131          'lc' => String::substr(AppLocale::getLocale(), 3), 
00132          'custom' => $queuedPaymentId,
00133          'notify_url' => $request->url(null, 'payment', 'plugin', array($this->getName(), 'ipn')),  
00134          'return' => $queuedPayment->getRequestUrl(),
00135          'cancel_return' => $request->url(null, 'payment', 'plugin', array($this->getName(), 'cancel')),
00136          'first_name' => ($user)?$user->getFirstName():'',  
00137          'last_name' => ($user)?$user->getLastname():'',
00138          'item_number' => $queuedPayment->getAssocId(),
00139          'cmd' => '_xclick'
00140       );
00141 
00142       AppLocale::requireComponents(LOCALE_COMPONENT_APPLICATION_COMMON);
00143       $templateMgr =& TemplateManager::getManager();
00144       $templateMgr->assign('params', $params);
00145       $templateMgr->assign('paypalFormUrl', $this->getSetting($press->getId(), 'paypalurl'));
00146       $templateMgr->display($this->getTemplatePath() . 'paymentForm.tpl');
00147    }
00148 
00154    function handle($args, &$request) {
00155       $templateMgr =& TemplateManager::getManager();
00156       $press =& $request->getPress();
00157       if (!$press) return parent::handle($args, $request);
00158 
00159       // Just in case we need to contact someone
00160       import('classes.mail.MailTemplate');
00161       // Prefer technical support contact
00162       $contactName = $press->getSetting('supportName');
00163       $contactEmail = $press->getSetting('supportEmail');
00164       if (!$contactEmail) { // Fall back on primary contact
00165          $contactName = $press->getSetting('contactName');
00166          $contactEmail = $press->getSetting('contactEmail');
00167       }
00168       $mail = new MailTemplate('PAYPAL_INVESTIGATE_PAYMENT');
00169       $mail->setFrom($contactEmail, $contactName);
00170       $mail->addRecipient($contactEmail, $contactName);
00171 
00172       $paymentStatus = $request->getUserVar('payment_status');
00173 
00174       switch (array_shift($args)) {
00175          case 'ipn':
00176             // Build a confirmation transaction.
00177             $req = 'cmd=_notify-validate';
00178             if (get_magic_quotes_gpc()) {
00179                foreach ($_POST as $key => $value) $req .= '&' . urlencode(stripslashes($key)) . '=' . urlencode(stripslashes($value));
00180             } else {
00181                foreach ($_POST as $key => $value) $req .= '&' . urlencode($key) . '=' . urlencode($value);  
00182             }
00183             // Create POST response
00184             $ch = curl_init();
00185             curl_setopt($ch, CURLOPT_URL, $this->getSetting($press->getId(), 'paypalurl'));
00186             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
00187             curl_setopt($ch, CURLOPT_POST, 1);
00188             curl_setopt($ch, CURLOPT_HTTPHEADER, Array('Content-Type: application/x-www-form-urlencoded', 'Content-Length: ' . strlen($req)));
00189             curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
00190             $ret = curl_exec ($ch);
00191             curl_close ($ch);
00192 
00193             // Check the confirmation response and handle as necessary.
00194             if (strcmp($ret, 'VERIFIED') == 0) switch ($paymentStatus) {
00195                case 'Completed':
00196                   $payPalDao =& DAORegistry::getDAO('PayPalDAO');
00197                   $transactionId = $request->getUserVar('txn_id');
00198                   if ($payPalDao->transactionExists($transactionId)) {
00199                      // A duplicate transaction was received; notify someone.
00200                      $mail->assignParams(array(
00201                         'pressName' => $press->getLocalizedTitle(),
00202                         'postInfo' => print_r($_POST, true),
00203                         'additionalInfo' => "Duplicate transaction ID: $transactionId",
00204                         'serverVars' => print_r($_SERVER, true)
00205                      ));
00206                      $mail->send();
00207                      exit();
00208                   } else {
00209                      // New transaction succeeded. Record it.
00210                      $payPalDao->insertTransaction(
00211                         $transactionId,
00212                         $request->getUserVar('txn_type'),
00213                         $request->getUserVar('payer_email'),
00214                         $request->getUserVar('receiver_email'),
00215                         $request->getUserVar('item_number'),
00216                         $request->getUserVar('payment_date'),
00217                         $request->getUserVar('payer_id'),
00218                         $request->getUserVar('receiver_id')
00219                      );
00220                      $queuedPaymentId = $request->getUserVar('custom');
00221 
00222                      import('classes.payment.omp.OMPPaymentManager');
00223                      $ompPaymentManager = new OMPPaymentManager($request);
00224 
00225                      // Verify the cost and user details as per PayPal spec.
00226                      $queuedPayment =& $ompPaymentManager->getQueuedPayment($queuedPaymentId);
00227                      if (!$queuedPayment) {
00228                         // The queued payment entry is missing. Complain.
00229                         $mail->assignParams(array(
00230                            'pressName' => $press->getLocalizedName(),
00231                            'postInfo' => print_r($_POST, true),
00232                            'additionalInfo' => "Missing queued payment ID: $queuedPaymentId",
00233                            'serverVars' => print_r($_SERVER, true)
00234                         ));
00235                         $mail->send();
00236                         exit();
00237                      }
00238 
00239                      //NB: if/when paypal subscriptions are enabled, these checks will have to be adjusted
00240                      // because subscription prices may change over time
00241                      if (
00242                         (($queuedAmount = $queuedPayment->getAmount()) != ($grantedAmount = $request->getUserVar('mc_gross')) && $queuedAmount > 0) ||
00243                         ($queuedCurrency = $queuedPayment->getCurrencyCode()) != ($grantedCurrency = $request->getUserVar('mc_currency')) ||
00244                         ($grantedEmail = $request->getUserVar('receiver_email')) != ($queuedEmail = $this->getSetting($press->getId(), 'selleraccount'))
00245                      ) {
00246                         // The integrity checks for the transaction failed. Complain.
00247                         $mail->assignParams(array(
00248                            'pressName' => $press->getLocalizedTitle(),
00249                            'postInfo' => print_r($_POST, true),
00250                            'additionalInfo' =>
00251                               "Granted amount: $grantedAmount\n" .
00252                               "Queued amount: $queuedAmount\n" .
00253                               "Granted currency: $grantedCurrency\n" .
00254                               "Queued currency: $queuedCurrency\n" .
00255                               "Granted to PayPal account: $grantedEmail\n" .
00256                               "Configured PayPal account: $queuedEmail",
00257                            'serverVars' => print_r($_SERVER, true)
00258                         ));
00259                         $mail->send();
00260                         exit();
00261                      }
00262 
00263                      // Update queued amount if amount set by user (e.g. donation)
00264                      if ($queuedAmount == 0 && $grantedAmount > 0) {
00265                         $queuedPaymentDao =& DAORegistry::getDAO('QueuedPaymentDAO');
00266                         $queuedPayment->setAmount($grantedAmount);
00267                         $queuedPayment->setCurrencyCode($grantedCurrency);
00268                         $queuedPaymentDao->updateQueuedPayment($queuedPaymentId, $queuedPayment);
00269                      }
00270 
00271                      // Fulfill the queued payment.
00272                      if ($ompPaymentManager->fulfillQueuedPayment($queuedPayment, $this->getName())) exit();
00273                      
00274                      // If we're still here, it means the payment couldn't be fulfilled.
00275                      $mail->assignParams(array(
00276                         'pressName' => $press->getLocalizedTitle(),
00277                         'postInfo' => print_r($_POST, true),
00278                         'additionalInfo' => "Queued payment ID $queuedPaymentId could not be fulfilled.",
00279                         'serverVars' => print_r($_SERVER, true)
00280                      ));
00281                      $mail->send();
00282                   }
00283                   exit();
00284                case 'Pending':
00285                   // Ignore.
00286                   exit();
00287                default:
00288                   // An unhandled payment status was received; notify someone.
00289                   $mail->assignParams(array(
00290                      'pressName' => $press->getLocalizedTitle(),
00291                      'postInfo' => print_r($_POST, true),
00292                      'additionalInfo' => "Payment status: $paymentStatus",
00293                      'serverVars' => print_r($_SERVER, true)
00294                   ));
00295                   $mail->send();
00296                   exit();
00297             } else {
00298                // An unknown confirmation response was received; notify someone.
00299                $mail->assignParams(array(
00300                   'pressName' => $press->getLocalizedTitle(),
00301                   'postInfo' => print_r($_POST, true),
00302                   'additionalInfo' => "Confirmation return: $ret",
00303                   'serverVars' => print_r($_SERVER, true)
00304                ));
00305                $mail->send();
00306                exit();
00307             }
00308 
00309             break;
00310          case 'cancel':
00311             Handler::setupTemplate();
00312             $templateMgr->assign(array(
00313                'currentUrl' => $request->url(null, 'index'),
00314                'pageTitle' => 'plugins.paymethod.paypal.purchase.cancelled.title',
00315                'message' => 'plugins.paymethod.paypal.purchase.cancelled',
00316                'backLink' => $request->getUserVar('ompReturnUrl'),
00317                'backLinkLabel' => 'common.continue'
00318             ));
00319             $templateMgr->display('common/message.tpl');
00320             exit();
00321             break;
00322       }
00323       parent::handle($args); // Don't know what to do with it
00324    }
00325 
00329    function getInstallSchemaFile() {
00330       return ($this->getPluginPath() . DIRECTORY_SEPARATOR . 'schema.xml');
00331    }
00332 
00336    function getInstallEmailTemplatesFile() {
00337       return ($this->getPluginPath() . DIRECTORY_SEPARATOR . 'emailTemplates.xml');
00338    }
00339 
00343    function getInstallEmailTemplateDataFile() {
00344       return ($this->getPluginPath() . '/locale/{$installedLocale}/emailTemplates.xml');
00345    }
00346 }
00347 
00348 ?>

Generated on Mon Sep 17 2012 13:58:56 for Open Monograph Press by  doxygen 1.7.1