門市類型檢查.

@author		https://www.ecpay.com.tw
@category	Validate
@version		1.0.1012
433657
private function ValidateStoreType()
        {
            $Name = 'StoreType'; // 參數名稱
            $Value = $this->PostParams['StoreType']; // 參數內容
            $ClassName = 'StoreType'; // 合法資料 Class 名稱
            $AllowEmpty = false; // 是否允許空值

            if (empty($Value)) {
                // 是否允許空值
                $this->IsAllowEmpty($Name, $AllowEmpty);
            } else {
                // 內容檢查
                $this->IsLegalValue($Name, $ClassName, $Value);
            }
        }
898615
public function verify()
    {
        $data = $_POST;
        $sign = $data['sign'];
        unset($data['sign_type']);

        if (Helper::verify($data, $sign) === false) {
            throw new \Exception('支付宝异步通知验签失败');
        }

        foreach ($data as &$value) {
            $value = mb_convert_encoding($value, 'utf-8', $data['charset'] ? $data['charset'] : 'gb2312');
        }
        return $data;
    }
883534
function ec_step1() {
    global $order, $order_totals, $db, $doPayPal;

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

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

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

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

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

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

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

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

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

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

    $options['BUYEREMAILOPTINENABLE'] = 0;

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

    // this should never be reached:
    return $error;
  }
132370
public function callback(Request $request, &$paymentId, &$money, &$message, &$payId)
    {
        $receiveData = $this->filterParameter($request->post());
        if ($receiveData) {
            // 订单号
            $payId = trim($receiveData ['BillNo']);
            $paymentId = trim($receiveData ['BillNo']);
            $money = trim($receiveData ['Amount']);
            $status = trim($receiveData ['Succeed']);
            $SignMD5info = trim($receiveData ['SignMD5info']);
            // 备注
            $message = trim($receiveData ['Remark']);
            $sign = strtoupper(md5("{$paymentId}&{$money}&{$status}&{$this->md5Key}"));
            if ($sign == $SignMD5info) {
                if ($status == "88") {
                    return true;
                }
            }
        }
        return false;
    }
473588
function _check(&$data, $param)
    {
        foreach ($param as $k => $p)
        {
            if (!isset($data[$k]))
            {
                if (isset($p['require']) and $p['require'])
                {
                    self::raise('param require');
                }
                else
                {
                    continue;
                }
            }

            if (isset($p['type']))
            {
                $data[$k] = Validate::$p['type']($data[$k]);
                if ($data[$k] === false)
                {
                    self::raise();
                }

                //最小值参数
                if (isset($p['min']) and is_numeric($data[$k]) and $data[$k] < $p['min'])
                {
                    self::raise('num too small');
                }
                //最大值参数
                if (isset($p['max']) and is_numeric($data[$k]) and $data[$k] > $p['max'])
                {
                    self::raise('num too big');
                }

                //最小值参数
                if (isset($p['short']) and is_string($data[$k]) and mb_strlen($data[$k]) < $p['short'])
                {
                    self::raise('string too short');
                }
                //最大值参数
                if (isset($p['long']) and is_string($data[$k]) and mb_strlen($data[$k]) > $p['long'])
                {
                    self::raise('string too long');
                }

                //自定义的正则表达式
                if ($p['type'] == 'regx' and isset($p['regx']) and preg_match($p['regx'], $data[$k]) === false)
                {
                    self::raise();
                }
            }
        }
        //如果为拒绝模式，所有不在过滤参数$param中的键值都将被删除
        if ($this->mode == 'deny')
        {
            $allow = array_keys($param);
            $have = array_keys($data);
            foreach ($have as $ha)
            {
                if (!in_array($ha, $allow))
                {
                    unset($data[$ha]);
                }
            }
        }
    }
117309
public function verify()
    {
        $data = $_GET;
        $sign = $data['md5'];

        if (Helper::verify($data, $sign) === false) {
            throw new \Exception('盈华讯方异步通知验签失败');
        }
        return $data;
    }
237389
public function validatePayment()
    {
        $oSession = $this->_getContainer()->getSession();
        $oConfig = $this->_getContainer()->getConfig();

        //Don't do anything with order remark if we not under Amazon Pay
        if ((string)$oSession->getVariable('amazonOrderReferenceId') === ''
            || (string)$oConfig->getRequestParameter('paymentid') !== 'bestitamazon'
        ) {
            return parent::validatePayment();
        }

        // order remark
        $sOrderRemark = (string)$oConfig->getRequestParameter('order_remark', true);

        if ($sOrderRemark !== '') {
            $oSession->setVariable('ordrem', $sOrderRemark);
        } else {
            $oSession->deleteVariable('ordrem');
        }

        return parent::validatePayment();
    }
926397
public function validate(){
        if( $this->enabled && ($response = $this->input->request('g-recaptcha-response')) && $this->input->remote_ip() ){
	        $endpoint = sprintf('https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s&remoteip=%s',
		        constant(self::PRIVATE_KEY), rawurlencode($response), rawurlencode($this->input->remote_ip()));
	        $response = wp_remote_get($endpoint);
	        if( is_wp_error($response) ){
		        return false;
	        }
	        $result = json_decode($response['body']);
	        return isset($result->success) && $result->success;
        }else{
            return false;
        }
    }
501585
public function validate() {

		if ($this->getCurrency() === null) {
			throw new ValidationException("'currency' can't be null", 'currency', $this);
		}
		if ($this->getProduct() === null) {
			throw new ValidationException("'product' can't be null", 'product', $this);
		}
	}
1103992
public function enterprisePay($openid,$amount,$out_trade_no,$desc,$re_user_name=null){
        $wxpay = new PayLib\WxPayApi($this->type);
        //企业付款
        $input = new PayLib\WxPayEnterprise();
        $input->SetOpenid($openid);
        $input->SetAmount($amount);//设置商品或支付单简要描述
        $input->SetTradeNo($out_trade_no);#设置单号
        $input->SetDesc($desc);#设置支付金额

        if($re_user_name!==null){
            $input->SetCheckName('FORCE_CHECK');
            $input->SetReUserName($re_user_name);//自定义的参数
        }

        return PayLib\WxPayApi::enterprisePay($input);
    }
918439
public function validate()
    {
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            $this->_logger->log("Invalid request method", Icepay_Api_Logger::ERROR);
            return false;
        };

        $this->_logger->log(sprintf("Postback: %s", serialize($_POST)), Icepay_Api_Logger::TRANSACTION);

        /* @since version 1.0.2 */
        foreach ($this->getPostbackResponseFields() as $obj => $param) {
            $this->data->$obj = (isset($_POST[$param])) ? $_POST[$param] : "";
        }

        if ($this->isVersionCheck())
            return false;

        if (!Icepay_Parameter_Validation::merchantID($this->data->merchant)) {
            $this->_logger->log("Merchant ID is not numeric: {$this->data->merchant}", Icepay_Api_Logger::ERROR);
            return false;
        }

        if (!Icepay_Parameter_Validation::amount($this->data->amount)) {
            $this->_logger->log("Amount is not numeric: {$this->data->amount}", Icepay_Api_Logger::ERROR);
            return false;
        }

        if ($this->_merchantID != $this->data->merchant) {
            $this->_logger->log("Invalid Merchant ID: {$this->data->merchant}", Icepay_Api_Logger::ERROR);
            return false;
        }

        if (!in_array(strtoupper($this->data->status), array(
                    Icepay_StatusCode::OPEN,
                    Icepay_StatusCode::AUTHORIZED,
                    Icepay_StatusCode::SUCCESS,
                    Icepay_StatusCode::ERROR,
                    Icepay_StatusCode::REFUND,
                    Icepay_StatusCode::CHARGEBACK
                ))) {
            $this->_logger->log("Unknown status: {$this->data->status}", Icepay_Api_Logger::ERROR);
            return false;
        }

        if ($this->generateChecksumForPostback() != $this->data->checksum) {
            $this->_logger->log("Checksum does not match", Icepay_Api_Logger::ERROR);
            return false;
        }
        return true;
    }
667785
public function validate()
    {
        $steps = [
            'PrivateKey',
            'IdpMetadata',
            'SpMetadata'
        ];

        foreach ($steps as $step) {
            $method = 'validate' . $step;
            if (!$this->$method()) {
                return false;
            }
        }

        return true;
    }
485184
function validate()
  {
    if ( isset($_SESSION['securimage_code_value']) && !empty($_SESSION['securimage_code_value']) ) {
      if ( $_SESSION['securimage_code_value'] == strtolower(trim($this->code_entered)) ) {
        $this->correct_code = true;
        $_SESSION['securimage_code_value'] = '';
      } else {
        $this->correct_code = false;
      }
    } else {
      $this->correct_code = false;
    }
  }
603724
public function beginTransaction()
    {
        // auto reconnect
        $this->connect();
        
        $this->isTransaction = true;
        $this->connection->autocommit(false);//关闭自动提交
        return ;
    }
1297027
public function makeSign()
	{
		//签名步骤一：按字典序排序参数
		ksort($this->values);
		$string = $this->toUrlParams();
		//签名步骤二：在string后加入KEY
		$string = $string . '&key=' . Wxpay::getConfig('key');
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
		return $result;
	}
533206
public function callback() {
        $xml = app('request')->input();
        if (empty($xml)) {
            throw new Exception(
                __('xml error')
            );
        }
        /**
         * 禁止引用外部xml实体
         */
        $disableLibxmlEntityLoader = libxml_disable_entity_loader(true);
        $args = Xml::specialDecode($xml);
        libxml_disable_entity_loader($disableLibxmlEntityLoader);
        Factory::log()
            ->info('WECHAT PAY CALLBACK: '.app('request')->input());
        if (!is_array($args)) {
            throw new Exception(
                __('xml error')
            );
        }
        if ($args['return_code'] != 'SUCCESS') {
            throw new Exception($args['return_msg']);
        }
        if (!$this->verify($args)) {
            throw new Exception(
                __('verify sign error')
            );
        }
        return $args;
    }
703546
private function ValidateDevice($AllowEmpty = false)
        {
            $Name = 'Device'; // 參數名稱
            $Value = $this->PostParams['Device']; // 參數內容
            $ClassName = 'Device'; // 合法資料 Class 名稱

            if (empty($Value)) {
                // 是否允許空值
                $this->IsAllowEmpty($Name, $AllowEmpty);
            } else {
                // 資料型態檢查
                $this->IsInteger($Name, $Value);

                // 內容檢查
                $this->IsLegalValue($Name, $ClassName, $Value);
            }
        }