Second step of ExpressCheckout. Display an order confirmation form which
        contains hidden fields with the token / PayerID from PayPal.
423935
def render_confirm_form(self):
        
        warn_untested()
        initial = dict(token=self.request.GET['token'], PayerID=self.request.GET['PayerID'])
        self.context[self.form_context_name] = self.confirm_form_cls(initial=initial)
        return TemplateResponse(self.request, self.confirm_template, self.context)
138968
function DoExpressCheckoutPayment($token, $payerId, $options = array()) {
    $values = array_merge($options, array('TOKEN'   => $token,
                                          'PAYERID' => $payerId));
    if (PAYPAL_DEV_MODE == 'true') $this->log('DoExpressCheckout - breakpoint 1 - ['.$token  . ' ' . $payerId . ' ' . "]\n\n[" . print_r($values, true) .']', $token);

    if ($this->_mode == 'payflow') {
      $values['ACTION'] = 'D'; /* ACTION=D denotes DoExpressCheckoutPayment via Payflow */
      $values['TENDER'] = 'P';
      $values['TRXTYPE'] = $this->_trxtype;
      $values['NOTIFYURL'] = zen_href_link('ipn_main_handler.php', '', 'SSL',false,false,true);
    } elseif ($this->_mode == 'nvp') {
      if (!isset($values['PAYMENTACTION']) || $this->checkHasApiCredentials() === FALSE) $values['PAYMENTACTION'] = ($this->_trxtype == 'S' || ($this->checkHasApiCredentials() === FALSE) ? 'Sale' : 'Authorization');
      $values['NOTIFYURL'] = urlencode(zen_href_link('ipn_main_handler.php', '', 'SSL',false,false,true));
    }
    $this->values = $values;
    $this->notify('NOTIFY_PAYPAL_DOEXPRESSCHECKOUTPAYMENT');
    if (PAYPAL_DEV_MODE == 'true') $this->log('DoExpressCheckout - breakpoint 2 '.print_r($this->values, true), $token);
    return $this->_request($this->values, 'DoExpressCheckoutPayment');
  }
465210
public function confirmPayment($orderId)
    {
        try {
            $orderId = \intval($orderId);

            if (null !== $order = $this->getOrder($orderId)) {
                $this->getLog()->addInfo(
                    $this->getTranslator()->trans(
                        "Processing confirmation of order ref. %ref, ID %id",
                        array('%ref' => $order->getRef(), '%id' => $order->getId())
                    )
                );

                $event = new OrderEvent($order);

                $event->setStatus(OrderStatusQuery::getPaidStatus()->getId());

                $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event);

                $this->getLog()->addInfo(
                    $this->getTranslator()->trans(
                        "Order ref. %ref, ID %id has been successfully paid.",
                        array('%ref' => $order->getRef(), '%id' => $order->getId())
                    )
                );
            }
        } catch (\Exception $ex) {
            $this->getLog()->addError(
                $this->getTranslator()->trans(
                    "Error occured while processing order ref. %ref, ID %id: %err",
                    array(
                        '%err' => $ex->getMessage(),
                        '%ref' => !isset($order) ? "?" : $order->getRef(),
                        '%id' => !isset($order) ? "?" : $order->getId()
                    )
                )
            );

            throw $ex;
        }
    }
238820
function moneyorder() {
      global $order;

      $this->code = 'moneyorder';
      $this->title = MODULE_PAYMENT_MONEYORDER_TEXT_TITLE;
      if (IS_ADMIN_FLAG === true && (MODULE_PAYMENT_MONEYORDER_PAYTO == 'the Store Owner/Website Name' || MODULE_PAYMENT_MONEYORDER_PAYTO == '')) $this->title .= '<span class="alert"> (not configured - needs pay-to)</span>';
      $this->description = MODULE_PAYMENT_MONEYORDER_TEXT_DESCRIPTION;
      $this->sort_order = MODULE_PAYMENT_MONEYORDER_SORT_ORDER;
      $this->enabled = ((MODULE_PAYMENT_MONEYORDER_STATUS == 'True') ? true : false);

      if ((int)MODULE_PAYMENT_MONEYORDER_ORDER_STATUS_ID > 0) {
        $this->order_status = MODULE_PAYMENT_MONEYORDER_ORDER_STATUS_ID;
      }

      if (is_object($order)) $this->update_status();

      $this->email_footer = MODULE_PAYMENT_MONEYORDER_TEXT_EMAIL_FOOTER;
    }
945077
function alterShippingEditButton() {
    return false;
    if ($this->in_special_checkout() && empty($_SESSION['paypal_ec_markflow'])) {
      return zen_href_link('ipn_main_handler.php', 'type=ec&clearSess=1', 'SSL', true,true, true);
    }
  }
312810
async def mailed_confirm(self, **params):
		
		if not params:
			return {"error":400, "reason":"Missed required fields"}

		# Check if required fields exists
		cid = params.get("cid")
		buyer_address = params.get("buyer_address")
		price = params.get("price")
		offer_type = params.get("offer_type")
		coinid = params.get("coinid").upper()
		try:
			coinid = coinid.replace("TEST", "")
		except:
			pass
		# Check if required fileds 
		if not all([cid, buyer_address, price]):
			return {"error":400, "reason":"Missed required fields"}




		# Get content owner address
		#if coinid in settings.AVAILABLE_COIN_ID:
		#	client_bridge.endpoint = settings.bridges[coinid]
		#else:
		#	return {"error":400, "reason":"Invalid coin ID"}
		#owneraddr = await client_bridge.request(method_name="ownerbycid", cid=cid)


		# Send appropriate mail to seller if exists
		#seller = await getaccountbywallet(wallet=owneraddr)
		#logging.debug(seller)
		#if "error" in seller.keys():
		#	return seller
		#if seller.get("email"):
		#	emaildata = {
		#		"to": seller["email"],
		#		"subject": "Robin8 support",
	 	#		"optional": "You`ve got a new offer from %s" % seller["public_key"]
	 	#
		#	}
		#	await client_email.request(method_name="sendmail", **emaildata)

		# Send news for seller
		buyer = await getaccountbywallet(wallet=buyer_address) 
		if "error" in buyer.keys():
			buyer["public_key"] = None

		newsdata = {
			"event_type":"made offer",
			"cid": cid,
			"access_string":buyer["public_key"],
			"buyer_pubkey":buyer["public_key"],
			"buyer_address":buyer_address,
			#"owneraddr":owneraddr,
			"price": price,
			"offer_type": offer_type,
			"coinid":coinid
		}
		news = await self.insert_news(**newsdata)
		return {"result":"ok"}
1223706
def confirm_paid(self, purchase_order_id, session, confirm_remark=None):
        ''''''
        request = TOPRequest('taobao.fenxiao.order.confirm.paid')
        request['purchase_order_id'] = purchase_order_id
        if confirm_remark!=None: request['confirm_remark'] = confirm_remark
        self.create(self.execute(request, session))
        return self.is_success
883534
function ec_step1() {
    global $order, $order_totals, $db, $doPayPal;

    // if cart is empty due to timeout on login or shopping cart page, go to timeout screen
    if ($_SESSION['cart']->count_contents() == 0) {
      $message = 'Logging out due to empty shopping cart.  Is session started properly? ... ' . "\nSESSION Details:\n" . print_r($_SESSION, TRUE) . 'GET:' . "\n" . print_r($_GET, TRUE);
      include_once(DIR_WS_MODULES . 'payment/paypal/paypal_functions.php');
      ipn_debug_email($message);
      zen_redirect(zen_href_link(FILENAME_TIME_OUT, '', 'SSL'));
    }

    // init new order object
    require(DIR_WS_CLASSES . 'order.php');
    $order = new order;

    // load the selected shipping module so that shipping taxes can be assessed
    require(DIR_WS_CLASSES . 'shipping.php');
    $shipping_modules = new shipping($_SESSION['shipping']);

    // load OT modules so that discounts and taxes can be assessed
    require(DIR_WS_CLASSES . 'order_total.php');
    $order_total_modules = new order_total;
    $order_totals = $order_total_modules->pre_confirmation_check();
    $order_totals = $order_total_modules->process();

    $doPayPal = $this->paypal_init();
    $options = array();

    // build line item details
    $options = $this->getLineItemDetails($this->selectCurrency());

    // Set currency and amount
    $options['CURRENCYCODE'] = $this->selectCurrency();
    $order_amount = $this->calc_order_amount($order->info['total'], $options['CURRENCYCODE']);

    // Determine the language to use when visiting the PP site
    $lc_code = $this->getLanguageCode();
    if ($lc_code != '') $options['LOCALECODE'] = $lc_code;

    // Allow delayed payments such as eCheck?
    if (defined('MODULE_PAYMENT_PAYPALEC_ALLOWEDPAYMENT') && MODULE_PAYMENT_PAYPALEC_ALLOWEDPAYMENT == 'Instant Only') $options['ALLOWEDPAYMENTMETHOD'] = 'InstantPaymentOnly';

    //Gift Options
    $options['GIFTMESSAGEENABLE'] = 0;
    $options['GIFTRECEIPTEENABLE'] = 0;
    $options['GIFTWRAPENABLE'] = 0;
    $options['GIFTWRAPNAME'] = '';
    $options['GIFTWRAPAMOUNT'] = 0;

    $options['BUYEREMAILOPTINENABLE'] = 0;

    $options['CUSTOMERSERVICENUMBER'] = (defined('STORE_TELEPHONE_CUSTSERVICE') && STORE_TELEPHONE_CUSTSERVICE != '') ? substr(STORE_TELEPHONE_CUSTSERVICE, 0, 16) : '';

    // Store Name to appear on PayPal page
    $options['BRANDNAME'] = (defined('MODULE_PAYMENT_PAYPALWPP_BRANDNAME') && strlen(MODULE_PAYMENT_PAYPALWPP_BRANDNAME) > 3) ? substr(MODULE_PAYMENT_PAYPALWPP_BRANDNAME, 0, 127) : substr(STORE_NAME, 0, 127);

    // Payment Transaction/Authorization Mode
    $options['PAYMENTACTION'] = (MODULE_PAYMENT_PAYPALWPP_TRANSACTION_MODE == 'Auth Only') ? 'Authorization' : 'Sale';
    // for future:
    if (MODULE_PAYMENT_PAYPALWPP_TRANSACTION_MODE == 'Order') $options['PAYMENTACTION'] = 'Order';

    $options['ALLOWNOTE'] = 1;  // allow customer to enter a note on the PayPal site, which will be copied to order comments upon return to store.
    $options['SOLUTIONTYPE'] = 'Sole';  // Use 'Mark' for normal Express Checkout, 'Sole' for auctions or alternate flow
    $options['LANDINGPAGE'] = 'Billing';  // "Billing" or "Login" selects the style of landing page on PayPal site during checkout

    // Set the return URL if they click "Submit" on PayPal site
    $return_url = str_replace('&amp;', '&', zen_href_link('ipn_main_handler.php', 'type=ec', 'SSL', true, true, true));
    // Select the return URL if they click "cancel" on PayPal site or click to return without making payment or login
    $cancel_url = str_replace('&amp;', '&', zen_href_link(($_SESSION['customer_first_name'] != '' && $_SESSION['customer_id'] != '' ? FILENAME_CHECKOUT_SHIPPING : FILENAME_SHOPPING_CART), 'ec_cancel=1', 'SSL'));

    // debug
    $val = $_SESSION; unset($val['navigation']);
    $this->zcLog('ec_step1 - 1', 'Checking to see if we are in markflow' . "\n" . 'cart contents: ' . $_SESSION['cart']->get_content_type() . "\n\nNOTE: " . '$this->showPaymentPage = ' . (int)$this->showPaymentPage . "\nCustomer ID: " . (int)$_SESSION['customer_id'] . "\nSession Data: " . print_r($val, true));

    /**
     * Check whether shipping is required on this order or not.
     * If not, tell PayPal to skip all shipping options
     * ie: don't ask for any shipping info if cart content is strictly virtual and customer is already logged-in
     * (if not logged in, we need address information only to build the customer record)
     */
    if ($_SESSION['cart']->get_content_type() == 'virtual' && isset($_SESSION['customer_id']) && $_SESSION['customer_id'] > 0) {
      $this->zcLog('ec-step1-addr_check', "cart contents is virtual and customer is logged in ... therefore options['NOSHIPPING']=1");
      $options['NOSHIPPING'] = 1;
    } else {
      $this->zcLog('ec-step1-addr_check', "cart content is not all virtual (or customer is not logged in) ... therefore will be submitting address details");
      $options['NOSHIPPING'] = 0;
      // If we are in a "mark" flow and the customer has a usable address, set the addressoverride variable to 1. This will
      // override the shipping address in PayPal with the shipping address that is selected in Zen Cart.
      // @TODO: consider using address-validation against Paypal's addresses via API
      if (MODULE_PAYMENT_PAYPALWPP_CONFIRMED_ADDRESS != 'Yes' && ($address_arr = $this->getOverrideAddress()) !== false) {
        $address_error = false;
        foreach(array('entry_firstname','entry_lastname','entry_street_address','entry_city','entry_postcode','zone_code','countries_iso_code_2') as $val) {
          if ($address_arr[$val] == '') $address_error = true;
          if ($address_error == true) $this->zcLog('ec-step1-addr_check2', '$address_error = true because ' .$val . ' is blank.');
        }
        if ($address_error == false) {
          // set the override var
          $options['ADDROVERRIDE'] = 1;

          // set the address info
          $options['SHIPTONAME']    = substr($address_arr['entry_firstname'] . ' ' . $address_arr['entry_lastname'], 0, 32);
          $options['SHIPTOSTREET']  = substr($address_arr['entry_street_address'], 0, 100);
          if ($address_arr['entry_suburb'] != '') $options['SHIPTOSTREET2'] = substr($address_arr['entry_suburb'], 0, 100);
          $options['SHIPTOCITY']    = substr($address_arr['entry_city'], 0, 40);
          $options['SHIPTOZIP']     = substr($address_arr['entry_postcode'], 0, 20);
          $options['SHIPTOSTATE']   = substr($address_arr['zone_code'], 0, 40);
          $options['SHIPTOCOUNTRYCODE'] = substr($address_arr['countries_iso_code_2'], 0, 2);
          $options['SHIPTOPHONENUM'] = substr($address_arr['entry_telephone'], 0, 20);
        }
      }
      $this->zcLog('ec-step1-addr_check3', 'address details from override check:'.($address_arr == FALSE ? ' <NONE FOUND>' : print_r($address_arr, true)));

      // Do we require a "confirmed" shipping address ?
      if (MODULE_PAYMENT_PAYPALWPP_CONFIRMED_ADDRESS == 'Yes') {
        $options['REQCONFIRMSHIPPING'] = 1;
      }
    }
    // if we know customer's email address, supply it, so as to pre-fill the signup box at PayPal (useful for new PayPal accounts only)
    if (!empty($_SESSION['customer_first_name']) && !empty($_SESSION['customer_id'])) {
      $sql = "select * from " . TABLE_CUSTOMERS . " where customers_id = :custID ";
      $sql = $db->bindVars($sql, ':custID', $_SESSION['customer_id'], 'integer');
      $zc_getemail = $db->Execute($sql);
      if ($zc_getemail->RecordCount() > 0 && $zc_getemail->fields['customers_email_address'] != '') {
        $options['EMAIL'] = $zc_getemail->fields['customers_email_address'];
      }
      if ($zc_getemail->RecordCount() > 0 && $zc_getemail->fields['customers_telephone'] != '' && (!isset($options['ADDROVERRIDE']) || isset($options['ADDROVERRIDE']) && $options['ADDROVERRIDE'] != 1)) {
        $options['SHIPTOPHONENUM'] = $zc_getemail->fields['customers_telephone'];
      }
    }

    if (!isset($options['AMT'])) $options['AMT'] = number_format($order_amount, 2);

    $this->zcLog('ec_step1 - 2 -submit', print_r(array_merge($options, array('RETURNURL' => $return_url, 'CANCELURL' => $cancel_url)), true));

    /**
     * Ask PayPal for the token with which to initiate communications
     */
    $response = $doPayPal->SetExpressCheckout($return_url, $cancel_url, $options);


  $submissionCheckOne = TRUE;
  $submissionCheckTwo = TRUE;
  if ($submissionCheckOne) {
    // If there's an error on line-item details, remove tax values and resubmit, since the most common cause of 10413 is tax mismatches
    if ($response['L_ERRORCODE0'] == '10413') {
      $this->zcLog('ec_step1 - 3 - removing tax portion', 'Tax Subtotal does not match sum of taxes for line-items. Tax details removed from line-item submission data.' . "\n" . print_r($options, true));
          //echo '1st submission REJECTED. {'.$response['L_ERRORCODE0'].'}<pre>'.print_r($options, true) . urldecode(print_r($response, true));
      $tsubtotal = 0;
      foreach ($options as $key=>$value) {
        if (substr($key, 0, 8) == 'L_TAXAMT') {
          $tsubtotal += preg_replace('/[^0-9.\-]/', '', $value);
          unset($options[$key]);
        }
      }
      $options['TAXAMT'] = $tsubtotal;
      $amt = preg_replace('/[^0-9.%]/', '', $options['AMT']);
//      echo 'oldAMT:'.$amt;
//      echo ' newTAXAMT:'.$tsubtotal;
      $taxamt = preg_replace('/[^0-9.%]/', '', $options['TAXAMT']);
      $shipamt = preg_replace('/[^0-9.%]/', '', $options['SHIPPINGAMT']);
      $itemamt = preg_replace('/[^0-9.%]/', '', $options['ITEMAMT']);
      $calculatedAmount = $itemamt + $taxamt + $shipamt;
      if ($amt != $calculatedAmount) $amt = $calculatedAmount;
//      echo ' newAMT:'.$amt;
      $options['AMT'] = $amt;
      $response = $doPayPal->SetExpressCheckout($return_url, $cancel_url, $options);
//echo '<br>2nd submission. {'.$response['L_ERRORCODE0'].'}<pre>'.print_r($options, true);
    }
    if ($submissionCheckTwo) {
    if ($response['L_ERRORCODE0'] == '10413') {
      $this->zcLog('ec_step1 - 4 - removing line-item details', 'PayPal designed their own mathematics rules. Dumbing it down for them.' . "\n" . print_r($options, true));
//echo '2nd submission REJECTED. {'.$response['L_ERRORCODE0'].'}<pre>'.print_r($options, true) . urldecode(print_r($response, true));
      foreach ($options as $key=>$value) {
        if (substr($key, 0, 2) == 'L_') {
          unset($options[$key]);
        }
      }
      $amt = preg_replace('/[^0-9.%]/', '', $options['AMT']);
      $taxamt = preg_replace('/[^0-9.%]/', '', $options['TAXAMT']);
      $shipamt = preg_replace('/[^0-9.%]/', '', $options['SHIPPINGAMT']);
      $itemamt = preg_replace('/[^0-9.%]/', '', $options['ITEMAMT']);
      $calculatedAmount = $itemamt + $taxamt + $shipamt;
      if ($amt != $calculatedAmount) $amt = $calculatedAmount;
      $options['AMT'] = $amt;
      $response = $doPayPal->SetExpressCheckout($return_url, $cancel_url, $options);
//echo '<br>3rd submission. {'.$response['L_ERRORCODE0'].'}<pre>'.print_r($options, true);
    }
   }
  }

    /**
     * Determine result of request for token -- if error occurred, the errorHandler will redirect accordingly
     */
    $error = $this->_errorHandler($response, 'SetExpressCheckout');

    // Success, so read the EC token
    $_SESSION['paypal_ec_token'] = preg_replace('/[^0-9.A-Z\-]/', '', urldecode($response['TOKEN']));

    // prepare to redirect to PayPal so the customer can log in and make their selections
    $paypal_url = $this->getPayPalLoginServer();

    // Set the name of the displayed "continue" button on the PayPal site.
    // 'commit' = "Pay Now"  ||  'continue' = "Review Payment"
    $orderReview = true;
    if ($_SESSION['paypal_ec_markflow'] == 1) $orderReview = false;
    $userActionKey = "&useraction=" . ((int)$orderReview == false ? 'commit' : 'continue');

    // This is where we actually redirect the customer's browser to PayPal. Upon return from PayPal, they go to ec_step2
    header("HTTP/1.1 302 Object Moved");
    zen_redirect($paypal_url . "?cmd=_express-checkout&token=" . $_SESSION['paypal_ec_token'] . $userActionKey);

    // this should never be reached:
    return $error;
  }
1240834
function install() {
    global $db, $messageStack;
    if (defined('MODULE_PAYMENT_PAYPALWPP_STATUS')) {
      $messageStack->add_session('Express Checkout module already installed.', 'error');
      zen_redirect(zen_href_link(FILENAME_MODULES, 'set=payment&module=paypalwpp', 'NONSSL'));
      return 'failed';
    }
    if (defined('MODULE_PAYMENT_PAYPAL_STATUS')) {
      $messageStack->add_session('NOTE: You already have the PayPal Website Payments Standard module installed. You should REMOVE it if you want to install Express Checkout.', 'error');
      zen_redirect(zen_href_link(FILENAME_MODULES, 'set=payment&module=paypal', 'NONSSL'));
      return 'failed';
    }

    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable this Payment Module', 'MODULE_PAYMENT_PAYPALWPP_STATUS', 'True', 'Do you want to enable this payment module?', '6', '25', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Live or Sandbox', 'MODULE_PAYMENT_PAYPALWPP_SERVER', 'live', '<strong>Live: </strong> Used to process Live transactions<br><strong>Sandbox: </strong>For developers and testing', '6', '25', 'zen_cfg_select_option(array(\'live\', \'sandbox\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Express Checkout Shortcut Button', 'MODULE_PAYMENT_PAYPALWPP_ECS_BUTTON', 'On', 'The Express Checkout Shortcut button shows up on your shopping cart page to invite your customers to pay using PayPal without having to give all their address details on your site first before selecting shipping options.<br />It has been shown to increase sales and conversions when enabled.<br />Default: On ', '6', '25', 'zen_cfg_select_option(array(\'On\', \'Off\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Express Checkout: Require Confirmed Address', 'MODULE_PAYMENT_PAYPALWPP_CONFIRMED_ADDRESS', 'No', 'Do you want to require that your (not-logged-in) customers use a *confirmed* address when choosing their shipping address in PayPal?<br />(this is ignored for logged-in customers)', '6', '25',  'zen_cfg_select_option(array(\'Yes\', \'No\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Express Checkout: Select Cheapest Shipping Automatically', 'MODULE_PAYMENT_PAYPALWPP_AUTOSELECT_CHEAPEST_SHIPPING', 'Yes', 'When customer returns from PayPal, do we want to automatically select the Cheapest shipping method and skip the shipping page? (making it more *express*)<br />Note: enabling this means the customer does *not* have easy access to select an alternate shipping method (without going back to the Checkout-Step-1 page)', '6', '25',  'zen_cfg_select_option(array(\'Yes\', \'No\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Express Checkout: Skip Payment Page', 'MODULE_PAYMENT_PAYPALWPP_SKIP_PAYMENT_PAGE', 'Yes', 'If the customer is checking out with Express Checkout, do you want to skip the checkout payment page, making things more *express*? <br /><strong>(NOTE: The Payment Page will auto-display regardless of this setting if you have Coupons or Gift Certificates enabled in your store.)</strong>', '6', '25',  'zen_cfg_select_option(array(\'Yes\', \'No\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Express Checkout: Automatic Account Creation', 'MODULE_PAYMENT_PAYPALWPP_NEW_ACCT_NOTIFY', 'Yes', 'If a visitor is not an existing customer, a Zen Cart account is created for them.  Would you like make it a permanent account and send them an email containing their login information?<br />NOTE: Permanent accounts are auto-created if the customer purchases downloads or gift certificates, regardless of this setting.', '6', '25', 'zen_cfg_select_option(array(\'Yes\', \'No\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort order of display.', 'MODULE_PAYMENT_PAYPALWPP_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.', '6', '25', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_PAYPALWPP_ZONE', '0', 'If a zone is selected, only enable this payment method for that zone.', '6', '25', 'zen_get_zone_class_title', 'zen_cfg_pull_down_zone_classes(', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Order Status', 'MODULE_PAYMENT_PAYPALWPP_ORDER_STATUS_ID', '2', 'Set the status of orders paid with this payment module to this value. <br /><strong>Recommended: Processing[2]</strong>', '6', '25', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Unpaid Order Status', 'MODULE_PAYMENT_PAYPALWPP_ORDER_PENDING_STATUS_ID', '1', 'Set the status of unpaid orders made with this payment module to this value. <br /><strong>Recommended: Pending[1]</strong>', '6', '25', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Refund Order Status', 'MODULE_PAYMENT_PAYPALWPP_REFUNDED_STATUS_ID', '1', 'Set the status of refunded orders to this value. <br /><strong>Recommended: Pending[1]</strong>', '6', '25', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('PayPal Page Style', 'MODULE_PAYMENT_PAYPALWPP_PAGE_STYLE', 'Primary', 'The page-layout style you want customers to see when they visit the PayPal site. You can configure your <strong>Custom Page Styles</strong> in your PayPal Profile settings. This value is case-sensitive.', '6', '25', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Store (Brand) Name at PayPal', 'MODULE_PAYMENT_PAYPALWPP_BRANDNAME', '', 'The name of your store as it should appear on the PayPal login page. If blank, your store name will be used.', '6', '25', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Payment Action', 'MODULE_PAYMENT_PAYPALWPP_TRANSACTION_MODE', 'Final Sale', 'How do you want to obtain payment?<br /><strong>Default: Final Sale</strong>', '6', '25', 'zen_cfg_select_option(array(\'Auth Only\', \'Final Sale\'), ',  now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Transaction Currency', 'MODULE_PAYMENT_PAYPALWPP_CURRENCY', 'Selected Currency', 'Which currency should the order be sent to PayPal as? <br />NOTE: if an unsupported currency is sent to PayPal, it will be auto-converted to USD (or GBP if using UK account)<br /><strong>Default: Selected Currency</strong>', '6', '25', 'zen_cfg_select_option(array(\'Selected Currency\', \'Only USD\', \'Only AUD\', \'Only CAD\', \'Only EUR\', \'Only GBP\', \'Only CHF\', \'Only CZK\', \'Only DKK\', \'Only HKD\', \'Only HUF\', \'Only JPY\', \'Only NOK\', \'Only NZD\', \'Only PLN\', \'Only SEK\', \'Only SGD\', \'Only THB\', \'Only MXN\', \'Only ILS\', \'Only PHP\', \'Only TWD\', \'Only BRL\', \'Only MYR\', \'Only TKD\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Allow eCheck?', 'MODULE_PAYMENT_PAYPALEC_ALLOWEDPAYMENT', 'Any', 'Do you want to allow non-instant payments like eCheck/EFT/ELV?', '6', '25', 'zen_cfg_select_option(array(\'Any\', \'Instant Only\'), ', now())");

    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Fraud Mgmt Filters - FMF', 'MODULE_PAYMENT_PAYPALWPP_EC_RETURN_FMF_DETAILS', 'No', 'If you have enabled FMF support in your PayPal account and wish to utilize it in your transactions, set this to yes. Otherwise, leave it at No.', '6', '25','zen_cfg_select_option(array(\'No\', \'Yes\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('API Signature -- Username', 'MODULE_PAYMENT_PAYPALWPP_APIUSERNAME', '', 'The API Username from your PayPal API Signature settings under *API Access*. This value typically looks like an email address and is case-sensitive.', '6', '25', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added, set_function, use_function) values ('API Signature -- Password', 'MODULE_PAYMENT_PAYPALWPP_APIPASSWORD', '', 'The API Password from your PayPal API Signature settings under *API Access*. This value is a 16-character code and is case-sensitive.', '6', '25', now(), 'zen_cfg_password_input(', 'zen_cfg_password_display')");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added, set_function, use_function) values ('API Signature -- Signature Code', 'MODULE_PAYMENT_PAYPALWPP_APISIGNATURE', '', 'The API Signature from your PayPal API Signature settings under *API Access*. This value is a 56-character code, and is case-sensitive.', '6', '25', now(), '', 'zen_cfg_password_display')");

    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('PAYFLOW: User', 'MODULE_PAYMENT_PAYPALWPP_PFUSER', '', 'If you set up one or more additional users on the account, this value is the ID of the user authorized to process transactions. Otherwise it should be the same value as VENDOR. This value is case-sensitive.', '6', '25', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('PAYFLOW: Partner', 'MODULE_PAYMENT_PAYPALWPP_PFPARTNER', 'ZenCart', 'Your Payflow Partner name linked to your Payflow account. This value is case-sensitive.<br />Typical values: <strong>PayPal</strong> or <strong>ZenCart</strong>', '6', '25', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('PAYFLOW: Vendor', 'MODULE_PAYMENT_PAYPALWPP_PFVENDOR', '', 'Your merchant login ID that you created when you registered for the Payflow Pro account. This value is case-sensitive.', '6', '25', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added, set_function, use_function) values ('PAYFLOW: Password', 'MODULE_PAYMENT_PAYPALWPP_PFPASSWORD', '', 'The 6- to 32-character password that you defined while registering for the account. This value is case-sensitive.', '6', '25', now(), 'zen_cfg_password_input(', 'zen_cfg_password_display')");

    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('PayPal Mode', 'MODULE_PAYMENT_PAYPALWPP_MODULE_MODE', 'PayPal', 'Which PayPal API system should be used for processing? <br /><u>Choices:</u><br /><font color=green>For choice #1, you need to supply <strong>API Settings</strong> above.</font><br /><strong>1. PayPal</strong> = Express Checkout with a regular PayPal account<br />or<br /><font color=green>for choices 2 &amp; 3 you need to supply <strong>PAYFLOW settings</strong>, below (and have a Payflow account)</font><br /><strong>2. Payflow-UK</strong> = Website Payments Pro UK Payflow Edition<br /><strong>3. Payflow-US</strong> = Payflow Pro Gateway only<!--<br /><strong>4. PayflowUS+EC</strong> = Payflow Pro with Express Checkout-->', '6', '25',  'zen_cfg_select_option(array(\'PayPal\', \'Payflow-UK\', \'Payflow-US\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Debug Mode', 'MODULE_PAYMENT_PAYPALWPP_DEBUGGING', 'Off', 'Would you like to enable debug mode?  A complete detailed log of failed transactions will be emailed to the store owner.', '6', '25', 'zen_cfg_select_option(array(\'Off\', \'Alerts Only\', \'Log File\', \'Log and Email\'), ', now())");

    $this->notify('NOTIFY_PAYMENT_PAYPALWPP_INSTALLED');
  }
565745
function confirmation() {
    $confirmation = array('title' => '',
                          'fields' => array(array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_FIRSTNAME,
                                                  'field' => $_POST['paypalwpp_cc_firstname']),
                                            array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_LASTNAME,
                                                  'field' => $_POST['paypalwpp_cc_lastname']),
                                            array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_TYPE,
                                                  'field' => $this->cc_card_type),
                                            array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_NUMBER,
                                                  'field' => substr($_POST['paypalwpp_cc_number'], 0, 4) . str_repeat('X', (strlen($_POST['paypalwpp_cc_number']) - 8)) . substr($_POST['paypalwpp_cc_number'], -4)),
                                            array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_EXPIRES,
                                                  'field' => strftime('%B, %Y', mktime(0,0,0,$_POST['paypalwpp_cc_expires_month'], 1, '20' . $_POST['paypalwpp_cc_expires_year'])),
                                            (isset($_POST['paypalwpp_cc_issuenumber']) ? array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_ISSUE_NUMBER,
                                                  'field' => $_POST['paypalwpp_cc_issuenumber']) : '')
                                            )));
    // 3D-Secure
    if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK' && $this->requiresLookup($_POST['paypalwpp_cc_number']) == true) {
          $confirmation['fields'][count($confirmation['fields'])] = array(
              'title' => '',
              'field' => '<div id="' . $this->code.'-cc-securetext"><p>' .
                         '<a href="javascript:void window.open(\'vbv_learn_more.html\',\'vbv_service\',\'width=550,height=450\')">' .
                         zen_image(DIR_WS_IMAGES.'3ds/vbv_learn_more.gif') . '</a>' .
                         '<a href="javascript:void window.open(\'mcs_learn_more.html\',\'mcsc_service\',\'width=550,height=450\')">' .
                         zen_image(DIR_WS_IMAGES.'3ds/mcsc_learn_more.gif') . '</a></p>' .
                         '<p>' . TEXT_3DS_CARD_MAY_BE_ENROLLED . '</p></div>');
    }
    return $confirmation;
  }
612958
function in_special_checkout() {
    if ((defined('MODULE_PAYMENT_PAYPALDP_STATUS') && MODULE_PAYMENT_PAYPALDP_STATUS == 'True') &&
             !empty($_SESSION['paypal_ec_token']) &&
             !empty($_SESSION['paypal_ec_payer_id']) &&
             !empty($_SESSION['paypal_ec_payer_info'])) {
      return true;
    }
  }
32263
public function buildForm()
    {
        $formBuilder = $this
            ->formFactory
            ->createNamedBuilder(null);

        $orderId = $this
            ->paymentBridge
            ->getOrderId();

        $orderCurrency = $this
            ->paymentBridge
            ->getCurrency();

        $this->checkCurrency($orderCurrency);

        /**
         * Creates the success return route, when coming back
         * from PayPal web checkout.
         */
        $successReturnUrl = $this
            ->urlFactory
            ->getSuccessReturnUrlForOrderId($orderId);

        /**
         * Creates the cancel payment route, when cancelling
         * the payment process from PayPal web checkout.
         */
        $cancelReturnUrl = $this
            ->urlFactory
            ->getCancelReturnUrlForOrderId($orderId);

        /**
         * Creates the IPN payment notification route,
         * which is triggered after PayPal processes the
         * payment and returns the validity of the transaction.
         *
         * For forther information
         *
         * https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNandPDTVariables/
         * https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNIntro/
         */
        $processUrl = $this
            ->urlFactory
            ->getProcessUrlForOrderId($orderId);

        $formBuilder
            ->setAction($this->urlFactory->getApiEndpoint())
            ->setMethod('POST')
            ->add('business', 'hidden', [
                'data' => $this->business,
            ])
            ->add('return', 'hidden', [
                'data' => $successReturnUrl,
            ])
            ->add('cancel_return', 'hidden', [
                'data' => $cancelReturnUrl,
            ])
            ->add('notify_url', 'hidden', [
                'data' => $processUrl,
            ])
            ->add('currency_code', 'hidden', [
                'data' => $orderCurrency,
            ])
            ->add('env', 'hidden', [
                'data' => '',
            ]);

        /**
         * Create a PayPal cart line for each order line.
         *
         * Project specific PaymentBridgeInterface::getExtraData
         * should return an array of this form
         *
         *   ['items' => [
         *       0 => [ 'item_name' => 'Item 1', 'amount' => 1234, 'quantity' => 2 ],
         *       1 => [ 'item_name' => 'Item 2', 'amount' => 2345, 'quantity' => 1 ],
         *   ]]
         *
         * The 'items' key consists of an array with the basic information
         * of each line of the order. Amount is the price of the product,
         * not the total of the order line
         */
        $cartData = $this->paymentBridge->getExtraData();
        $itemsData = $cartData['items'];
        $iteration = 1;

        foreach ($itemsData as $orderLine) {
            $formBuilder
                ->add('item_name_' . $iteration, 'hidden', [
                    'data' => $orderLine['item_name'],
                ])
                ->add('amount_' . $iteration, 'hidden', [
                    'data' => $orderLine['amount'],
                ])
                ->add('quantity_' . $iteration, 'hidden', [
                    'data' => $orderLine['quantity'],
                ]);
            ++$iteration;
        }

        if (isset($cartData['discount_amount_cart'])) {
            $formBuilder->add('discount_amount_cart', 'hidden', [
                'data' => $cartData['discount_amount_cart'],
            ]);
        }

        return $formBuilder
            ->getForm()
            ->createView();
    }
215792
protected function submitEditCheckout()
    {
        $this->setSubmitted('order');

        $this->setAddressFormCheckout();
        $this->submitAddAddressCheckout();

        if ($this->isPosted('checkout_login') && empty($this->uid)) {
            $this->show_login_form = true;
        }

        $this->same_payment_address = (bool) $this->getPosted('same_payment_address', true, false, 'bool');

        if ($this->isPosted('update')) {
            $this->setMessage($this->text('Form has been updated'), 'success', false);
        }

        $this->submitLoginCheckout();

        if ($this->isPosted('checkout_anonymous')) {
            $this->show_login_form = false;
        }

        $this->validateCouponCheckout();
        $this->submitCartCheckout();
        $this->submitOrderCheckout();
    }
1281153
function before_process() {
    global $order, $doPayPal, $messageStack;
    $options = array();
    $optionsShip = array();
    $optionsNVP = array();

    $options = $this->getLineItemDetails($this->selectCurrency($order->info['currency']));

    //$this->zcLog('before_process - 1', 'Have line-item details:' . "\n" . print_r($options, true));

    // Initializing DESC field: using for comments related to tax-included pricing, populated by getLineItemDetails()
    $options['DESC'] = '';

    $doPayPal = $this->paypal_init();
      /****************************************
       * Do DP checkout
       ****************************************/
      $this->zcLog('before_process - DP-1', 'Beginning DP mode' /* . print_r($_POST, TRUE)*/);
      // Set state fields depending on what PayPal wants to see for that country
      $this->setStateAndCountry($order->billing);
      if (zen_not_null($order->delivery['street_address'])) {
        $this->setStateAndCountry($order->delivery);
      }

      // Validate credit card data
      include(DIR_WS_CLASSES . 'cc_validation.php');
      $cc_validation = new cc_validation();
      $response = $cc_validation->validate($_POST['wpp_cc_number'], $_POST['wpp_cc_expdate_month'], $_POST['wpp_cc_expdate_year'],
                                           $_POST['wpp_cc_issuedate_month'], $_POST['wpp_cc_issuedate_year']);
      $error = '';
      switch ($response) {
        case -1:
          $error = sprintf(TEXT_CCVAL_ERROR_UNKNOWN_CARD, substr($cc_validation->cc_number, 0, 4));
          break;
        case -2:
        case -3:
        case -4:
          $error = TEXT_CCVAL_ERROR_INVALID_DATE;
          break;
        case false:
          $error = TEXT_CCVAL_ERROR_INVALID_NUMBER;
          break;
      }

      if (($response === false) || ($response < 1) ) {
        $this->zcLog('before_process - DP-2', 'CC validation results: ' . $error . '(' . $response . ')');
        $messageStack->add_session('checkout_payment', $error . '<!-- ['.$this->code.'] -->' . '<!-- result: ' . $response . ' -->', 'error');
        zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
      }
      if (!in_array($cc_validation->cc_type, array('Visa', 'MasterCard', 'Switch', 'Solo', 'Discover', 'American Express', 'Maestro'))) {
//        $this->zcLog('before_process - DP-3', 'CC info: ' . $cc_validation->cc_type . ' ' . substr($cc_validation->cc_number, 0, 4) . str_repeat('X', (strlen($cc_validation->cc_number) - 8)) . substr($cc_validation->cc_number, -4) . ' ' . $error);
        $messageStack->add_session('checkout_payment', MODULE_PAYMENT_PAYPALDP_TEXT_BAD_CARD . '<!-- [' . $this->code . ' ' . $cc_validation->cc_type . '] -->', 'error');
        zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
      }

      // if CC validation passed, continue using the validated data
      $cc_type = $cc_validation->cc_type;
      $cc_number = $cc_validation->cc_number;
      $cc_first_name = ($_POST['wpp_payer_firstname'] != '' ? $_POST['wpp_payer_firstname'] : $_SESSION['customer_first_name']);
      $cc_last_name = ($_POST['wpp_payer_lastname'] != '' ? $_POST['wpp_payer_lastname'] : $_SESSION['customer_last_name']);
      $cc_checkcode = $_POST['wpp_cc_checkcode'];
      $cc_expdate_month = $cc_validation->cc_expiry_month;
      $cc_expdate_year = $cc_validation->cc_expiry_year;
      $cc_issuedate_month = $_POST['wpp_cc_issuedate_month'];
      $cc_issuedate_year = $_POST['wpp_cc_issuedate_year'];
      $cc_issuenumber = $_POST['wpp_cc_issuenumber'];
      $cc_owner_ip = current(explode(':', str_replace(',', ':', zen_get_ip_address())));

      // If they're still here, set some of the order object's variables.
      $order->info['cc_type'] = $cc_type;
      $order->info['cc_number'] = substr($cc_number, 0, 4) . str_repeat('X', (strlen($cc_number) - 8)) . substr($cc_number, -4);
      $order->info['cc_owner'] = $cc_first_name . ' ' . $cc_last_name;
      $order->info['cc_expires'] = ''; //$cc_expdate_month . substr($cc_expdate_year, -2);
      $order->info['ip_address'] = $cc_owner_ip;

      // Set currency
      $my_currency = $this->selectCurrency($order->info['currency'], 'DP');

      // if CC is switch or solo, must be GBP
      if (in_array($cc_type, array('Switch', 'Solo', 'Maestro'))) {
        $my_currency = 'GBP';
      }

//      $order->info['total'] = zen_round($order->info['total'], 2);
      $order_amount = $this->calc_order_amount($order->info['total'], $my_currency);
      $display_order_amount = $this->calc_order_amount($order->info['total'], $my_currency, TRUE);


      // 3D-Secure
      if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK') {
        // determine the card type and validate that authentication was attempted and completed if applicable
        if (($_SESSION['3Dsecure_requires_lookup'] || $this->requiresLookup($_POST['wpp_cc_number']) == true)) {  // authentication attempt required?
          // validate an acceptable lookup result
          if (isset($_SESSION['3Dsecure_enroll_lookup_attempted']) == false || strcasecmp($_SESSION['3Dsecure_enroll_lookup_attempted'], 'Y') != 0) {
            // lookup never attempted for required card, so need to redirect to payment-selection page
            $reason = 'Customer arrived on the order process page without attempting authentication lookup.';
            $error = MODULE_PAYMENT_PAYPALDP_CANNOT_BE_COMPLETED;
            $messageStack->add_session('checkout_payment', $error . '<!-- ['.$this->code.'] -->' . '<!-- result: ' . $reason . ' -->', 'error');
            $errorText = $reason ."\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
            $errorText .= $this->code;
            zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULE_PAYMENT_PAYPALDP_TEXT_EMAIL_ERROR_SUBJECT, $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
            zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
          }
          // if enrolled, validate an acceptable authentication result
          if (strcasecmp('Y', $_SESSION['3Dsecure_enrolled']) == 0) {
            if (isset($_SESSION['3Dsecure_authentication_attempted']) == false || strcasecmp($_SESSION['3Dsecure_authentication_attempted'], 'Y') != 0) {
              $reason = 'Customer arrived on the order process page without completing required authentication.';
              $error = MODULE_PAYMENT_PAYPALDP_CANNOT_BE_COMPLETED;
              $messageStack->add_session('checkout_payment', $error . '<!-- ['.$this->code.'] -->' . '<!-- result: ' . $reason . ' -->', 'error');
              $errorText = $reason ."\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
              $errorText .= $this->code;
              zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULE_PAYMENT_PAYPALDP_TEXT_EMAIL_ERROR_SUBJECT, $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');

              // remove the lookup/auth attempted status
              unset($_SESSION['3Dsecure_enroll_lookup_attempted']);
              unset($_SESSION['3Dsecure_authentication_attempted']);

              // authentication result was not acceptable, redirect
              zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
            }
          }
        }
        if ($cc_type != 'Solo') {  // PayPal doesn't support 3d-secure on Solo cards
          if (isset($_SESSION['3Dsecure_enrolled'])) {
            $options['MPIVENDOR3DS'] = $_SESSION['3Dsecure_enrolled'];
          }
          if ($_SESSION['3Dsecure_auth_eci'] != '') {
            $options['ECI'] = $_SESSION['3Dsecure_auth_eci'];
          }
          if (isset($_SESSION['3Dsecure_auth_xid']) and strlen($_SESSION['3Dsecure_auth_xid']) > 0) {
            $options['XID'] = $_SESSION['3Dsecure_auth_xid'];
            $options['CAVV'] = $_SESSION['3Dsecure_auth_cavv'];
            $options['AUTHSTATUS3DS'] = $_SESSION['3Dsecure_auth_status'];
          }
        }
      }
///////////////////////////


      // Initialize the paypal caller object.
      $doPayPal = $this->paypal_init();
      $optionsAll = array_merge($options,
                    array('STREET'      => $order->billing['street_address'],
                          'ZIP'         => $order->billing['postcode'],
                          'CITY'        => $order->billing['city'],
                          'STATE'       => $order->billing['state'],
                          'STREET2'     => $order->billing['suburb'],
                          'COUNTRYCODE' => $order->billing['country']['iso_code_2'],
                          'EXPDATE'     => $cc_expdate_month . $cc_expdate_year,
                          'EMAIL'       => $order->customer['email_address'],
                          'PHONENUM'    => $order->customer['telephone']));

      $optionsShip = array();
      if (isset($order->delivery) && $order->delivery['street_address'] != '') {
        $optionsShip= array('SHIPTONAME'   => ($order->delivery['name'] == '' ? $order->delivery['firstname'] . ' ' . $order->delivery['lastname'] : $order->delivery['name']),
                            'SHIPTOSTREET' => $order->delivery['street_address'],
                            'SHIPTOSTREET2' => $order->delivery['suburb'],
                            'SHIPTOCITY'   => $order->delivery['city'],
                            'SHIPTOZIP'    => $order->delivery['postcode'],
                            'SHIPTOSTATE'  => $order->delivery['state'],
                            'SHIPTOCOUNTRYCODE'=> $order->delivery['country']['iso_code_2']);
      }
      // if these optional parameters are blank, remove them from transaction
      if (isset($optionsShip['SHIPTOSTREET2']) && trim($optionsShip['SHIPTOSTREET2']) == '') unset($optionsShip['SHIPTOSTREET2']);
      if ($optionsAll['STREET2'] == '') unset($optionsAll['STREET2']);
      if (isset($optionsShip['SHIPTOPHONE']) && trim($optionsShip['SHIPTOPHONE']) == '') unset($optionsShip['SHIPTOPHONE']);

      // if State is not supplied, repeat the city so that it's not blank, otherwise PayPal croaks
      if ((!isset($optionsShip['SHIPTOSTATE']) || trim($optionsShip['SHIPTOSTATE']) == '') && isset($optionsShip['SHIPTOCITY'])) $optionsShip['SHIPTOSTATE'] = $optionsShip['SHIPTOCITY'];

      // Payment Transaction/Authorization Mode
      $optionsNVP['PAYMENTACTION'] = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'Authorization' : 'Sale';
      if (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') $this->order_status = $this->order_pending_status;

//      if (in_array($cc_type, array('Switch', 'Solo'))) {
//        $optionsNVP['PAYMENTACTION'] = 'Authorization';
//      }
      $optionsAll['BUTTONSOURCE'] = $this->buttonSource;
      $optionsAll['CURRENCY']     = $my_currency;
      if (strlen($cc_owner_ip) > 7) {
        $optionsAll['IPADDRESS']    = $cc_owner_ip;
      }
      if ($cc_issuedate_month && $cc_issuedate_year) {
        $optionsAll['CARDSTART'] = $cc_issuedate_month . substr($cc_issuedate_year, -2);
      }
      if (isset($_POST['wpp_cc_issuenumber'])) $optionsAll['CARDISSUE'] = $_POST['wpp_cc_issuenumber'];

      // Add note to track that this was an API WPP transaction:
      $optionsAll['CUSTOM'] = 'DP-' . (int)$_SESSION['customer_id'] . '-' . time();

      // send the store name as transaction identifier, to help distinguish payments between multiple stores:
      $optionsAll['INVNUM'] = (int)$_SESSION['customer_id'] . '-' . time() . '-[' . substr(preg_replace('/[^a-zA-Z0-9_]/', '', STORE_NAME), 0, 30) . ']';  // (cannot send actual invoice number because it's not assigned until after payment is completed)

      if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK' || (MODULE_PAYMENT_PAYPALWPP_PFVENDOR != '' && MODULE_PAYMENT_PAYPALWPP_PFPASSWORD != '')) { // Payflow params required
        if (isset($optionsAll['COUNTRYCODE'])) {
          $optionsAll['COUNTRY'] = $optionsAll['COUNTRYCODE'];
          unset($optionsAll['COUNTRYCODE']);
        }
        if (isset($optionsShip['SHIPTOCOUNTRYCODE'])) {
          $optionsShip['SHIPTOCOUNTRY'] = $optionsShip['SHIPTOCOUNTRYCODE'];
          unset($optionsShip['SHIPTOCOUNTRYCODE']);
        }
        if (isset($optionsShip['SHIPTOSTREET2'])) unset($optionsShip['SHIPTOSTREET2']);
        if (isset($optionsAll['STREET2'])) unset($optionsAll['STREET2']);
      }
      if (isset($optionsAll['DESC']) && $optionsAll['DESC'] == '') unset($optionsAll['DESC']);
      $this->zcLog('before_process - DP-4', 'options: ' . print_r(array_merge($optionsAll, $optionsNVP, $optionsShip), true) . "\n" . 'Rest of data: ' . "\n" . number_format($order_amount, 2) . ' ' . $cc_expdate_month . ' ' . substr($cc_expdate_year, -2) . ' ' . $cc_first_name . ' ' . $cc_last_name . ' ' . $cc_type);

      if (!isset($optionsAll['AMT'])) $optionsAll['AMT'] = number_format($order_amount, 2, '.', '');
      $response = $doPayPal->DoDirectPayment($cc_number,
                                           $cc_checkcode,
                                           $cc_expdate_month . substr($cc_expdate_year, -2),
                                           $cc_first_name, $cc_last_name,
                                           $cc_type,
                                           $optionsAll, array_merge($optionsNVP, $optionsShip));

      $this->zcLog('before_process - DP-5', 'resultset:' . "\n" . urldecode(print_r($response, true)));

      // CHECK RESPONSE
      $error = $this->_errorHandler($response, 'DoDirectPayment');

      if ($this->fmfResponse != '') {
        $this->order_status = $this->order_pending_status;
      }

      $this->feeamt = '';
      $this->taxamt = '';
      $this->pendingreason = '';
      $this->reasoncode = '';
      $this->numitems = sizeof($order->products);
      $this->responsedata = $response;

      if ($response['PNREF']) {
      // PNREF only comes from payflow mode
        $this->payment_type = MODULE_PAYMENT_PAYPALDP_PF_TEXT_TYPE;
        $this->transaction_id = $response['PNREF'];
        $this->payment_status = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'Authorization' : 'Completed';
        $this->avs = 'AVSADDR: ' . $response['AVSADDR'] . ', AVSZIP: ' . $response['AVSZIP'] . ', IAVS: ' . $response['IAVS'];
        $this->cvv2 = $response['CVV2MATCH'];
        $this->amt = $display_order_amount . ' ' . $my_currency;
        $this->payment_time = date('Y-m-d h:i:s');
        $this->responsedata['CURRENCYCODE'] = $my_currency;
        $this->responsedata['EXCHANGERATE'] = $order->info['currency_value'];
        $this->auth_code = $this->response['AUTHCODE'];
      } else {
        // here we're in NVP mode
        $this->transaction_id = $response['TRANSACTIONID'];
        $this->payment_type = MODULE_PAYMENT_PAYPALDP_DP_TEXT_TYPE;
        $this->payment_status = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'Authorization' : 'Completed';
        $this->pendingreason = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'authorization' : '';
        $this->avs = $response['AVSCODE'];
        $this->cvv2 = $response['CVV2MATCH'];
        $this->correlationid = $response['CORRELATIONID'];
        $this->payment_time = urldecode($response['TIMESTAMP']);
        $this->amt = urldecode($response['AMT'] . ' ' . $response['CURRENCYCODE']);
        $this->auth_code = (isset($this->response['AUTHCODE'])) ? $this->response['AUTHCODE'] : $this->response['TOKEN'];
        $this->transactiontype = 'cart';
      }
  }
897120
function after_process() {
    global $insert_id, $db, $order;
    // FMF
    if ($this->fmfResponse != '') {
      $detailedMessage = $insert_id . "\n" . $this->fmfResponse . "\n" . MODULES_PAYMENT_PAYPALDP_TEXT_EMAIL_FMF_INTRO . "\n" . print_r($this->fmfErrors, TRUE);
      zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULES_PAYMENT_PAYPALDP_TEXT_EMAIL_FMF_SUBJECT . ' (' . $insert_id . ')', $detailedMessage, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($detailedMessage)), 'paymentalert');
    }

    // add a new OSH record for this order's PP details
    $commentString = "Transaction ID: :transID: " .
                     (isset($this->responsedata['PPREF']) ? "\nPPRef: " . $this->responsedata['PPREF'] : "") .
                     (isset($this->responsedata['AUTHCODE'])? "\nAuthCode: " . $this->responsedata['AUTHCODE'] : "") .
                                 "\nPayment Type: :pmtType: " .
                     ($this->payment_time != '' ? "\nTimestamp: :pmtTime: " : "") .
                                 "\nPayment Status: :pmtStatus: " .
                     (isset($this->responsedata['auth_exp']) ? "\nAuth-Exp: " . $this->responsedata['auth_exp'] : "") .
                     ($this->avs != 'N/A' ? "\nAVS Code: ".$this->avs."\nCVV2 Code: ".$this->cvv2 : '') .
                     (trim($this->amt) != '' ? "\nAmount: :orderAmt: " : "");
    $commentString = $db->bindVars($commentString, ':transID:', $this->transaction_id, 'noquotestring');
    $commentString = $db->bindVars($commentString, ':pmtType:', $this->payment_type, 'noquotestring');
    $commentString = $db->bindVars($commentString, ':pmtTime:', $this->payment_time, 'noquotestring');
    $commentString = $db->bindVars($commentString, ':pmtStatus:', $this->payment_status, 'noquotestring');
    $commentString = $db->bindVars($commentString, ':orderAmt:', $this->amt, 'noquotestring');

    $sql_data_array= array(array('fieldName'=>'orders_id', 'value'=>$insert_id, 'type'=>'integer'),
                           array('fieldName'=>'orders_status_id', 'value'=>$order->info['order_status'], 'type'=>'integer'),
                           array('fieldName'=>'date_added', 'value'=>'now()', 'type'=>'noquotestring'),
                           array('fieldName'=>'customer_notified', 'value'=>0, 'type'=>'integer'),
                           array('fieldName'=>'comments', 'value'=>$commentString, 'type'=>'string'));
    $db->perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);

    // 3D-Secure
    if ($this->requiresLookup($order->info['cc_type']) == true) {
      // CardinalCommerce Liability Protection Status
      // Inserts 'PROTECTED' or 'NOT PROTECTED' status, ECI, CAVV values in the order status history comments
      $auth_proc_status = $this->determine3DSecureProtection($order->info['cc_type'], $_SESSION['3Dsecure_auth_eci']);
      $commentString = "3D-Secure: " . $auth_proc_status . "\n" . 'ECI Value = ' . $_SESSION['3Dsecure_auth_eci'] . "\n" . 'CAVV Value = ' . $_SESSION['3Dsecure_auth_cavv'];
      $sql_data_array= array(array('fieldName'=>'orders_id', 'value'=> $insert_id, 'type'=>'integer'),
                             array('fieldName'=>'orders_status_id', 'value'=> $order->info['order_status'], 'type'=>'integer'),
                             array('fieldName'=>'date_added', 'value'=>'now()', 'type'=>'noquotestring'),
                             array('fieldName'=>'customer_notified', 'value'=> -1, 'type'=>'integer'),
                             array('fieldName'=>'comments', 'value'=> $commentString, 'type'=>'string'));
      $db->perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
    }

    // store the PayPal order meta data -- used for later matching and back-end processing activities
    $paypal_order = array('order_id' => $insert_id,
                          'txn_type' => $this->transactiontype,
                          'module_name' => $this->code,
                          'module_mode' => MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY,
                          'reason_code' => $this->reasoncode,
                          'payment_type' => $this->payment_type,
                          'payment_status' => $this->payment_status,
                          'pending_reason' => $this->pendingreason,
                          'invoice' => urldecode($_SESSION['paypal_ec_token'] . $this->responsedata['PPREF']),
                          'first_name' => $_SESSION['paypal_ec_payer_info']['payer_firstname'],
                          'last_name' => $_SESSION['paypal_ec_payer_info']['payer_lastname'],
                          'payer_business_name' => $_SESSION['paypal_ec_payer_info']['payer_business'],
                          'address_name' => $_SESSION['paypal_ec_payer_info']['ship_name'],
                          'address_street' => $_SESSION['paypal_ec_payer_info']['ship_street_1'],
                          'address_city' => $_SESSION['paypal_ec_payer_info']['ship_city'],
                          'address_state' => $_SESSION['paypal_ec_payer_info']['ship_state'],
                          'address_zip' => $_SESSION['paypal_ec_payer_info']['ship_postal_code'],
                          'address_country' => $_SESSION['paypal_ec_payer_info']['ship_country'],
                          'address_status' => $_SESSION['paypal_ec_payer_info']['ship_address_status'],
                          'payer_email' => $_SESSION['paypal_ec_payer_info']['payer_email'],
                          'payer_id' => $_SESSION['paypal_ec_payer_id'],
                          'payer_status' => $_SESSION['paypal_ec_payer_info']['payer_status'],
                          'payment_date' => trim(preg_replace('/[^0-9-:]/', ' ', $this->payment_time)),
                          'business' => '',
                          'receiver_email' => (MODULE_PAYMENT_PAYPALWPP_PFVENDOR != '' ? MODULE_PAYMENT_PAYPALWPP_PFVENDOR : str_replace('_api1', '', MODULE_PAYMENT_PAYPALWPP_APIUSERNAME)),
                          'receiver_id' => '',
                          'txn_id' => $this->transaction_id,
                          'parent_txn_id' => '',
                          'num_cart_items' => (float)$this->numitems,
                          'mc_gross' => (float)$this->amt,
                          'mc_fee' => (float)urldecode($this->feeamt),
                          'mc_currency' => $this->responsedata['CURRENCYCODE'],
                          'settle_amount' => (float)urldecode($this->responsedata['SETTLEAMT']),
                          'settle_currency' => $this->responsedata['CURRENCYCODE'],
                          'exchange_rate' => (urldecode($this->responsedata['EXCHANGERATE']) > 0 ? urldecode($this->responsedata['EXCHANGERATE']) : 1.0),
                          'notify_version' => '0',
                          'verify_sign' =>'',
                          'date_added' => 'now()',
                          'memo' => (sizeof($this->fmfErrors) > 0 ? 'FMF Details ' . print_r($this->fmfErrors, TRUE) : '{Record generated by payment module}'),
                         );
    zen_db_perform(TABLE_PAYPAL, $paypal_order);

    // Unregister the paypal session variables, making it necessary to start again for another purchase
    unset($_SESSION['paypal_ec_temp']);
    unset($_SESSION['paypal_ec_token']);
    unset($_SESSION['paypal_ec_payer_id']);
    unset($_SESSION['paypal_ec_payer_info']);
    unset($_SESSION['paypal_ec_final']);
    unset($_SESSION['paypal_ec_markflow']);
    $this->clear_3DSecure_session_vars(TRUE);
  }
1044273
def __place_order(self, token):
        
        order_id = 0
        response = None

        if not token or token['value'] == '':
            raise LendingClubError('The token parameter is False, None or unknown.')

        # Process order confirmation page
        try:
            # Place the order
            payload = {}
            if token:
                payload['struts.token.name'] = token['name']
                payload[token['name']] = token['value']
            response = self.lc.session.post('/portfolio/orderConfirmed.action', data=payload)

            # Process HTML for the order ID
            html = response.text
            soup = BeautifulSoup(html, 'html5lib')

            # Order num
            order_field = soup.find(id='order_id')
            if order_field:
                order_id = int(order_field['value'])

            # Did not find an ID
            if order_id == 0:
                self.__log('An investment order was submitted, but a confirmation ID could not be determined')
                raise LendingClubError('No order ID was found when placing the order.', response)
            else:
                return order_id

        except Exception as e:
            raise LendingClubError('Could not place the order: {0}'.format(str(e)), response)
1305286
public boolean confirmPayment(String orderNumber, String timestamp, String paid, String method, String authCode) {
		String base = new StringBuilder()
  	  .append(orderNumber)
  	  .append('|')
  	  .append(timestamp)
  	  .append('|')
  	  .append(paid)
  	  .append('|')
  	  .append(method)
  	  .append('|')
  	  .append(merchantSecret)
  	  .toString();
		
		return 
			StringUtils.equals(
				StringUtils.upperCase(DigestUtils.md5Hex(base)),
				authCode
			);
	}