=============================================================================
 Create empty payment profile
17729
def create_empty_payment_profile(user)      
      options = {
        :customer_profile_id => user.authnet_customer_profile_id.to_i,      
        :payment_profile => {
          :bill_to => { :first_name => user.first_name, :last_name => user.last_name, :address => '', :city => '', :state => '', :zip => '', :phone_number => '', :email => user.email },        
          :payment => { :credit_card => Caboose::StdClass.new({ :number => '4111111111111111', :month => 1, :year => 2020, :first_name => user.first_name, :last_name => user.last_name }) }
        }
        #, :validation_mode => :live
      }    
      resp = self.gateway.create_customer_payment_profile(options)            
      if resp.success?        
        user.authnet_payment_profile_id = resp.params['customer_payment_profile_id']        
        user.save
      else
        puts "=================================================================="            
        puts resp.message
        puts ""
        puts resp.inspect
        puts "=================================================================="
      end
    end
453125
function createAccount (commandOptions, { accountName, domainId, publicKey }) {
  return command(
    commandOptions,
    txHelper.addCommand(
      txHelper.emptyTransaction(),
      'createAccount',
      {
        accountName,
        domainId,
        publicKey
      }
    )
  )
}
863609
def create_user_profile(sender, instance, created, **kwargs):
    """"""
    if created:
        profile = UserProfile.objects.get_or_create(user=instance)[0]
        profile.hash_pass = create_htpasswd(instance.hash_pass)
        profile.save()
    else:
        # update password
        try:
            up = UserProfile.objects.get(user=instance.id)
            up.hash_pass = create_htpasswd(instance.hash_pass)
            up.save()
        except AttributeError:
            pass
262025
def __load_profile(self, profile, uuid, verbose):
        """"""

        def is_empty_profile(prf):
            return not (prf.name or prf.email or
                        prf.gender or prf.gender_acc or
                        prf.is_bot or prf.country_code)

        uid = api.unique_identities(self.db, uuid)[0]

        if profile:
            self.__create_profile(profile, uuid, verbose)
        elif is_empty_profile(uid.profile):
            self.__create_profile_from_identities(uid.identities, uuid, verbose)
        else:
            self.log("-- empty profile given for %s. Not updated" % uuid, verbose)
181305
def create(
        cls, api_key=None, idempotency_key=None, stripe_account=None, **params
    ):
        """"""
        url = cls.class_url()
        headers = populate_headers(idempotency_key)
        return make_request(
            cls, 'post', url, stripe_account=stripe_account,
            headers=headers, params=params)
800582
def delete(self):
        """"""
        response = delete_payment_profile(self.customer_profile.profile_id,
                                          self.payment_profile_id)
        response.raise_if_error()
        return super(CustomerPaymentProfile, self).delete()
765208
public function createPaymentProfile(CIMCreateCardResponse $createCardResponse)
    {
        // Parse the customer profile Id from the message
        $msg = $createCardResponse->getMessage();
        preg_match("/ID (.+) already/i", $msg, $matches);
        if (empty($matches[1])) {
            // Duplicate profile id not found. Return current response
            return $createCardResponse;
        }

        // Use the customerProfileId and create a payment profile for the customer
        $parameters = array_replace($this->getParameters(), array('customerProfileId' => $matches[1]));
        $createPaymentProfileResponse = $this->makeCreatePaymentProfileRequest($parameters);
        if ($createPaymentProfileResponse->isSuccessful()) {
            $parameters['customerPaymentProfileId'] = $createPaymentProfileResponse->getCustomerPaymentProfileId();
        } elseif ($this->getForceCardUpdate() !== true ||
            ($this->getOpaqueDataDescriptor() && $this->getOpaqueDataValue())
        ) {
            // force card update flag turned off. No need to further process.
            // also if opaque data is being used we are not able to update existing payment profiles
            return $createCardResponse;
        }

        $getProfileResponse = $this->makeGetProfileRequest($parameters);

        // Check if there is a pre-existing profile for the given card numbers.
        // For these codes we should check for duplicate payment profiles
        $otherErrorCodes = array(
            CIMGetProfileResponse::ERROR_DUPLICATE_PROFILE,
            CIMGetProfileResponse::ERROR_MAX_PAYMENT_PROFILE_LIMIT_REACHED
        );
        if (!$createPaymentProfileResponse->isSuccessful() &&
            in_array($createPaymentProfileResponse->getReasonCode(), $otherErrorCodes)
        ) {
            // There is a possibility of a duplicate payment profile, so find matching payment profile id
            // from the customer profile and update it.
            $card = $this->getCard();
            $last4 = substr($card->getNumber(), -4);

            $customerPaymentProfileId = $getProfileResponse->getMatchingPaymentProfileId($last4);

            if (!$customerPaymentProfileId) {
                // Failed. Matching customer payment profile id not found. Return the original response
                return $createCardResponse;
            }

            $parameters['customerPaymentProfileId'] = $customerPaymentProfileId;
            $updatePaymentProfileResponse = $this->makeUpdatePaymentProfileRequest($parameters);
            if (!$updatePaymentProfileResponse->isSuccessful()) {
                // Could not update payment profile. Return the original response
                return $createCardResponse;
            }
        }

        // return the updated customer profile
        $getPaymentProfileResponse = $this->makeGetPaymentProfileRequest($parameters);
        if (!$getPaymentProfileResponse->isSuccessful()) {
            // Could not get the updated customer profile. Return the original response
            return $createCardResponse;
        }

        return $getPaymentProfileResponse;
    }
364816
function _doCapt($oID, $captureType = 'Complete', $amt = 0, $currency = 'USD', $note = '') {
    global $db, $doPayPal, $messageStack;
    $doPayPal = $this->paypal_init();

    //@TODO: Read current order status and determine best status to set this to
    $new_order_status = (int)MODULE_PAYMENT_PAYPALDP_ORDER_STATUS_ID;

    $orig_order_amount = 0;
    $doPayPal = $this->paypal_init();
    $proceedToCapture = false;
    $captureNote = strip_tags(zen_db_input($_POST['captnote']));
    if (isset($_POST['captfullconfirm']) && $_POST['captfullconfirm'] == 'on') {
      $proceedToCapture = true;
    } else {
      $messageStack->add_session(MODULE_PAYMENT_PAYPALDP_TEXT_CAPTURE_FULL_CONFIRM_ERROR, 'error');
    }
    if (isset($_POST['captfinal']) && $_POST['captfinal'] == 'on') {
      $captureType = 'Complete';
    } else {
      $captureType = 'NotComplete';
    }
    if (isset($_POST['btndocapture']) && $_POST['btndocapture'] == MODULE_PAYMENT_PAYPAL_ENTRY_CAPTURE_BUTTON_TEXT_FULL) {
      $captureAmt = (float)$_POST['captamt'];
      if ($captureAmt == 0) {
        $messageStack->add_session(MODULE_PAYMENT_PAYPALDP_TEXT_INVALID_CAPTURE_AMOUNT, 'error');
        $proceedToCapture = false;
      }
    }
    // look up history on this order from PayPal table
    $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID  AND parent_txn_id = '' ";
    $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
    $zc_ppHist = $db->Execute($sql);
    if ($zc_ppHist->RecordCount() == 0) return false;
    $txnID = $zc_ppHist->fields['txn_id'];
    /**
     * Submit capture request to PayPal
     */
    if ($proceedToCapture) {
      $response = $doPayPal->DoCapture($txnID, $captureAmt, $currency, $captureType, '', $captureNote);
      $error = $this->_errorHandler($response, 'DoCapture');
      $new_order_status = ($new_order_status > 0 ? $new_order_status : 1);
      if (!$error) {
        if (isset($response['PNREF'])) {
          if (!isset($response['AMT'])) $response['AMT'] = $captureAmt;
          if (!isset($response['ORDERTIME'])) $response['ORDERTIME'] = date("M-d-Y h:i:s");
        }
        // Success, so save the results
        $sql_data_array = array('orders_id' => (int)$oID,
                                'orders_status_id' => (int)$new_order_status,
                                'date_added' => 'now()',
                                'comments' => 'FUNDS COLLECTED. Trans ID: ' . urldecode($response['TRANSACTIONID']) . $response['PNREF']. "\n" . ' Amount: ' . urldecode($response['AMT']) . ' ' . $currency . "\n" . 'Time: ' . urldecode($response['ORDERTIME']) . "\n" . (isset($response['RECEIPTID']) ? 'Receipt ID: ' . urldecode($response['RECEIPTID']) : 'Auth Code: ' . $response['AUTHCODE']) . (isset($response['PPREF']) ? "\nPPRef: " . $response['PPREF'] : '') . "\n" . $captureNote,
                                'customer_notified' => 0
                             );
        zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
        $db->Execute("update " . TABLE_ORDERS  . "
                      set orders_status = '" . (int)$new_order_status . "'
                      where orders_id = '" . (int)$oID . "'");
        $messageStack->add_session(sprintf(MODULE_PAYMENT_PAYPALDP_TEXT_CAPT_INITIATED, urldecode($response['AMT']), urldecode($response['RECEIPTID'] . $response['AUTHCODE']). $response['PNREF']), 'success');
        return true;
      }
    }
  }
460460
def sync(self):
        """"""
        output = get_profile(self.profile_id)
        output['response'].raise_if_error()
        for payment_profile in output['payment_profiles']:
            instance, created = CustomerPaymentProfile.objects.get_or_create(
                customer_profile=self,
                payment_profile_id=payment_profile['payment_profile_id']
            )
            instance.sync(payment_profile)
1217906
public static function onActivate()
    {
        // add additional field to order
        self::addOrderTable();

        // create orders payments table
        self::addOrderPaymentsTable();

        // payment comments
        self::addOrderPaymentsCommentsTable();

        self::addMissingFieldsOnUpdate();
        self::ensureCorrectFieldsEncodingOnUpdate();

        // adding record to oxPayment table
        self::addPaymentMethod();

        // enabling PayPal payment method
        self::enablePaymentMethod();

        // enable PayPal RDF
        self::enablePayPalRDFA();
    }
370266
function init()
    {
        $this->_a['table'] = 'discount_discount';
        $this->_a['verbose'] = 'Discount Entity';
        $this->_a['cols'] = array(
            'id' => array(
                'type' => 'Pluf_DB_Field_Sequence',
                'blank' => false,
                'editable' => false,
                'readable' => true
            ),
            'code' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'blank' => false,
                'size' => 25,
                'editable' => true,
                'readable' => true
            ),
            'type' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'blank' => false,
                'size' => 50,
                'editable' => true,
                'readable' => true
            ),
            'count' => array(
                'type' => 'Pluf_DB_Field_Integer',
                'blank' => true,
                'is_null' => true,
                'default' => 1,
                'editable' => true,
                'readable' => true
            ),
            'remain_count' => array(
                'type' => 'Pluf_DB_Field_Integer',
                'blank' => false,
                'default' => 0,
                'editable' => false,
                'readable' => true
            ),
            'off_value' => array(
                'type' => 'Pluf_DB_Field_Integer',
                'default' => 0,
                'editable' => true,
                'readable' => true
            ),
            'name' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'blank' => true,
                'is_null' => true,
                'size' => 250,
                'editable' => true,
                'readable' => true
            ),
            'creation_dtime' => array(
                'type' => 'Pluf_DB_Field_Datetime',
                'blank' => true,
                'editable' => false,
                'readable' => true
            ),
            'valid_day' => array(
                'type' => 'Pluf_DB_Field_Integer',
                'blank' => true,
                'is_null' => true,
                'default' => NULL,
                'editable' => true,
                'readable' => true
            ),
            'description' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'blank' => true,
                'is_null' => true,
                'size' => 250,
                'editable' => true,
                'readable' => true
            ),
            'properties' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'blank' => true,
                'is_null' => true,
                'size' => 500,
                'editable' => true,
                'readable' => true
            ),
            // relations
            'user' => array(
                'type' => 'Pluf_DB_Field_Foreignkey',
                'model' => 'User',
                'blank' => true,
                'is_null' => true,
                'relate_name' => 'user',
                'editable' => true,
                'readable' => true
            )
        );
        
        $this->_a['idx'] = array(
            'discount_idx' => array(
                'col' => 'code',
                'type' => 'unique', // normal, unique, fulltext, spatial
                'index_type' => '', // hash, btree
                'index_option' => '',
                'algorithm_option' => '',
                'lock_option' => ''
            )
        );
    }
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'];
  }
1345802
function create(callback, payee, amount, reference) {
  if(!util.isFunction(callback)) {
    throw new Error('callback must be a function');
  }

  var resource = this.coinjar.personal.api_endpoint + '/v1/payments.json',
    query = {
      payment : {}
    };

  if(payee) { query.payment.payee = payee; }
  if(amount) { query.payment.amount = amount; }
  if(reference) { query.payment.reference = reference; }

  request.post(resource)
    .auth(this.coinjar.personal.auth_token)
    .send(query)
    .end(function (response) {
      if(isResponseError(response, callback)) { return; }
      return callback(null, response.body.payment);
    });
}
295015
function paypal_init() {
    $nvp = (MODULE_PAYMENT_PAYPALWPP_APIPASSWORD != '' && MODULE_PAYMENT_PAYPALWPP_APISIGNATURE != '') ? true : false;
    $ec = ($nvp && $_GET['type'] == 'ec') ? true : false;
    if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK' && !$ec) {
      $doPayPal = new paypal_curl(array('mode' => 'payflow',
                                        'user' =>   trim(MODULE_PAYMENT_PAYPALWPP_PFUSER),
                                        'vendor' => trim(MODULE_PAYMENT_PAYPALWPP_PFVENDOR),
                                        'partner'=> trim(MODULE_PAYMENT_PAYPALWPP_PFPARTNER),
                                        'pwd' =>    trim(MODULE_PAYMENT_PAYPALWPP_PFPASSWORD),
                                        'server' => MODULE_PAYMENT_PAYPALDP_SERVER));
      $doPayPal->_endpoints = array('live'    => 'https://payflowpro.paypal.com/transaction',
                                    'sandbox' => 'https://pilot-payflowpro.paypal.com/transaction');
    } else {
      $doPayPal = new paypal_curl(array('mode' => 'nvp',
                                        'user' => trim(MODULE_PAYMENT_PAYPALWPP_APIUSERNAME),
                                        'pwd' =>  trim(MODULE_PAYMENT_PAYPALWPP_APIPASSWORD),
                                        'signature' => trim(MODULE_PAYMENT_PAYPALWPP_APISIGNATURE),
                                        'version' => '61.0',
                                        'server' => MODULE_PAYMENT_PAYPALDP_SERVER));
      $doPayPal->_endpoints = array('live'    => 'https://api-3t.paypal.com/nvp',
                                    'sandbox' => 'https://api-3t.sandbox.paypal.com/nvp');
    }

    // set logging options
    $doPayPal->_logDir = $this->_logDir;
    $doPayPal->_logLevel = $this->_logLevel;

    // set proxy options if configured
    if (CURL_PROXY_REQUIRED == 'True' && CURL_PROXY_SERVER_DETAILS != '') {
      $proxy_tunnel_flag = (defined('CURL_PROXY_TUNNEL_FLAG') && strtoupper(CURL_PROXY_TUNNEL_FLAG) == 'FALSE') ? false : true;
      $doPayPal->setCurlOption(CURLOPT_HTTPPROXYTUNNEL, $proxy_tunnel_flag);
      $doPayPal->setCurlOption(CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
      $doPayPal->setCurlOption(CURLOPT_PROXY, CURL_PROXY_SERVER_DETAILS);
    }

    // transaction processing mode
    $doPayPal->_trxtype = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'A' : 'S';

    return $doPayPal;
  }
1351176
public function create_booking_stripe_payment_post(
      VO\Integer $booking_id = null,
      VO\StringVO $transaction_id = null,
      VO\StringVO $payment_status = null

      )
    {
      $request = new Request(
          new GuzzleClient,
          $this->credentials,
          VO\HTTP\Url::fromNative($this->base_url . '/classroom/agent/book/stripe_payment'),
          new VO\HTTP\Method('POST')
      );

      $request_parameters = array();

      if (!is_null($booking_id)) {
          $request_parameters['booking_id'] = $booking_id->__toInteger();
      }

      if (!is_null($transaction_id)) {
          $request_parameters['transaction_id'] = $transaction_id->__toString();
      }

      if (!is_null($payment_status)) {
          $request_parameters['payment_status'] = $payment_status->__toString();
      }


      $response = $request->send($request_parameters);

      return $response->get_data();
    }
857697
function before_process() {
    global $order, $order_totals, $db, $messageStack, $lp_avs, $lp_trans_num;
    $myorder = array();

    // Calculate the next expected order id
    $last_order_id = $db->Execute("select * from " . TABLE_ORDERS . " order by orders_id desc limit 1");
    $new_order_id = $last_order_id->fields['orders_id'];
    $new_order_id = ($new_order_id + 1);
    // add randomized suffix to order id to produce uniqueness ... since it's unwise to submit the same order-number twice to the gateway
    $new_order_id = (string)$new_order_id . '-' . zen_create_random_value(6);

    // Build Info to send to Gateway
    $myorder["result"] = "LIVE";
    switch (MODULE_PAYMENT_LINKPOINT_API_TRANSACTION_MODE_RESPONSE) {
      case "TESTING: Successful": $myorder["result"] = "GOOD"; break;
      case "TESTING: Decline"   : $myorder["result"] = "DECLINE"; break;
      case "TESTING: Duplicate" : $myorder["result"] = "DUPLICATE"; break;
    }

    // "oid" - Order ID number must be unique. If not set, gateway will assign one.
    //$oid = zen_create_random_value(16, 'digits'); // Create a UID for the order
    $myorder["oid"] = $new_order_id; //"";    // time(); ????

    // prepare totals for submission
    $surcharges = 0;
    $creditsApplied = 0;
    global $order_totals;
    reset($order_totals);
    $myorder['subtotal'] = $myorder['tax'] = $myorder['shipping'] = $myorder['chargetotal'] = 0;
    for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
      if ($order_totals[$i]['code'] == '') continue;
      if (in_array($order_totals[$i]['code'], array('ot_total','ot_subtotal','ot_tax','ot_shipping'))) {
        if ($order_totals[$i]['code'] == 'ot_subtotal') $myorder["subtotal"]    = round($order_totals[$i]['value'],2);
        if ($order_totals[$i]['code'] == 'ot_tax')      $myorder["tax"]        += round($order_totals[$i]['value'],2);
        if ($order_totals[$i]['code'] == 'ot_shipping') $myorder["shipping"]    = round($order_totals[$i]['value'],2);
        if ($order_totals[$i]['code'] == 'ot_total')    $myorder["chargetotal"] = round($order_totals[$i]['value'],2);
      } else {
        global $$order_totals[$i]['code'];
        if (substr($order_totals[$i]['text'], 0, 1) == '-' || (isset($$order_totals[$i]['code']->credit_class) && $$order_totals[$i]['code']->credit_class == true)) {
          $creditsApplied += round($order_totals[$i]['value'],2);
        } else {
          $surcharges += round($order_totals[$i]['value'],2);
        }
      }
    }
    foreach(array('subtotal', 'tax', 'chargetotal', 'shipping') as $i) {
      if (isset($myorder[$i])) $myorder[$i] = number_format($myorder[$i], 2, '.', '');
    }

    if ($surcharges == 0 && $creditsApplied == 0 && $order->info['total'] >= $order->info['subtotal'] && sizeof($order->products) <= 20) {
    // itemized contents
      $num_line_items = 0;
      reset($order->products);
      for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
        $num_line_items++;
        $myorder["items"][$num_line_items]['id']          = $order->products[$i]['id'];

        $myorder["items"][$num_line_items]['description'] = substr(htmlentities($order->products[$i]['name'], ENT_QUOTES, 'UTF-8'), 0, 128);
        $myorder["items"][$num_line_items]['quantity']    = $order->products[$i]['qty'];
        $myorder["items"][$num_line_items]['price']       = number_format(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']), 2, '.', '');
        // check and adjust for fractional quantities, which cannot be submitted as line-item details
        $q = $order->products[$i]['qty']; $q1 = strval($q); $q2 = (int)$q; $q3 = strval($q2);
        if ($q1 != $q3 || $myorder["items"][$num_line_items]['quantity'] * $myorder["items"][$num_line_items]['price'] != number_format($order->products[$i]['qty'] * $order->products[$i]['final_price'], 2, '.', '')) {
          $myorder["items"][$num_line_items]['quantity']    = 1;
          $myorder["items"][$num_line_items]['price']       = number_format(zen_round(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']), $decimals) * $order->products[$i]['qty'], 2, '.', '');
          $myorder["items"][$num_line_items]['description'] = '(' . $order->products[$i]['qty'] . ' x )' . substr($myorder["items"][$num_line_items]['description'], 115);
        }

        if (isset($order->products[$i]['attributes'])) {
          $options_text_length = 0;
          for ($j=0, $m=sizeof($order->products[$i]['attributes']); $j<$m; $j++) {
            $options_text_length += strlen($order->products[$i]['attributes'][$j]['option'] . $order->products[$i]['attributes'][$j]['value']);
          }
          if ($options_text_length < 128) {
            for ($j=0, $m=sizeof($order->products[$i]['attributes']); $j<$m; $j++) {
              $myorder["items"][$num_line_items]['options' . $j]['name'] = substr(htmlentities($order->products[$i]['attributes'][$j]['option'], ENT_QUOTES, 'UTF-8'), 0, 128);
              $myorder["items"][$num_line_items]['options' . $j]['value'] = substr(htmlentities($order->products[$i]['attributes'][$j]['value'], ENT_QUOTES, 'UTF-8'), 0, 128);
            }
          }
        }
        // track one-time charges
        if ($order->products[$i]['onetime_charges'] != 0 ) {
          $num_line_items++;
          $myorder["items"][$num_line_items]['id']          = 'OTC';
          $myorder["items"][$num_line_items]['description'] = 'One Time Charges';
          $myorder["items"][$num_line_items]['quantity']    = 1;
          $myorder["items"][$num_line_items]['price']       = number_format(zen_add_tax($order->products[$i]['onetime_charges'], $order->products[$i]['tax']), 2, '.', '');
        }
      }
/*
        // deal with surcharges/fees
        $num_line_items++;
        $myorder["items"][$num_line_items]['id']          = 'Surcharge';
        $myorder["items"][$num_line_items]['description'] = $order_totals[$i]['title'];
        $myorder["items"][$num_line_items]['quantity']    = 1;
        $myorder["items"][$num_line_items]['price']       = number_format($order_totals[$i]['value'], 2, '.', '');
        $myorder["subtotal"] += $surcharges;
*/

     // FirstData can't accept more than 20 line-item submissions per transaction
      if ($num_line_items > 20) {
        unset($myorder["items"]);
        $num_line_items = 0;
      }
      // Verify that the line-item math works
      for ($i=1, $n=$num_line_items; $i <= $n; $i++) {
        $sum2 += ($myorder["items"][$i]['quantity'] * $myorder["items"][$i]['price']);
      }
      if (strval($sum2) != strval($myorder['subtotal'])) {
        unset($myorder['items']);
        $num_line_items = 0;
      }
    }

    // Subtotal Sanity Check in case there are addon modules affecting calculations
    $sum1 = strval($myorder['subtotal'] + $myorder['shipping'] + $myorder['tax']);
    if ($sum1 > $myorder['chargetotal']) {
      foreach(array('subtotal', 'tax', 'shipping', 'items') as $i) {
        if (isset($myorder[$i])) unset($myorder[$i]);
      }
    } elseif ($sum1 < $myorder['chargetotal']) {
      if ($num_line_items > 0 && $num_line_items < 20 && isset($myorder['items'])) {
        $num_line_items++;
        $myorder["items"][$num_line_items]['id']          = 'Adj';
        $myorder["items"][$num_line_items]['description'] = 'Rounding Adjustment';
        $myorder["items"][$num_line_items]['quantity']    = 1;
        $myorder["items"][$num_line_items]['price']       = number_format($myorder['chargetotal'] - $sum1, 2, '.', '');
        $myorder['subtotal'] += round($myorder['chargetotal'] - $sum1, 2);
        $myorder['subtotal'] = number_format($myorder['subtotal'], 2, '.', '');
      } else {
        foreach(array('subtotal', 'tax', 'shipping', 'items') as $i) {
          if (isset($myorder[$i])) unset($myorder[$i]);
        }
      }
    }
    // clean up zeros
    foreach(array('subtotal', 'tax', 'shipping') as $i) {
      if (isset($myorder[$i]) && $myorder[$i] == 0) unset($myorder[$i]);
    }

    $myorder["ip"]  = current(explode(':', str_replace(',', ':', zen_get_ip_address())));
    $myorder["ponumber"]    = "";

    // CARD INFO
    $myorder["cardnumber"]   = $_POST['cc_number'];
    $myorder["cardexpmonth"] = $_POST['cc_expires_month'];
    $myorder["cardexpyear"]  = $_POST['cc_expires_year'];
    $myorder["cvmindicator"] = "provided";
    $myorder["cvmvalue"]     = $_POST['cc_cvv'];

    // BILLING INFO
    $myorder["userid"]   = $_SESSION['customer_id'];
    $myorder["customerid"] = $_SESSION['customer_id'];
    $myorder["name"]     = htmlentities($_POST['cc_owner'], ENT_QUOTES, 'UTF-8'); //$order->billing['firstname'] . ' ' . $order->billing['lastname']);
    $myorder["company"]  = htmlentities($order->billing['company'], ENT_QUOTES, 'UTF-8');
    $myorder["address1"] = htmlentities($order->billing['street_address'], ENT_QUOTES, 'UTF-8');
    $myorder["address2"] = htmlentities($order->billing['suburb'], ENT_QUOTES, 'UTF-8');
    $myorder["city"]     = $order->billing['city'];
    $myorder["state"]    = $order->billing['state'];
    $myorder["country"]  = $order->billing['country']['iso_code_2'];
    $myorder["phone"]    = $order->customer['telephone'];
    //$myorder["fax"]      = $order->customer['fax'];
    $myorder["email"]    = $order->customer['email_address'];
    $myorder["addrnum"]  = $order->billing['street_address'];   // Required for AVS. If not provided, transactions will downgrade.
    $myorder["zip"]      = $order->billing['postcode']; // Required for AVS. If not provided, transactions will downgrade.

    // SHIPPING INFO
    $myorder["sname"]     = htmlentities($order->delivery['firstname'] . ' ' . $order->delivery['lastname'], ENT_QUOTES, 'UTF-8');
    $myorder["saddress1"] = htmlentities($order->delivery['street_address'], ENT_QUOTES, 'UTF-8');
    $myorder["saddress2"] = htmlentities($order->delivery['suburb'], ENT_QUOTES, 'UTF-8');
    $myorder["scity"]     = $order->delivery['city'];
    $myorder["sstate"]    = $order->delivery['state'];
    $myorder["szip"]      = $order->delivery['postcode'];
    $myorder["scountry"]  = $order->delivery['country']['iso_code_2'];

    // MISC
    $myorder["comments"] = "Website Order";
    // $myorder["referred"] = "";
    $myorder["ordertype"]  = (MODULE_PAYMENT_LINKPOINT_API_AUTHORIZATION_MODE == 'Authorize Only' ? 'PREAUTH': 'SALE');
    $this->payment_status = $myorder["ordertype"];

    // send request to gateway
    $result = $this->_sendRequest($myorder);

    // alert to customer if communication failure
    if (!is_array($result)) {
      $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_FAILURE_MESSAGE, 'error');
      zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
    }

    // resubmit without subtotals if subtotal error occurs
    if ($result["r_approved"] != "APPROVED" && !($result["r_approved"] == "SUBMITTED" && $result["r_message"] == 'APPROVED')) {
      if (in_array(substr($result['r_error'],0,10), array('SGS-002301', 'SGS-010503', 'SGS-005003'))) {
        foreach(array('items', 'subtotal', 'tax', 'shipping') as $i) {
          if (isset($myorder[$i])) unset($myorder[$i]);
        }
        $myorder["oid"] .= '-b';
        $myorder["chargetotal"] = ($myorder["chargetotal"] - 0.01);
        $result = $this->_sendRequest($myorder);
        if (!is_array($result)) {
          $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_FAILURE_MESSAGE, 'error');
          zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
        }
      }
    }

// PARSE Results
    $all_response_info = '';
    foreach($result as $key=>$value) {
      $all_response_info .= ' ' .$key . '='.$value;
    }
    if ($this->code_debug) $messageStack->add_session('header', $all_response_info, 'caution');

    $chargetotal = $myorder["chargetotal"];

// prepare transaction logging info
    $cust_info = '';
    $cc_number = substr($myorder["cardnumber"], 0, 4) . str_repeat('X', abs(strlen($myorder["cardnumber"]) - 8)) . substr($myorder["cardnumber"], -4);
    foreach($myorder as $key=>$value) {
      if ($key != 'cardnumber') {
        if ($key == 'cvmvalue') {
          $value = '****';
        }
        if ($key == 'cardexpmonth') {
          $cc_month = $value;
        }
        if ($key == 'cardexpyear') {
          $cc_year = $value;
        }
        if (is_array($value)) $value = print_r($value, true);
        if (!in_array($key, array('keyfile', 'configfile', 'transactionorigin', 'terminaltype', 'host', 'port'))) $cust_info .= ' ' .$key . '=' . $value . ';';
      } else {
        $cust_info .= ' ' .$key . '=' . $cc_number . ';';
      }
    }
    // store last 4 digits of CC number
//    $order->info['cc_number'] = str_repeat('X', (strlen($myorder["cardnumber"]) - 4)) . substr($myorder["cardnumber"], -4);
    // store first and last 4 digits of CC number ... which is the Visa-standards-compliant approach, same as observed by Linkpoint's services
    $order->info['cc_number'] = $cc_number;

    $order->info['cc_type'] = $_POST['cc_type'];
    $order->info['cc_owner'] = $_POST['cc_owner'];
    $order->info['cc_cvv'] = '***';
    $order->info['cc_expires'] = '';// $_POST['cc_expires'];


    $lp_trans_num = $result['r_ordernum'];
    $transaction_tax = $result['r_tax']; // The calculated tax for the order, when the ordertype is calctax.
    $transaction_shipping = $result['r_shipping']; // The calculated shipping charges for the order, when the ordertype is calcshipping.
    $this->response_codes = $result['r_avs']; // AVS Response for transaction

    // these are used to update the order-status-history upon order completion
    $this->transaction_id = $result['r_tdate'] . ' Order Number/Code: ' . $result['r_ordernum'];
    $this->auth_code = $result['r_code']; // The approval code for this transaction.

//  Store Transaction history in Database
    $sql_data_array= array(array('fieldName'=>'lp_trans_num', 'value' => $result['r_ordernum'], 'type'=>'string'), // The order number associated with this transaction.
                           array('fieldName'=>'order_id', 'value' => $result['r_ordernum'], 'type'=>'integer'),
                           array('fieldName'=>'approval_code', 'value' => $result['r_code'], 'type'=>'string'), // The approval code for this transaction.
                           array('fieldName'=>'transaction_response_time', 'value' => $result['r_time'], 'type'=>'string'), // The time+date of the transaction server response.
                           array('fieldName'=>'r_error', 'value' => $result['r_error'], 'type'=>'string'),
                           array('fieldName'=>'customer_id', 'value' => $_SESSION['customer_id'] , 'type'=>'integer'),
                           array('fieldName'=>'avs_response', 'value' => $result['r_avs'], 'type'=>'string'), // AVS Response for transaction
                           array('fieldName'=>'transaction_result', 'value' => $result['r_approved'], 'type'=>'string'), // Transaction result: APPROVED, DECLINED, or FRAUD.
                           array('fieldName'=>'message', 'value' => $result['r_message'] . "\n" . $all_response_info, 'type'=>'string'), // Any message returned by the processor; e.g., CALL VOICE CENTER.
                           array('fieldName'=>'transaction_time', 'value' => $result['r_tdate'], 'type'=>'string'), // A server time-date stamp for this transaction.
                           array('fieldName'=>'transaction_reference_number', 'value' => $result['r_ref'], 'type'=>'string'), // Reference number returned by the CC processor.
                           array('fieldName'=>'fraud_score', 'value' => $result['r_score'], 'type'=>'integer'), // LinkShield fraud risk score.
                           array('fieldName'=>'cc_number', 'value' => $cc_number, 'type'=>'string'),
                           array('fieldName'=>'cust_info', 'value' => $cust_info, 'type'=>'string'),
                           array('fieldName'=>'chargetotal', 'value' => $chargetotal, 'type'=>'string'),
                           array('fieldName'=>'cc_expire', 'value' => $cc_month . '/' . $cc_year, 'type'=>'string'),
                           array('fieldName'=>'ordertype', 'value' => $myorder['ordertype'], 'type'=>'string'), // transaction type: PREAUTH or SALE
                           array('fieldName'=>'date_added', 'value' => 'now()', 'type'=>'noquotestring'));
    if (MODULE_PAYMENT_LINKPOINT_API_STORE_DATA == 'True') {
      $db->perform(TABLE_LINKPOINT_API, $sql_data_array);
    }

  //  Begin check of specific error conditions
    if ($result["r_approved"] != "APPROVED" && !($result["r_approved"] == "SUBMITTED" && $result["r_message"] == 'APPROVED')) {
      if (substr($result['r_error'],0,10) == 'SGS-020005') $messageStack->add_session('checkout_payment', $result['r_error'], 'error');  // Error (Merchant config file is missing, empty or cannot be read)
      if (substr($result['r_error'],0,10) == 'SGS-005000') $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_GENERAL_ERROR . '<br />' . $result['r_error'], 'error'); // The server encountered a database error
      if (substr($result['r_error'],0,10) == 'SGS-000001' || strstr($result['r_error'], 'D:Declined') || strstr($result['r_error'], 'R:Referral')) $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_DECLINED_MESSAGE . '<br />' . $result['r_error'], 'error');
      if (substr($result['r_error'],0,10) == 'SGS-005005' || strstr($result['r_error'], 'Duplicate transaction')) $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_DUPLICATE_MESSAGE . '<br />' . $result['r_error'], 'error');
      if (substr($result['r_error'],0,10) == 'SGS-002301') $messageStack->add_session('checkout_payment', 'Subtotal miscalculation. Please notify the storeowner.' . '<br />' . $result['r_error'], 'error');
    }
  //  End specific error conditions

  //  Begin Transaction Status does not equal APPROVED
    if ($result["r_approved"] != "APPROVED") {
      // alert to customer:
      $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_DECLINED_MESSAGE, 'caution');
      zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
    }
  //  End Transaction Status does not equal APPROVED

    $avs_meanings = array();
    $avs_meanings['YY'] = ' - Street Address and Zip Code match.';
    $avs_meanings['YN'] = ' - Street Address matches but Zip Code does NOT match.';
    $avs_meanings['YX'] = ' - Street Address matches, but Zip Code comparison unavailable.';
    $avs_meanings['NY'] = ' - Street Address DOES NOT match, but Zip Code matches.';
    $avs_meanings['XY'] = ' - Street Address check not available, but Zip Code matches.';
    $avs_meanings['NN'] = ' - Street Address DOES NOT MATCH and Zip Code DOES NOT MATCH.';
    $avs_meanings['NX'] = ' - Street Address DOES NOT MATCH and Zip Code comparison unavailable.';
    $avs_meanings['XN'] = ' - Street Address check not available. Zip Code DOES NOT MATCH.';
    $avs_meanings['XX'] = ' - No validation for address or zip code could be performed (not available from issuing bank).';

    // Possible Fraud order. Allow transaction to process, but notify shop for owner to take appropriate action on order
    if (($result["r_approved"] == "APPROVED") && (substr($result['r_code'], 17, 2) != "YY")  && MODULE_PAYMENT_LINKPOINT_API_FRAUD_ALERT == 'Yes') {
      //DEBUG: $messageStack->add_session('header', 'possible fraud situation--> ' . $result['r_code'], 'caution');
      $message = 'Potential Fraudulent Order - Bad Address - Action Required' . "\n" .
                 'This alert occurs because the "Approval Code" below does not contain the expected YY response.' . "\n" .
                 'Thus, you might want to verify the address with the customer prior to shipping, or be sure to use Registered Mail with Signature Required in case they file a chargeback.' . "\n\n" .
                 'Customer Name: ' . $order->customer['firstname'] . ' ' . $order->customer['lastname'] . "\n\n" .
                 'AVS Result: ' . $result['r_avs'] . $avs_meanings[substr($result['r_avs'],0,2)] . "\n\n" .
                 'Order Number: ' . $lp_trans_num . "\n" .
                 'Transaction Date and Time: ' . $result['r_time'] . "\n" .
                 'Approval Code: ' . $result['r_code'] . "\n" .
                 'Reference Number: ' . $result['r_ref'] . "\n\n" .
                 'Error Message: ' . $result['r_error'] . "\n\n" .
                 'Transaction Result: ' . $result['r_approved'] . "\n\n" .
                 'Message: ' . $result['r_message'] . "\n\n" .
                 'Fraud Score: ' . ($result['r_score'] == '' ? 'Not Enabled' : $result['r_score']) . "\n\n" .
                 'AVS CODE MEANINGS: ' . "\n" .
                 'YY** = Street Address and Zip Code match.' . "\n" .
                 'YN** = Street Address matches but Zip Code does NOT match.' . "\n" .
                 'YX** = Street Address matches, but Zip Code comparison unavailable.' . "\n" .
                 'NY** = Street Address DOES NOT match, but Zip Code matches.' . "\n" .
                 'XY** = Street Address check not available, but Zip Code matches.' . "\n" .
                 'NN** = Street Address DOES NOT MATCH and Zip Code DOES NOT MATCH.' . "\n" .
                 'NX** = Street Address DOES NOT MATCH and Zip Code comparison unavailable.' . "\n" .
                 'XN** = Street Address check not available. Zip Code DOES NOT MATCH.' . "\n" .
                 'XX** = Neither validation is available.' . "\n";
      $html_msg['EMAIL_MESSAGE_HTML'] = nl2br($result['r_message']);
      zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, 'Potential Fraudulent Order - Bad Address - Action Required - ' . $lp_trans_num, $message, STORE_NAME, EMAIL_FROM, $html_msg, 'fraudalert');
    }
  // end fraud alert
  }
589222
function (opts, id) {
        let uri = this.classUrl
        if (id) {
          uri += '/' + id
        }

        if (typeof opts.data === 'function') {
          opts.next = opts.data
          opts.data = {}
        }

        // Reset payment sources
        this.payment_sources = null

        return new Promise(function (resolve, reject) {
          new Requestor({ api_version: instance.api_version }).request({
            method: 'get',
            url: [Conekta.api_base, uri].join(''),
            data: opts.data || {},
            next: function (error, response) {
              if (!error) {
                response = this.listObjectsToArray(response)
                this._json = response
                if (id) {
                  this._id = response.id
                } else {
                  _.each(response.data, (item) => {
                    const index = _.extend(
                      {
                        _json: item,
                        _id: item._id
                      },
                      this
                    )
                    this._items.push(index)
                  })
                }
                this.build_children()
              }
              if (opts.next !== undefined) {
                opts.next(error, this)
              } else {
                if (error) {
                  reject(error) 
                } else {
                  resolve(this)
                }
              }
            }.bind(this)
          })
        }.bind(this))

      }