payment processing
429139
public function doProcess()
	{

		// card errors
		$rc = $this->doProcessCards();
		if ($rc !== '00') {
			$this->payment->rc = $rc;
			$this->payment->rrn = '';
			$this->payment->irn = '';
			$this->payment->status = Status::ERROR;
			$this->payment->save();

			return;
		}

		// process type errors
		$rc = $this->doProcessType();
		if ($rc !== '00') {
			$this->payment->rc = $rc;
			$this->payment->status = Status::ERROR;
			$this->payment->save();

			return;
		}

		// auth
		$this->doDetectAuth();

		// approved
		if($this->payment->status != Status::AUTHORIZATION){
			$this->payment->status = Status::SUCCESS;
		}
		$this->payment->rc = '00';
		$this->payment->approval = mt_rand(100000, 999999);
		$this->payment->save();

	}
583699
function Payment() {
    /**
     * The subtotal value
     * @member
     */
    this.subtotal = null;
    /**
     * The total value
     * @member
     */
    this.total = null;
    /**
     * The currency value
     * @member
     */
    this.currency = null;
    /**
     * The source value
     * @member
     */
    this.source = null;
    /**
     * The error of value
     * @member
     * @type { Error }
     */
    this.error = Object.create(Error.prototype);

}
387470
function selection() {
    global $order;
    $this->cc_type_check =
            'var value = document.checkout_payment.paypalwpp_cc_type.value;' .
            'if (value == "Solo" || value == "Maestro" || value == "Switch") {' .
            '    document.checkout_payment.paypalwpp_cc_issue_month.disabled = false;' .
            '    document.checkout_payment.paypalwpp_cc_issue_year.disabled = false;' .
            '    document.checkout_payment.paypalwpp_cc_checkcode.disabled = false;' .
            '    if (document.checkout_payment.paypalwpp_cc_issuenumber) document.checkout_payment.paypalwpp_cc_issuenumber.disabled = false;' .
            '} else {' .
            '    if (document.checkout_payment.paypalwpp_cc_issuenumber) document.checkout_payment.paypalwpp_cc_issuenumber.disabled = true;' .
            '    if (document.checkout_payment.paypalwpp_cc_issue_month) document.checkout_payment.paypalwpp_cc_issue_month.disabled = true;' .
            '    if (document.checkout_payment.paypalwpp_cc_issue_year) document.checkout_payment.paypalwpp_cc_issue_year.disabled = true;' .
            '    document.checkout_payment.paypalwpp_cc_checkcode.disabled = false;' .
            '}';
    if (sizeof($this->cards) == 0) $this->cc_type_check = '';

    /**
     * since we are processing via the gateway, prepare and display the CC fields
     */
    $expires_month = array();
    $expires_year = array();
    $issue_year = array();
    for ($i = 1; $i < 13; $i++) {
      $expires_month[] = array('id' => sprintf('%02d', $i), 'text' => strftime('%B - (%m)',mktime(0,0,0,$i,1,2000)));
    }

    $today = getdate();
    for ($i = $today['year']; $i < $today['year'] + 15; $i++) {
      $expires_year[] = array('id' => strftime('%y', mktime(0,0,0,1,1,$i)), 'text' => strftime('%Y',mktime(0,0,0,1,1,$i)));
    }

    $onFocus = ' onfocus="methodSelect(\'pmt-' . $this->code . '\')"';

    $fieldsArray = array();
    $fieldsArray[] = array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_FIRSTNAME,
                           'field' => zen_draw_input_field('paypalwpp_cc_firstname', $order->billing['firstname'], 'id="'.$this->code.'-cc-ownerf"'. $onFocus . ' autocomplete="off"') .
                           '<script type="text/javascript">function paypalwpp_cc_type_check() { ' . $this->cc_type_check . ' } </script>',
                           'tag' => $this->code.'-cc-ownerf');
    $fieldsArray[] = array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_LASTNAME,
                           'field' => zen_draw_input_field('paypalwpp_cc_lastname', $order->billing['lastname'], 'id="'.$this->code.'-cc-ownerl"'. $onFocus . ' autocomplete="off"'),
                           'tag' => $this->code.'-cc-ownerl');
    if (sizeof($this->cards)>0) $fieldsArray[] = array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_TYPE,
                            'field' => zen_draw_pull_down_menu('paypalwpp_cc_type', $this->cards, '', 'onchange="paypalwpp_cc_type_check();" onblur="paypalwpp_cc_type_check();"' . 'id="'.$this->code.'-cc-type"'. $onFocus),
                           'tag' => $this->code.'-cc-type');
    $fieldsArray[] = array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_NUMBER,
                           'field' => zen_draw_input_field('paypalwpp_cc_number', $ccnum, 'id="'.$this->code.'-cc-number"' . $onFocus . ' autocomplete="off"'),
                           'tag' => $this->code.'-cc-number');
    $fieldsArray[] = array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_EXPIRES,
                           'field' => zen_draw_pull_down_menu('paypalwpp_cc_expires_month', $expires_month, strftime('%m'), 'id="'.$this->code.'-cc-expires-month"' . $onFocus) . '&nbsp;' . zen_draw_pull_down_menu('paypalwpp_cc_expires_year', $expires_year, '', 'id="'.$this->code.'-cc-expires-year"' . $onFocus),
                           'tag' => $this->code.'-cc-expires-month');
    $fieldsArray[] = array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_CHECKNUMBER,
                           'field' => zen_draw_input_field('paypalwpp_cc_checkcode', '', 'size="4" maxlength="4"' . ' id="'.$this->code.'-cc-cvv"' . $onFocus . ' autocomplete="off"') . '&nbsp;<small>' . MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_CHECKNUMBER_LOCATION . '</small><script type="text/javascript">paypalwpp_cc_type_check();</script>',
                           'tag' => $this->code.'-cc-cvv');

    $selection = array('id' => $this->code,
                       'module' => MODULE_PAYMENT_PAYPALDP_TEXT_TITLE,
                       'fields' => $fieldsArray);

    if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK' && (CC_ENABLED_MAESTRO=='1' || CC_ENABLED_SWITCH=='1' || CC_ENABLED_SOLO=='1')) {
      // add extra fields for Switch/Solo cards
      for ($i = $today['year'] - 10; $i <= $today['year']; $i++) {
        $issue_year[] = array('id' => strftime('%y',mktime(0,0,0,1,1,$i)), 'text' => strftime('%Y',mktime(0,0,0,1,1,$i)));
      }
      array_splice($selection['fields'], 4, 0,
                   array(array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_ISSUE,
                               'field' => zen_draw_pull_down_menu('paypalwpp_cc_issue_month', $expires_month, '', 'id="'.$this->code.'-cc-issue-month"' . $onFocus ) . '&nbsp;' . zen_draw_pull_down_menu('paypalwpp_cc_issue_year', $issue_year, '', 'id="'.$this->code.'-cc-issue-year"' . $onFocus),
                               'tag' => $this->code.'-cc-issue-month')));
      // add extra field for Maestro cards
      array_splice($selection['fields'], 4, 0,
                   array(array('title' => MODULE_PAYMENT_PAYPALDP_TEXT_CREDIT_CARD_MAESTRO_ISSUENUMBER,
                               'field' => zen_draw_input_field('paypalwpp_cc_issuenumber', $maestronum, 'size="4" maxlength="4"' . ' id="'.$this->code.'-cc-issuenumber"' . $onFocus . ' autocomplete="off"'),
                               'tag' => $this->code.'-cc-issuenumber')));
      // 3D-Secure
      $selection['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>',
                               'tag' => $this->code.'-cc-securetext');
    }
    return $selection;
  }
1234712
public function calculate()
    {
        $this->init();

        foreach ($this->getPaymentList() as $payment) {
            $status = $payment->getStatus();
            $action = $payment->getAction();
            $amount = $payment->getAmount();

            $this->aggregateAmounts($action, $status, $amount);
        }
    }
411971
function ec_step2_finish($paypal_ec_payer_info, $new_acct_notify) {
    global $db, $order;

    // register the payer_info in the session
    $_SESSION['paypal_ec_payer_info'] = $paypal_ec_payer_info;

    // debug
    $this->zcLog('ec_step2_finish - 1', 'START: paypal_ec_payer_info= ' . print_r($_SESSION['paypal_ec_payer_info'], true));

    /**
     * Building customer zone/address from returned data
     */
    // set some defaults, which will be updated later:
    $country_id = '223';
    $address_format_id = 2;
    $state_id = 0;
    $acct_exists = false;
    // store default address id for later use/reference
    $original_default_address_id = $_SESSION['customer_default_address_id'];

    // Get the customer's country ID based on name or ISO code
    $sql = "SELECT countries_id, address_format_id, countries_iso_code_2, countries_iso_code_3
                FROM " . TABLE_COUNTRIES . "
                WHERE countries_iso_code_2 = :countryId
                   OR countries_name = :countryId
                LIMIT 1";
    $sql1 = $db->bindVars($sql, ':countryId', $paypal_ec_payer_info['ship_country_name'], 'string');
    $country1 = $db->Execute($sql1);
    $sql2 = $db->bindVars($sql, ':countryId', $paypal_ec_payer_info['ship_country_code'], 'string');
    $country2 = $db->Execute($sql2);

    // see if we found a record, if yes, then use it instead of default American format
    if ($country1->RecordCount() > 0) {
      $country_id = $country1->fields['countries_id'];
      if (!isset($paypal_ec_payer_info['ship_country_code']) || $paypal_ec_payer_info['ship_country_code'] == '') $paypal_ec_payer_info['ship_country_code'] = $country1->fields['countries_iso_code_2'];
      $country_code3 = $country1->fields['countries_iso_code_3'];
      $address_format_id = (int)$country1->fields['address_format_id'];
    } elseif ($country2->RecordCount() > 0) {
      // if didn't find it based on name, check using ISO code (ie: in case of no-shipping-address required/supplied)
      $country_id = $country2->fields['countries_id'];
      $country_code3 = $country2->fields['countries_iso_code_3'];
      $address_format_id = (int)$country2->fields['address_format_id'];
    } else {
      // if defaulting to US, make sure US is valid
      $sql = "SELECT countries_id FROM " . TABLE_COUNTRIES . " WHERE countries_id = :countryId: LIMIT 1";
      $sql = $db->bindVars($sql, ':countryId:', $country_id, 'integer');
      $result = $db->Execute($sql);
      if ($result->EOF) {
        $this->notify('NOTIFY_PAYPAL_CUSTOMER_ATTEMPT_TO_USE_INVALID_COUNTRY_CODE');
        $this->zcLog('ec-step2-finish - 1b', 'Cannot use address due to country lookup/match failure.');
        $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_INVALID_ZONE_ERROR, true, FILENAME_SHOPPING_CART);
      }
    }
    // Need to determine zone, based on zone name first, and then zone code if name fails check. Otherwise uses 0.
    $sql = "SELECT zone_id
                  FROM " . TABLE_ZONES . "
                  WHERE zone_country_id = :zCountry
                  AND zone_code = :zoneCode
                   OR zone_name = :zoneCode
                  LIMIT 1";
    $sql = $db->bindVars($sql, ':zCountry', $country_id, 'integer');
    $sql = $db->bindVars($sql, ':zoneCode', $paypal_ec_payer_info['ship_state'], 'string');
    $states = $db->Execute($sql);
    if ($states->RecordCount() > 0) {
      $state_id = $states->fields['zone_id'];
    }
    /**
     * Using the supplied data from PayPal, set the data into the order record
     */
    // customer
    $order->customer['name']            = $paypal_ec_payer_info['payer_firstname'] . ' ' . $paypal_ec_payer_info['payer_lastname'];
    $order->customer['company']         = $paypal_ec_payer_info['payer_business'];
    $order->customer['street_address']  = $paypal_ec_payer_info['ship_street_1'];
    $order->customer['suburb']          = $paypal_ec_payer_info['ship_street_2'];
    $order->customer['city']            = $paypal_ec_payer_info['ship_city'];
    $order->customer['postcode']        = $paypal_ec_payer_info['ship_postal_code'];
    $order->customer['state']           = $paypal_ec_payer_info['ship_state'];
    $order->customer['country']         = array('id' => $country_id, 'title' => $paypal_ec_payer_info['ship_country_name'], 'iso_code_2' => $paypal_ec_payer_info['ship_country_code'], 'iso_code_3' => $country_code3);
    $order->customer['format_id']       = $address_format_id;
    $order->customer['email_address']   = $paypal_ec_payer_info['payer_email'];
    $order->customer['telephone']       = $paypal_ec_payer_info['ship_phone'];
    $order->customer['zone_id']         = $state_id;

    // billing
    $order->billing['name']             = $paypal_ec_payer_info['payer_firstname'] . ' ' . $paypal_ec_payer_info['payer_lastname'];
    $order->billing['company']          = $paypal_ec_payer_info['payer_business'];
    $order->billing['street_address']   = $paypal_ec_payer_info['ship_street_1'];
    $order->billing['suburb']           = $paypal_ec_payer_info['ship_street_2'];
    $order->billing['city']             = $paypal_ec_payer_info['ship_city'];
    $order->billing['postcode']         = $paypal_ec_payer_info['ship_postal_code'];
    $order->billing['state']            = $paypal_ec_payer_info['ship_state'];
    $order->billing['country']          = array('id' => $country_id, 'title' => $paypal_ec_payer_info['ship_country_name'], 'iso_code_2' => $paypal_ec_payer_info['ship_country_code'], 'iso_code_3' => $country_code3);
    $order->billing['format_id']        = $address_format_id;
    $order->billing['zone_id']          = $state_id;

    // delivery
    if (strtoupper($_SESSION['paypal_ec_payer_info']['ship_address_status']) != 'NONE') {
      $order->delivery['name']          = $paypal_ec_payer_info['ship_name'];
      $order->delivery['company']       = trim($paypal_ec_payer_info['ship_name'] . ' ' . $paypal_ec_payer_info['payer_business']);
      $order->delivery['street_address']= $paypal_ec_payer_info['ship_street_1'];
      $order->delivery['suburb']        = $paypal_ec_payer_info['ship_street_2'];
      $order->delivery['city']          = $paypal_ec_payer_info['ship_city'];
      $order->delivery['postcode']      = $paypal_ec_payer_info['ship_postal_code'];
      $order->delivery['state']         = $paypal_ec_payer_info['ship_state'];
      $order->delivery['country']       = array('id' => $country_id, 'title' => $paypal_ec_payer_info['ship_country_name'], 'iso_code_2' => $paypal_ec_payer_info['ship_country_code'], 'iso_code_3' => $country_code3);
      $order->delivery['country_id']    = $country_id;
      $order->delivery['format_id']     = $address_format_id;
      $order->delivery['zone_id']       = $state_id;
    }

    // process submitted customer notes
    if (isset($paypal_ec_payer_info['order_comment']) && $paypal_ec_payer_info['order_comment'] != '') {
      $_SESSION['comments'] = (isset($_SESSION['comments']) && $_SESSION['comments'] != '' ? $_SESSION['comments'] . "\n" : '') . $paypal_ec_payer_info['order_comment'];
      $order->info['comments'] = $_SESSION['comments'];
    }
    // debug
    $this->zcLog('ec_step2_finish - 2', 'country_id = ' . $country_id . ' ' . $paypal_ec_payer_info['ship_country_name'] . ' ' . $paypal_ec_payer_info['ship_country_code'] ."\naddress_format_id = " . $address_format_id . "\nstate_id = " . $state_id . ' (original state tested: ' . $paypal_ec_payer_info['ship_state'] . ')' . "\ncountry1->fields['countries_id'] = " . $country1->fields['countries_id'] . "\ncountry2->fields['countries_id'] = " . $country2->fields['countries_id'] . "\n" . '$order->customer = ' . print_r($order->customer, true));

    // check to see whether PayPal should still be offered to this customer, based on the zone of their address:
    $this->update_status();
    if (!$this->enabled) {
      $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_INVALID_ZONE_ERROR, true, FILENAME_SHOPPING_CART);
    }

    // see if the user is logged in
    if (!empty($_SESSION['customer_first_name']) && !empty($_SESSION['customer_id']) && $_SESSION['customer_id'] > 0) {
      // They're logged in, so forward them straight to checkout stages, depending on address needs etc
      $order->customer['id'] = $_SESSION['customer_id'];

      // set the session value for express checkout temp
      $_SESSION['paypal_ec_temp'] = false;

      // if no address required for shipping, leave shipping portion alone
      if (strtoupper($_SESSION['paypal_ec_payer_info']['ship_address_status']) != 'NONE' && $_SESSION['paypal_ec_payer_info']['ship_street_1'] != '') {
        // set the session info for the sendto
        $_SESSION['sendto'] = $_SESSION['customer_default_address_id'];

        // This is the address matching section
        // try to match it first
        // note: this is by no means 100%
        $address_book_id = $this->findMatchingAddressBookEntry($_SESSION['customer_id'], (isset($order->delivery) ? $order->delivery : $order->billing));

        // no match, so add the record
        if (!$address_book_id) {
          $address_book_id = $this->addAddressBookEntry($_SESSION['customer_id'], (isset($order->delivery) ? $order->delivery : $order->billing), false);
        }
        // if couldn't add the record, perhaps due to removed country, or some other error, abort with message
        if (!$address_book_id) {
          $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_INVALID_ZONE_ERROR, true, FILENAME_SHOPPING_CART);
        }

        // set the address for use
        $_SESSION['sendto'] = $address_book_id;
      }
      // set the users billto information (default address)
      if (!isset($_SESSION['billto'])) {
        $_SESSION['billto'] = $_SESSION['customer_default_address_id'];
      }

      // debug
      $this->zcLog('ec_step2_finish - 3', 'Exiting ec_step2_finish logged-in mode.' . "\n" . 'Selected address: ' . $address_book_id . "\nOriginal was: " . $original_default_address_id);


      // select a shipping method, based on cheapest available option
      if (MODULE_PAYMENT_PAYPALWPP_AUTOSELECT_CHEAPEST_SHIPPING == 'Yes') $this->setShippingMethod();

      // send the user on
      if ($_SESSION['paypal_ec_markflow'] == 1) {
        $this->terminateEC('', false, FILENAME_CHECKOUT_PROCESS);
      } else {
        $this->terminateEC('', false, FILENAME_CHECKOUT_CONFIRMATION);
      }
    } else {
      // They're not logged in.  Create an account if necessary, and then log them in.
      // First, see if they're an existing customer, and log them in automatically

      // If Paypal didn't supply us an email address, something went wrong
      if (trim($paypal_ec_payer_info['payer_email']) == '') $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_INVALID_RESPONSE, true);

      // attempt to obtain the user information using the payer_email from the info returned from PayPal, via email address
      $sql = "SELECT customers_id, customers_firstname, customers_lastname, customers_paypal_payerid, customers_paypal_ec
              FROM " . TABLE_CUSTOMERS . "
              WHERE customers_email_address = :emailAddress ";
      $sql = $db->bindVars($sql, ':emailAddress', $paypal_ec_payer_info['payer_email'], 'string');
      $check_customer = $db->Execute($sql);

      // debug
      $this->zcLog('ec_step2_finish - 4', 'Not logged in. Looking for account.' . "\n" . (int)$check_customer->RecordCount() . ' matching customer records found.');

      if (!$check_customer->EOF) {
        $acct_exists = true;

        // see if this was only a temp account -- if so, remove it
        if ($check_customer->fields['customers_paypal_ec'] == '1') {
          // Delete the existing temporary account
          $this->ec_delete_user($check_customer->fields['customers_id']);
          $acct_exists = false;

          // debug
          $this->zcLog('ec_step2_finish - 5', 'Found temporary account - deleting it.');

        }
      }

      // Create an account, if the account does not exist
      if (!$acct_exists) {

        // debug
        $this->zcLog('ec_step2_finish - 6', 'No ZC account found for this customer. Creating new account.' . "\n" . '$this->new_acct_notify =' . $this->new_acct_notify);

        // Generate a random 8-char password
        $password = zen_create_random_value(8);

        $sql_data_array = array();

        // set the customer information in the array for the table insertion
        $sql_data_array = array(
            'customers_firstname'           => $paypal_ec_payer_info['payer_firstname'],
            'customers_lastname'            => $paypal_ec_payer_info['payer_lastname'],
            'customers_email_address'       => $paypal_ec_payer_info['payer_email'],
            'customers_email_format'        => (ACCOUNT_EMAIL_PREFERENCE == '1' ? 'HTML' : 'TEXT'),
            'customers_telephone'           => $paypal_ec_payer_info['ship_phone'],
            'customers_fax'                 => '',
            'customers_gender'              => $paypal_ec_payer_info['payer_gender'],
            'customers_newsletter'          => '0',
            'customers_password'            => zen_encrypt_password($password),
            'customers_paypal_payerid'      => $_SESSION['paypal_ec_payer_id']);

        // insert the data
        $result = zen_db_perform(TABLE_CUSTOMERS, $sql_data_array);

        // grab the customer_id (last insert id)
        $customer_id = $db->Insert_ID();

        // set the Guest customer ID -- for PWA purposes
        $_SESSION['customer_guest_id'] = $customer_id;

        // set the customer address information in the array for the table insertion
        $sql_data_array = array(
            'customers_id'              => $customer_id,
            'entry_gender'              => $paypal_ec_payer_info['payer_gender'],
            'entry_firstname'           => $paypal_ec_payer_info['payer_firstname'],
            'entry_lastname'            => $paypal_ec_payer_info['payer_lastname'],
            'entry_street_address'      => $paypal_ec_payer_info['ship_street_1'],
            'entry_suburb'              => $paypal_ec_payer_info['ship_street_2'],
            'entry_city'                => $paypal_ec_payer_info['ship_city'],
            'entry_zone_id'             => $state_id,
            'entry_postcode'            => $paypal_ec_payer_info['ship_postal_code'],
            'entry_country_id'          => $country_id);
        if (isset($paypal_ec_payer_info['ship_name']) && $paypal_ec_payer_info['ship_name'] != ''  && $paypal_ec_payer_info['ship_name'] != $paypal_ec_payer_info['payer_firstname'] . ' ' . $paypal_ec_payer_info['payer_lastname']) {
          $sql_data_array['entry_company'] = $paypal_ec_payer_info['ship_name'];
        }
        if ($state_id > 0) {
          $sql_data_array['entry_zone_id'] = $state_id;
          $sql_data_array['entry_state'] = '';
        } else {
          $sql_data_array['entry_zone_id'] = 0;
          $sql_data_array['entry_state'] = $paypal_ec_payer_info['ship_state'];
        }

        // insert the data
        zen_db_perform(TABLE_ADDRESS_BOOK, $sql_data_array);

        // grab the address_id (last insert id)
        $address_id = $db->Insert_ID();

        // set the address id lookup for the customer
        $sql = "UPDATE " . TABLE_CUSTOMERS . "
                SET customers_default_address_id = :addrID
                WHERE customers_id = :custID";
        $sql = $db->bindVars($sql, ':addrID', $address_id, 'integer');
        $sql = $db->bindVars($sql, ':custID', $customer_id, 'integer');
        $db->Execute($sql);

        // insert the new customer_id into the customers info table for consistency
        $sql = "INSERT INTO " . TABLE_CUSTOMERS_INFO . "
                       (customers_info_id, customers_info_number_of_logons, customers_info_date_account_created, customers_info_date_of_last_logon)
                VALUES (:custID, 1, now(), now())";
        $sql = $db->bindVars($sql, ':custID', $customer_id, 'integer');
        $db->Execute($sql);

        // send Welcome Email if appropriate
        if ($this->new_acct_notify == 'Yes') {
          // require the language file
          global $language_page_directory, $template_dir;
          if (!isset($language_page_directory)) $language_page_directory = DIR_WS_LANGUAGES . $_SESSION['language'] . '/';
          if (file_exists($language_page_directory . $template_dir . '/create_account.php')) {
            $template_dir_select = $template_dir . '/';
          } else {
            $template_dir_select = '';
          }
          require($language_page_directory . $template_dir_select . '/create_account.php');

          // set the mail text
          $email_text = sprintf(EMAIL_GREET_NONE, $paypal_ec_payer_info['payer_firstname']) . EMAIL_WELCOME . "\n\n" . EMAIL_TEXT;
          $email_text .= "\n\n" . EMAIL_EC_ACCOUNT_INFORMATION . "\nUsername: " . $paypal_ec_payer_info['payer_email'] . "\nPassword: " . $password . "\n\n";
          $email_text .= EMAIL_CONTACT;
          // include create-account-specific disclaimer
          $email_text .= "\n\n" . sprintf(EMAIL_DISCLAIMER_NEW_CUSTOMER, STORE_OWNER_EMAIL_ADDRESS). "\n\n";
          $email_html = array();
          $email_html['EMAIL_GREETING']      = sprintf(EMAIL_GREET_NONE, $paypal_ec_payer_info['payer_firstname']) ;
          $email_html['EMAIL_WELCOME']       = EMAIL_WELCOME;
          $email_html['EMAIL_MESSAGE_HTML']  = nl2br(EMAIL_TEXT . "\n\n" . EMAIL_EC_ACCOUNT_INFORMATION . "\nUsername: " . $paypal_ec_payer_info['payer_email'] . "\nPassword: " . $password . "\n\n");
          $email_html['EMAIL_CONTACT_OWNER'] = EMAIL_CONTACT;
          $email_html['EMAIL_CLOSURE']       = nl2br(EMAIL_GV_CLOSURE);
          $email_html['EMAIL_DISCLAIMER']    = sprintf(EMAIL_DISCLAIMER_NEW_CUSTOMER, '<a href="mailto:' . STORE_OWNER_EMAIL_ADDRESS . '">'. STORE_OWNER_EMAIL_ADDRESS .' </a>');

          // send the mail
          if (trim(EMAIL_SUBJECT) != 'n/a') zen_mail($paypal_ec_payer_info['payer_firstname'] . " " . $paypal_ec_payer_info['payer_lastname'], $paypal_ec_payer_info['payer_email'], EMAIL_SUBJECT, $email_text, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, $email_html, 'welcome');

          // set the express checkout temp -- false means the account is no longer "only" for EC ... it'll be permanent
          $_SESSION['paypal_ec_temp'] = false;
        } else {
          // Make it a temporary account that'll be deleted once they've checked out
          $sql = "UPDATE " . TABLE_CUSTOMERS . "
                  SET customers_paypal_ec = 1
                  WHERE customers_id = :custID ";
          $sql = $db->bindVars($sql, ':custID', $customer_id, 'integer');
          $db->Execute($sql);

          // set the boolean ec temp value since we created account strictly for EC purposes
          $_SESSION['paypal_ec_temp'] = true;
        }

        // hook notifier class vis a vis account-creation
        $this->notify('NOTIFY_LOGIN_SUCCESS_VIA_CREATE_ACCOUNT');

      } else {
        // set the boolean ec temp value for the account to false, since we didn't have to create one
        $_SESSION['paypal_ec_temp'] = false;
      }

      // log the user in with the email sent back from paypal response
      $this->user_login($_SESSION['paypal_ec_payer_info']['payer_email'], false);

      // debug
      $this->zcLog('ec_step2_finish - 7', 'Auto-Logged customer in. (' . $_SESSION['paypal_ec_payer_info']['payer_email'] . ') (' . $_SESSION['customer_id'] . ')' . "\n" . '$_SESSION[paypal_ec_temp]=' . $_SESSION['paypal_ec_temp']);


      // This is the address matching section
      // try to match it first
      // note: this is by no means 100%
      $address_book_id = $this->findMatchingAddressBookEntry($_SESSION['customer_id'], (isset($order->delivery) ? $order->delivery : $order->billing));
      // no match add the record
      if (!$address_book_id) {
        $address_book_id = $this->addAddressBookEntry($_SESSION['customer_id'], (isset($order->delivery) ? $order->delivery : $order->billing), false);
        if (!$address_book_id) {
          $address_book_id = $_SESSION['customer_default_address_id'];
        }
      }
      // if couldn't add the record, perhaps due to removed country, or some other error, abort with message
      if ($address_book_id == FALSE) {
        $this->terminateEC(MODULE_PAYMENT_PAYPALWPP_TEXT_INVALID_ZONE_ERROR, true, FILENAME_SHOPPING_CART);
      }

      // set the sendto to the address
      $_SESSION['sendto'] = $address_book_id;
      // set billto in the session
      $_SESSION['billto'] = $_SESSION['customer_default_address_id'];

      // select a shipping method, based on cheapest available option
      if (MODULE_PAYMENT_PAYPALWPP_AUTOSELECT_CHEAPEST_SHIPPING == 'Yes') $this->setShippingMethod();

      // debug
      $this->zcLog('ec_step2_finish - 8', 'Exiting via terminateEC (from originally-not-logged-in mode).' . "\n" . 'Selected address: ' . $address_book_id . "\nOriginal was: " . (int)$original_default_address_id . "\nprepared data: " . print_r($order->customer, true));

      // send the user on
      if ($_SESSION['paypal_ec_markflow'] == 1) {
        $this->terminateEC('', false, FILENAME_CHECKOUT_PROCESS);
      } else {
        $this->terminateEC('', false, FILENAME_CHECKOUT_CONFIRMATION);
      }
    }
  }
1074464
def payment_orders
      xml do |xml|
        xml.css("paymentOrdersResult > paymentOrders > paymentOrder").map do |node|
          SubscriptionPaymentOrder.load_from_xml(node)
        end
      end
    end
3888
public function paymentSuccessful() {
    if ($this->requestHasSucceeded() && $this->requestMethod->isDirectPayment()) {
      return $this->requestMethod->getTransactionSuccessfulCode() == $this->response['resultPayment'];
    }

    return false;
  }
669686
protected function submitPayment()
    {
        if ($this->controller->isPosted('pay')) {

            $gateway = $this->getGateway();
            $gateway->setDemoMode((bool) $this->getModuleSetting('test'));
            $gateway->setCurrency($this->data_order['currency']);
            $gateway->setSecretWord($this->getModuleSetting('secretWord'));
            $gateway->setAccountNumber($this->getModuleSetting('accountNumber'));

            $cart = array(array(
                'quantity' => 1,
                'type' => 'product',
                'price' => $this->data_order['total_formatted_number'],
                'name' => $this->controller->text('Order #@num', array('@num' => $this->data_order['order_id']))
            ));

            $gateway->setCart($cart);

            $this->response = $gateway->purchase($this->getPurchaseParams())->send();

            if ($this->response->isRedirect()) {
                $this->response->redirect();
            } else if (!$this->response->isSuccessful()) {
                $this->redirectError();
            }
        }
    }
1369908
public function process()
	{
		$view = $this->getView();

		try
		{
			$context = $this->_getContext();
			$basketCtrl = Controller_Frontend_Factory::createController( $context, 'basket' );

			// only start if there's something to do
			if( ( $serviceId = $view->param( 'c-payment-option', null ) ) !== null )
			{
				$serviceCtrl = Controller_Frontend_Factory::createController( $context, 'service' );

				$attributes = $view->param( 'c-payment/' . $serviceId, array() );
				$errors = $serviceCtrl->checkServiceAttributes( 'payment', $serviceId, $attributes );

				foreach( $errors as $key => $msg )
				{
					if( $msg === null ) {
						unset( $errors[$key] );
					}
				}

				if( count( $errors ) === 0 ) {
					$basketCtrl->setService( 'payment', $serviceId, $attributes );
				} else {
					$view->standardStepActive = 'payment';
				}

				$view->paymentError = $errors;
			}


			parent::process();


			// Test if payment service is available
			$services = $basketCtrl->get()->getServices();
			if( !isset( $view->standardStepActive ) && !array_key_exists( 'payment', $services ) )
			{
				$view->standardStepActive = 'payment';
				return false;
			}
		}
		catch( Exception $e )
		{
			$view->standardStepActive = 'payment';
			throw $e;
		}
	}
1221939
public function payment(Payment $payment, &$paymentParams)
    {
        if(!$this->checkCurrency($payment->currency)){
            Yii::$app->session->setFlash(Yii::t('payment', 'The gateway does not support the current currency!'));
        } else {
            $params = [
                'cmd' => '_xclick',
                'no_shipping' => 1,
                'business' => $this->business,
                'currency_code' => $payment->currency,
                'item_name' => !empty($payment->model_id) ? $payment->model_id : '充值',
                'item_number' => $payment->id,
                'amount' => round($payment->money, 2),
                'charset' => $this->charset,
                'rm' => 2,
                'return' => $this->getReturnUrl(),
                'cancel_return' => $this->getReturnUrl(),
                'notify_url' => $this->getNoticeUrl(),
            ];

            $this->getRedirectResponse($params);
        }
    }
538630
def capture(payment, creditcard, gateway_options)
      response = request(:capture_transaction, { 'Token' => security_token(gateway_options),
                                                 'RefNum' => payment.response_code,
                                                 'Amount' => payment.amount })
      billing_response response[:capture_transaction_response][:capture_transaction_return]
    end
1010835
protected function process()
    {

        // clean-up the repositories etc. to free memory
        $this->getCustomerAddressBunchProcessor()->cleanUp();

        // temporary persist the last customer address entity ID
        $this->setLastEntityId($this->getValue(ColumnKeys::ENTITY_ID));
    }
60428
function before_process() {
    global $order, $doPayPal, $messageStack;
    $options = array();
    $optionsShip = array();
    $optionsNVP = array();

    $options = $this->getLineItemDetails($this->selectCurrency($order->info['currency']));
    if (defined('MODULE_PAYMENT_PAYPALEC_ALLOWEDPAYMENT') && MODULE_PAYMENT_PAYPALEC_ALLOWEDPAYMENT == 'Instant Only') $options['ALLOWEDPAYMENTMETHOD'] = 'InstantPaymentOnly';

    //$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();
    $this->zcLog('before_process - EC-1', 'Beginning EC mode');
     /****************************************
      * Do EC checkout
      ****************************************/
      // do not allow blank address to be sent to PayPal
      if ($_SESSION['paypal_ec_payer_info']['ship_street_1'] != '' && strtoupper($_SESSION['paypal_ec_payer_info']['ship_address_status']) != 'NONE') {
        $options = array_merge($options,
                 array('SHIPTONAME'   => $_SESSION['paypal_ec_payer_info']['ship_name'],
                       'SHIPTOSTREET' => $_SESSION['paypal_ec_payer_info']['ship_street_1'],
                       'SHIPTOSTREET2'=> $_SESSION['paypal_ec_payer_info']['ship_street_2'],
                       'SHIPTOCITY'   => $_SESSION['paypal_ec_payer_info']['ship_city'],
                       'SHIPTOSTATE'  => $_SESSION['paypal_ec_payer_info']['ship_state'],
                       'SHIPTOZIP'    => $_SESSION['paypal_ec_payer_info']['ship_postal_code'],
                       'SHIPTOCOUNTRYCODE'=> $_SESSION['paypal_ec_payer_info']['ship_country_code'],
                       ));
        $this->zcLog('before_process - EC-2', 'address overrides added:' . "\n" . print_r($options, true));
      }

      $this->zcLog('before_process - EC-3', 'address info added:' . "\n" . print_r($options, true));

      $options['BUTTONSOURCE'] = $this->buttonSourceEC;

      // If the customer has changed their shipping address,
      // override the shipping address in PayPal with the shipping
      // address that is selected in Zen Cart.
      if ($order->delivery['street_address'] != '' && $order->delivery['street_address'] != $_SESSION['paypal_ec_payer_info']['ship_street_1'] && $_SESSION['paypal_ec_payer_info']['ship_street_1'] != '') {
        $_GET['markflow'] = 2;
        if (($address_arr = $this->getOverrideAddress()) !== false) {
          // set the override var
          $options['ADDROVERRIDE'] = 1;
          // set the address info
          $options['SHIPTONAME']    = $address_arr['entry_firstname'] . ' ' . $address_arr['entry_lastname'];
          $options['SHIPTOSTREET']  = $address_arr['entry_street_address'];
          if ($address_arr['entry_suburb'] != '') $options['SHIPTOSTREET2'] = $address_arr['entry_suburb'];
          $options['SHIPTOCITY']    = $address_arr['entry_city'];
          $options['SHIPTOZIP']     = $address_arr['entry_postcode'];
          $options['SHIPTOSTATE']   = $address_arr['zone_code'];
          $options['SHIPTOCOUNTRYCODE'] = $address_arr['countries_iso_code_2'];
        }
      }
      // if these optional parameters are blank, remove them from transaction
      if (isset($options['SHIPTOSTREET2']) && trim($options['SHIPTOSTREET2']) == '') unset($options['SHIPTOSTREET2']);
      if (isset($options['SHIPTOPHONENUM']) && trim($options['SHIPTOPHONENUM']) == '') unset($options['SHIPTOPHONENUM']);

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

      // FMF support
      $options['RETURNFMFDETAILS'] = (MODULE_PAYMENT_PAYPALWPP_EC_RETURN_FMF_DETAILS == 'Yes') ? 1 : 0;

      // Add note to track that this was an EC transaction (used in properly handling update IPNs related to EC transactions):
      $options['CUSTOM'] = 'EC-' . (int)$_SESSION['customer_id'] . '-' . time();

      // send the store name as transaction identifier, to help distinguish payments between multiple stores:
      $options['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)

      $options['CURRENCY'] = $this->selectCurrency($order->info['currency']);
//      $order->info['total'] = zen_round($order->info['total'], 2);
      $order_amount = $this->calc_order_amount($order->info['total'], $options['CURRENCY'], FALSE);

      // debug output
      $this->zcLog('before_process - EC-4', 'info being submitted:' . "\n" . $_SESSION['paypal_ec_token'] . ' ' . $_SESSION['paypal_ec_payer_id'] . ' ' . number_format($order_amount, 2) .  "\n" . print_r($options, true));

      if (isset($options['DESC']) && $options['DESC'] == '') unset($options['DESC']);

      if (!isset($options['AMT'])) $options['AMT'] = number_format($order_amount, 2, '.', '');
      $response = $doPayPal->DoExpressCheckoutPayment($_SESSION['paypal_ec_token'],
                                                      $_SESSION['paypal_ec_payer_id'],
                                                      $options);

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

      // CHECK RESPONSE -- if error, actions are taken in the errorHandler
      $errorHandlerMessage = $this->_errorHandler($response, 'DoExpressCheckoutPayment');

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

      // SUCCESS
      $this->payment_type = MODULE_PAYMENT_PAYPALWPP_EC_TEXT_TYPE;
      $this->responsedata = $response;
      if ($response['PAYMENTTYPE'] != '') $this->payment_type .=  ' (' . urldecode($response['PAYMENTTYPE']) . ')';

      $this->transaction_id = trim($response['PNREF'] . ' ' . $response['TRANSACTIONID']);
      if (empty($response['PENDINGREASON']) ||
          $response['PENDINGREASON'] == 'none' ||
          $response['PENDINGREASON'] == 'completed' ||
          $response['PAYMENTSTATUS'] == 'Completed') {
        $this->payment_status = 'Completed';
        if ($this->order_status > 0) $order->info['order_status'] = $this->order_status;
      } else {
        if ($response['PAYMENTSTATUS'] == 'Pending')
        {
          if ($response['L_ERRORCODE0'] == 11610 && $response['PENDINGREASON'] == '') $response['PENDINGREASON'] = 'Pending FMF Review by Storeowner';
        }
        $this->payment_status = 'Pending (' . $response['PENDINGREASON'] . ')';
        $order->info['order_status'] = $this->order_pending_status;
      }
      $this->avs = 'N/A';
      $this->cvv2 = 'N/A';
      $this->correlationid = $response['CORRELATIONID'];
      $this->transactiontype = $response['TRANSACTIONTYPE'];
      $this->payment_time = urldecode($response['ORDERTIME']);
      $this->feeamt = urldecode($response['FEEAMT']);
      $this->taxamt = urldecode($response['TAXAMT']);
      $this->pendingreason = $response['PENDINGREASON'];
      $this->reasoncode = $response['REASONCODE'];
      $this->numitems = sizeof($order->products);
      $this->amt = urldecode($response['AMT'] . ' ' . $response['CURRENCYCODE']);
      $this->auth_code = (isset($this->response['AUTHCODE'])) ? $this->response['AUTHCODE'] : $this->response['TOKEN'];
  }
1023589
def sync(self, data):
        """"""
        for k, v in data.get('billing', {}).items():
            setattr(self, k, v)
        self.card_number = data.get('credit_card', {}).get('card_number',
                                                           self.card_number)
        self.save(sync=False)
1192223
def process_transaction(self, transaction):
        
        asset = transaction.asset
        if isinstance(asset, Future):
            try:
                old_price = self._payout_last_sale_prices[asset]
            except KeyError:
                self._payout_last_sale_prices[asset] = transaction.price
            else:
                position = self.position_tracker.positions[asset]
                amount = position.amount
                price = transaction.price

                self._cash_flow(
                    self._calculate_payout(
                        asset.price_multiplier,
                        amount,
                        old_price,
                        price,
                    ),
                )

                if amount + transaction.amount == 0:
                    del self._payout_last_sale_prices[asset]
                else:
                    self._payout_last_sale_prices[asset] = price
        else:
            self._cash_flow(-(transaction.price * transaction.amount))

        self.position_tracker.execute_transaction(transaction)

        # we only ever want the dict form from now on
        transaction_dict = transaction.to_dict()
        try:
            self._processed_transactions[transaction.dt].append(
                transaction_dict,
            )
        except KeyError:
            self._processed_transactions[transaction.dt] = [transaction_dict]
1360807
def event_payment(self, date, time, pid, commerce_id, transaction_id, request_ip, token, webpay_server):
        '''
        '''
        raise NotImplementedError("Logging Handler must implement event_payment")
1118631
def refund_payment(self):
        
        Money = MoneyMaker(self.currency)
        filter_kwargs = {
            'transaction_id__startswith': 'ch_',
            'payment_method': StripePayment.namespace,
        }
        for payment in self.orderpayment_set.filter(**filter_kwargs):
            refund = stripe.Refund.create(charge=payment.transaction_id)
            if refund['status'] == 'succeeded':
                amount = Money(refund['amount']) / Money.subunits
                OrderPayment.objects.create(order=self, amount=-amount, transaction_id=refund['id'],
                                            payment_method=StripePayment.namespace)

        del self.amount_paid  # to invalidate the cache
        if self.amount_paid:
            # proceed with other payment service providers
            super(OrderWorkflowMixin, self).refund_payment()