コード例 #1
0
 /**
  * If the visitor is not a logged in, check if the page that is being accessed is private. 
  * If so, redirect to the login page or the access denied page. 
  */
 public static function verifyPageAccessRights($pageId)
 {
     if (!Cart66Common::isLoggedIn()) {
         $privatePages = self::getPrivatePageIds();
         $deniedLink = self::getDeniedLink();
         if (in_array($pageId, $privatePages)) {
             Cart66Session::set('Cart66AccessDeniedRedirect', Cart66Common::getCurrentPageUrl());
             wp_redirect($deniedLink);
             exit;
         }
     }
 }
コード例 #2
0
 public static function logout($redirectUrl = null)
 {
     if (Cart66Session::get('Cart66AccountId')) {
         Cart66Session::drop('Cart66AccountId');
         Cart66Session::drop('Cart66AccessDeniedRedirect');
         Cart66Session::drop('Cart66ProRateAmount');
         if (isset($redirectUrl)) {
             $url = str_replace('cart66-task=logout', '', $redirectUrl);
             Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Redirecting after logout to: {$url}");
             wp_redirect($url);
             exit;
         }
     }
 }
コード例 #3
0
        protected function _buildCheckoutView($gateway)
        {
            $ssl = Cart66Setting::getValue('auth_force_ssl');
            if ($ssl) {
                if (!Cart66Common::isHttps()) {
                    $sslUrl = "https://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
                    wp_redirect($sslUrl);
                    exit;
                }
            }
            // use manual gateway form to gather user information
            require_once CART66_PATH . "/gateways/Cart66ManualGateway.php";
            $gateway = new Cart66_paymill_for_wordpress();
            if (!Cart66Session::get('Cart66Cart')) {
                Cart66Session::set('Cart66Cart', new Cart66Cart());
            }
            if (!$GLOBALS['paymill_active']) {
                paymill_load_frontend_scripts();
                // load frontend scripts
                // settings
                $GLOBALS['paymill_active'] = true;
                $cart_total = intval(Cart66Session::get('Cart66Cart')->getGrandTotal(false) * 100);
                $currency = CURRENCY_CODE;
                $no_logos = false;
                ob_start();
                // form ids
                echo '<script>
				paymill_form_checkout_id = "#Cart66_paymill_for_wordpress_form";
				paymill_form_checkout_submit_id = "#Cart66CheckoutButton";
				paymill_shop_name = "cart66";
				paymill_pcidss3 = ' . (empty($GLOBALS['paymill_settings']->paymill_general_settings['pci_dss_3']) || $GLOBALS['paymill_settings']->paymill_general_settings['pci_dss_3'] != '1' ? 1 : 0) . ';
				paymill_pcidss3_lang = "' . substr(apply_filters('plugin_locale', get_locale(), $domain), 0, 2) . '";
				</script>
				';
                require_once PAYMILL_DIR . 'lib/tpl/checkout_form.php';
                $view .= '<h2>' . __('Payment Information', 'paymill') . '</h2>';
                $view .= ob_get_clean();
                $checkout = Cart66Common::getView('views/checkout.php', array('gateway' => $gateway), true, true);
                $view .= str_replace(array('Cart66ManualGateway', 'Payment Information'), array('Cart66_paymill_for_wordpress', 'Contact Information'), $checkout);
            } else {
                $view = '<div class="paymill_notification paymill_notification_once_only"><strong>Error:</strong> Paymill can be loaded once only on the same page.</div>';
            }
            return $view;
        }
コード例 #4
0
 /**
  * Tweak rate using the tweak factor and returned tweaked rate
  */
 private function _tweakRate($rate)
 {
     $tweakedRate = $rate;
     if ($tweakFactor = Cart66Setting::getValue('rate_tweak_factor')) {
         $tweakType = Cart66Setting::getValue('rate_tweak_type');
         if ($tweakType == 'percentage') {
             $t = $tweakFactor / 100;
             $tweakedRate = $rate + $rate * $t;
         } elseif ($tweakType == 'fixed') {
             $tweakedRate = $rate + $tweakFactor;
         }
         if ($tweakedRate < 0) {
             $tweakedRate = 0;
         }
         if (!Cart66Session::get('cart66_shipping_zip')) {
             $tweakedRate = $rate;
         }
         $tweakedRate = number_format($tweakedRate, 2, '.', '');
     }
     Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] RATE TWEAKER RESULT: Rate: {$rate} ==> Tweaked Rate: {$tweakedRate}");
     return $tweakedRate;
 }
コード例 #5
0
 protected function _buildCheckoutView($gateway)
 {
     $ssl = Cart66Setting::getValue('auth_force_ssl');
     if ($ssl) {
         if (!Cart66Common::isHttps()) {
             $sslUrl = "https://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
             wp_redirect($sslUrl);
             exit;
         }
     }
     if (!Cart66Session::get('Cart66Cart')->requirePayment()) {
         require_once CART66_PATH . "/gateways/Cart66ManualGateway.php";
         $gateway = new Cart66ManualGateway();
     }
     $view = Cart66Common::getView('views/checkout.php', array('gateway' => $gateway), true, true);
     return $view;
 }
コード例 #6
0
            <input class="Cart66CheckoutButton" type="image" src='<?php 
        echo $continueImg;
        ?>
' value="<?php 
        _e('Continue', 'cart66');
        ?>
" name="Complete Order"/>
          <?php 
    } else {
        ?>
            <input id="Cart66CheckoutButton" class="Cart66ButtonPrimary Cart66CompleteOrderButton Cart66ContinueButton" type="submit"  value="<?php 
        _e('Continue', 'cart66');
        ?>
" name="Complete Order"/>
          <?php 
    }
    ?>
        </li>
    
      </ul>
  
    </form>
<?php 
} else {
    ?>
  <?php 
    // TODO: Handle account generation for membership stuff
    $total = Cart66Session::get('Cart66Cart')->getGrandTotal();
    $gateway = new Cart66Mijireh();
    $gateway->initCheckout($total);
}
コード例 #7
0
  </div>
  <h2>We are retrieving your order.  Thank you for your patience!<br>This may take a few minutes.</h2>
  <?php 
    $url = Cart66Common::appendWurlQueryString('cart66AjaxCartRequests');
    if (Cart66Common::isHttps()) {
        $url = preg_replace('/http[s]*:/', 'https:', $url);
    } else {
        $url = preg_replace('/http[s]*:/', 'http:', $url);
    }
    ?>
  <input type="hidden" name="lookup-url" id="lookup-url" value="<?php 
    echo $url;
    ?>
" />
  <input type="hidden" name="ouid" id="ouid" value="<?php 
    echo Cart66Session::get('Cart66PendingOUID');
    ?>
" />
  <input type="hidden" name="current-page" id="current-page" value="<?php 
    echo Cart66Common::getCurrentPageUrl();
    ?>
" />
  <script type="text/javascript">
    (function($){
      $(document).ready(function(){
        setInterval(function(){
          lookUpOrder();
        }, 5000);
      })
      function lookUpOrder() {
        var ajaxurl = $('#lookup-url').val();
コード例 #8
0
    Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Setting Payment Details:\n" . print_r($payment, true));
    $pp->setPaymentDetails($payment);
    // Add cart items to PayPal
    $pp->populatePayPalCartItems();
    // Set Express Checkout URLs
    $returnPage = get_page_by_path('store/express');
    $returnUrl = get_permalink($returnPage->ID);
    $cancelPage = get_page_by_path('store/checkout');
    $cancelUrl = get_permalink($cancelPage->ID);
    $localeCode = Cart66Common::getLocaleCode();
    $ecUrls = array('RETURNURL' => $returnUrl, 'CANCELURL' => $cancelUrl, 'LOCALECODE' => $localeCode);
    $pp->setEcUrls($ecUrls);
    $response = $pp->SetExpressCheckout();
    $ack = strtoupper($response['ACK']);
    if ('SUCCESS' == $ack || 'SUCCESSWITHWARNING' == $ack) {
        Cart66Session::set('PayPalProToken', $response['TOKEN']);
        $expressCheckoutUrl = $pp->getExpressCheckoutUrl($response['TOKEN']);
        wp_redirect($expressCheckoutUrl);
        exit;
    } elseif (empty($ack)) {
        echo '<pre>Failed to connect via curl to PayPal. The most likely cause is that your PHP installation failed to verify that the CA cert is OK</pre>';
    } else {
        try {
            throw new Cart66Exception(ucwords($response['L_SHORTMESSAGE0']), 66503);
        } catch (Cart66Exception $e) {
            $exception = Cart66Exception::exceptionMessages($e->getCode(), $e->getMessage(), array('Error Number: ' . $response['L_ERRORCODE0'], $response['L_LONGMESSAGE0']));
            echo Cart66Common::getView('views/error-messages.php', $exception);
        }
    }
}
?>
コード例 #9
0
                }
                ?>
                    })
                  })(jQuery);
                </script> 
          <?php 
            }
            ?>
        </li>
      <?php 
        }
        ?>
      

      <?php 
        if ($account !== false && $account->id < 1 && (Cart66Session::get('Cart66Cart')->hasSubscriptionProducts() || Cart66Session::get('Cart66Cart')->hasMembershipProducts())) {
            ?>
  	<div id="createAccountDiv">
  		<h3><?php 
            _e('Create Your Account', 'cart66');
            ?>
</h3>
  	</div>
      <ul>    
        <li>
          <label for="account-first_name"><?php 
            _e('First name', 'cart66');
            ?>
:</label><input type="text" name="account[first_name]" value="<?php 
            echo $account->firstName;
            ?>
コード例 #10
0
<?php

if (Cart66Session::get('zendesk_logout_error')) {
    ?>
    <div class="alert-message">
      <?php 
    _e('Zendesk logged you out with the following error', 'cart66');
    ?>
:<br>
      <?php 
    echo Cart66Session::get('zendesk_logout_error');
    ?>
    </div>
<?php 
    Cart66Session::drop('zendesk_logout_error');
}
if (Cart66Common::isLoggedIn()) {
    ?>
  <p>Hi <?php 
    echo $data['account']->firstName;
    ?>
. <?php 
    _e('You are currently logged in.', 'cart66');
    ?>
  
  <a href="<?php 
    echo Cart66Common::appendQueryString('cart66-task=logout');
    ?>
"><?php 
    _e('Log out', 'cart66');
    ?>
コード例 #11
0
 public function saveMijirehOrder($order_number)
 {
     global $wpdb;
     // Make sure the order is not already in the database
     $orders_table = Cart66Common::getTableName('orders');
     $sql = "select id from {$orders_table} where trans_id = %s";
     $sql = $wpdb->prepare($sql, $order_number);
     $order_id = $wpdb->get_var($sql);
     if (!$order_id) {
         // Save the order
         $order = new Cart66Order();
         $cloud_order = $this->pullOrder($order_number);
         $order_data = $this->buildOrderDataArray($cloud_order);
         Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Order data: " . print_r($order_data, true));
         $order_data = Cart66Common::deNullArrayValues($order_data);
         $order_id = $order->rawSave($order_data);
         // Save the order items
         $order_items_table = Cart66Common::getTableName('order_items');
         foreach ($cloud_order['items'] as $key => $item) {
             $product = new Cart66Product();
             $product->loadByItemNumber($item['sku']);
             $data = array('order_id' => $order_id, 'product_id' => $product->id, 'product_price' => $item['price'], 'item_number' => $item['sku'], 'description' => $item['name'], 'quantity' => $item['quantity'], 'duid' => md5($order_id . $item['sku']));
             // Look for gravity forms data
             if (isset($cloud_order['meta_data'][$key]['gforms_' . $item['sku']])) {
                 $data['form_entry_ids'] = $cloud_order['meta_data'][$key]['gforms_' . $item['sku']];
             }
             $fIds = array();
             if (isset($data['form_entry_ids'])) {
                 $fIds = explode(',', $data['form_entry_ids']);
                 if (is_array($fIds) && count($fIds)) {
                     foreach ($fIds as $entryId) {
                         if (class_exists('RGFormsModel')) {
                             if ($lead = RGFormsModel::get_lead($entryId)) {
                                 $lead['status'] = 'active';
                                 RGFormsModel::update_lead($lead);
                             }
                         }
                     }
                 }
             }
             $data = Cart66Common::deNullArrayValues($data);
             Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Trying to save this order item:" . print_r($data, true));
             $wpdb->insert($order_items_table, $data);
             $order_item_id = $wpdb->insert_id;
             // Decrement inventory after sale
             if (Cart66Setting::getValue('track_inventory') == 1) {
                 $option_info = '';
                 if (isset($cloud_order['meta_data']['options_' . $item['sku']])) {
                     $option_info = $cloud_order['meta_data']['options_' . $item['sku']];
                 }
                 Cart66Product::decrementInventory($data['product_id'], $option_info, $data['quantity']);
             }
             // Look for membership product upgrades/extensions
             if (isset($cloud_order['meta_data']['account_id']) && is_numeric($cloud_order['meta_data']['account_id'])) {
                 $order->load($order_id);
                 $account_id = $cloud_order['meta_data']['account_id'];
                 if ($mp = $order->getMembershipProduct()) {
                     $account = new Cart66Account();
                     $account->load($account_id);
                     $account->attachMembershipProduct($mp, $account->firstName, $account->lastName);
                     $order->account_id = $account->id;
                     $order->save();
                 }
             }
         }
         //update the number of redemptions for the promotion code.
         if (Cart66Session::get('Cart66Promotion')) {
             Cart66Session::get('Cart66Promotion')->updateRedemptions();
         }
         // Send email receipts
         if (CART66_PRO && CART66_EMAILS && Cart66Setting::getValue('enable_advanced_notifications') == 1) {
             $notify = new Cart66AdvancedNotifications($order_id);
             $notify->sendAdvancedEmailReceipts();
         } elseif (CART66_EMAILS) {
             $notify = new Cart66Notifications($order_id);
             $notify->sendEmailReceipts();
         }
         //Cart66Common::sendEmailReceipts($order_id);
     }
     // Redirect to receipt page
     $this->goToReceipt($order_id);
 }
コード例 #12
0
ファイル: Cart66.php プロジェクト: rbredow/allyzabbacart
 /**
  * Hide private pages and pages that require a subscription feature level the subscriber does not have
  */
 public function hidePrivatePages($excludes)
 {
     global $wpdb;
     $hidePrivate = true;
     $mySubItemNums = array();
     $activeAccount = false;
     $featureLevel = false;
     if (Cart66Common::isLoggedIn()) {
         $hidePrivate = false;
         $account = new Cart66Account(Cart66Session::get('Cart66AccountId'));
         if ($account->isActive()) {
             $activeAccount = true;
             $featureLevel = $account->getFeatureLevel();
         }
         // Optionally add the logout link to the end of the navigation
         if (Cart66Setting::getValue('auto_logout_link')) {
             add_filter('wp_list_pages', array($this, 'appendLogoutLink'));
         }
         // Hide guest only pages
         $guestOnlyPageIds = Cart66AccessManager::getGuestOnlyPageIds();
         $excludes = array_merge($excludes, $guestOnlyPageIds);
     }
     // Hide pages requiring a feature level that the subscriber does not have
     $hiddenPages = Cart66AccessManager::hideSubscriptionPages($featureLevel, $activeAccount);
     if (count($hiddenPages)) {
         $excludes = array_merge($excludes, $hiddenPages);
     }
     if ($hidePrivate) {
         // Build list of private page ids
         $privatePageIds = Cart66AccessManager::getPrivatePageIds();
         $excludes = array_merge($excludes, $privatePageIds);
     }
     // Merge private page ids with other excluded pages
     if (is_array(get_option('exclude_pages'))) {
         $excludes = array_merge(get_option('exclude_pages'), $excludes);
     }
     sort($excludes);
     return $excludes;
 }
コード例 #13
0
 protected function _setPromoFromPost()
 {
     if (isset($_POST['couponCode']) && $_POST['couponCode'] != '') {
         $couponCode = Cart66Common::postVal('couponCode');
         $this->applyPromotion($couponCode);
     } else {
         if (Cart66Session::get('Cart66Promotion')) {
             $currentPromotionCode = Cart66Session::get('Cart66PromotionCode');
             $isAutoPromo = Cart66Session::get('Cart66Promotion')->auto_apply == 1 ? true : false;
             $this->applyPromotion($currentPromotionCode, $isAutoPromo);
             if (!Cart66Session::get('Cart66Promotion')) {
                 $this->_setAutoPromoFromPost();
             }
         } else {
             $this->clearPromotion();
             $this->_setAutoPromoFromPost();
         }
     }
 }
コード例 #14
0
            echo $gfIds;
            ?>
|' />
      <?php 
            if ($shipping > 0) {
                ?>
        <input type='hidden' name='handling_cart' value='<?php 
                echo $shipping;
                ?>
' />
      <?php 
            }
            ?>
    
      <?php 
            if (Cart66Session::get('Cart66Promotion') && Cart66Session::get('Cart66Promotion')->getDiscountAmount(Cart66Session::get('Cart66Cart')) > 0) {
                ?>
        <input type='hidden' name='discount_amount_cart' value='<?php 
                echo $discount;
                ?>
'/>
      <?php 
            }
            ?>
    
      <input type='hidden' name='notify_url' value='<?php 
            echo $ipnUrl;
            ?>
'>
      <?php 
            if ($returnUrl) {
コード例 #15
0
 /**
  * Return information about pro-rated credit or false if there is none.
  * 
  * Returns a standard object:
  *   $data->description = The description of the credit
  *   $data->amount = The monetary amount of the credit
  *   $data->money = The formated monetary amount of the credit
  * 
  * return object or false
  */
 public function getProRateInfo()
 {
     $data = false;
     $proRateAmount = 0;
     if ($this->isSpreedlySubscription()) {
         if (Cart66Common::isLoggedIn() && Cart66Session::get('Cart66Cart')) {
             if ($subscriptionId = Cart66Session::get('Cart66Cart')->getSpreedlySubscriptionId()) {
                 try {
                     $invoiceData = array('subscription-plan-id' => $subscriptionId, 'subscriber' => array('customer-id' => Cart66Session::get('Cart66AccountId')));
                     $invoice = new SpreedlyInvoice();
                     $invoice->createFromArray($invoiceData);
                     $this->_creditAmount = abs((double) $invoice->invoiceData->{'line-items'}->{'line-item'}[1]->amount);
                     $data = new stdClass();
                     $data->description = $invoice->invoiceData->{'line-items'}->{'line-item'}[1]->description;
                     $data->amount = $this->_creditAmount;
                     $data->money = Cart66Common::currency($this->_creditAmount);
                     if ($data->amount > 0) {
                         $proRateAmount = $data->amount;
                     }
                     Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Spreedly Invoice: " . print_r($invoice->invoiceData, true));
                 } catch (SpreedlyException $e) {
                     Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Unable to locate spreedly customer: " . Cart66Session::get('Cart66AccountId'));
                 }
             }
         }
     }
     Cart66Session::set('Cart66ProRateAmount', $proRateAmount, true);
     return $data;
 }
コード例 #16
0
ファイル: cart.php プロジェクト: rbredow/allyzabbacart
        ?>
    <a href="<?php 
        echo Cart66Session::get('Cart66LastPage');
        ?>
" title="Continue Shopping" class="Cart66CartContinueShopping"><img alt="Continue Shopping" class="continueShoppingImg" src="<?php 
        echo $continueShoppingImg;
        ?>
" /></a>
  <?php 
    } else {
        ?>
    <a href="<?php 
        echo Cart66Session::get('Cart66LastPage');
        ?>
" class="Cart66ButtonSecondary" title="Continue Shopping"><?php 
        _e('Continue Shopping', 'cart66');
        ?>
</a>
  <?php 
    }
    ?>
  </div>
  <?php 
    if ($promotion) {
        Cart66Session::get('Cart66Cart')->clearPromotion();
    }
    Cart66Session::drop("terms_acceptance");
}
?>

コード例 #17
0
 public static function ajaxAddToCart()
 {
     $message = Cart66Session::get('Cart66Cart')->addToCart(true);
     if (!is_array($message)) {
         $message = array('msgId' => -2, 'msgHeader' => __('Error', 'cart66'), 'msg' => '<p>' . __('An error occurred while trying to add a product to the cart. Please contact the site administrator.', 'cart66') . '</p>');
     }
     echo json_encode($message);
     die;
 }
コード例 #18
0
                    }
                }
                if ($id == 'select') {
                    $method_class = "select";
                } elseif ($method_class == 'methods-country ') {
                    $method_class = 'all-countries';
                }
                ?>
                          <option class="<?php 
                echo trim($method_class);
                ?>
" value='<?php 
                echo $id;
                ?>
' <?php 
                echo $id == Cart66Session::get('Cart66Cart')->getShippingMethodId() ? 'selected' : '';
                ?>
><?php 
                echo $name;
                ?>
</option>
                          <?php 
            }
            ?>
                        </select>
                      </th>
                    </tr>
                  <?php 
        }
        ?>
                <?php 
コード例 #19
0
 public function getProductPriceDescription()
 {
     if ($this->_productId > 0) {
         $product = new Cart66Product($this->_productId);
         if ($product->isPayPalSubscription()) {
             $product = new Cart66PayPalSubscription($product->id);
             $priceDescription = $product->getPriceDescription($product->offerTrial > 0, '(trial)');
         } elseif ($product->isSpreedlySubscription()) {
             $product = new Cart66Product($product->id);
             $priceDescription = $product->getPriceDescription();
         } elseif ($product->is_user_price == 1 || $product->gravity_form_pricing) {
             $session_var_name = "userPrice_{$this->_productId}";
             if ($product->gravity_form_pricing) {
                 $session_var_name .= '_' . $this->getFirstFormEntryId();
             }
             if (Cart66Session::get($session_var_name)) {
                 $userPrice = Cart66Session::get($session_var_name);
                 if ($product->min_price > 0 && $userPrice < $product->min_price) {
                     $userPrice = $product->min_price;
                 }
                 if ($product->max_price > 0 && $userPrice > $product->max_price) {
                     $userPrice = $product->max_price;
                 }
                 $priceDescription = Cart66Common::currency($userPrice);
             } else {
                 $priceDescription = Cart66Common::currency($product->price);
             }
         } else {
             $priceDescription = $product->getPriceDescription($this->_priceDifference);
             if (is_numeric($priceDescription)) {
                 $priceDescription = Cart66Common::currency($priceDescription);
             }
         }
     }
     return $priceDescription;
 }
コード例 #20
0
 /**
  * Make sure there is at least one product in the cart.
  * Return true if the cart is valid, otherwise false.
  *
  * @return boolean
  */
 public function validateCartForCheckout()
 {
     $isValid = true;
     $itemCount = Cart66Session::get('Cart66Cart')->countItems();
     if ($itemCount < 1) {
         $this->_errors['Invalid Cart'] = __('There must be at least one item in the cart.', 'cart66');
         $isValid = false;
     }
     return $isValid;
 }
コード例 #21
0
ファイル: checkout.php プロジェクト: rbredow/allyzabbacart
include $checkoutFormFile;
$checkoutFormFileContents = ob_get_contents();
ob_end_clean();
echo Cart66Common::minifyMarkup($checkoutFormFileContents);
// Include the client side javascript validation
$same_as_billing = false;
if ($_SERVER['REQUEST_METHOD'] == 'GET' && Cart66Setting::getValue('sameAsBillingOff') != 1) {
    $same_as_billing = true;
} elseif (isset($_POST['sameAsBilling']) && $_POST['sameAsBilling'] == '1') {
    $same_as_billing = true;
}
$shipping_address_display = !$same_as_billing || $gatewayName == 'Cart66Mijireh' || $gatewayName == 'Cart662Checkout' ? 'block' : 'none';
$billing_country = '';
if (isset($b['country']) && !empty($b['country'])) {
    $billing_country = $b['country'];
    $shipping_country = isset($s['country']) ? $s['country'] : $b['country'];
}
if (Cart66Session::get('Cart66ShippingCountryCode')) {
    $billing_country = Cart66Session::get('Cart66ShippingCountryCode');
    $shipping_country = Cart66Session::get('Cart66ShippingCountryCode');
}
$error_field_names = array();
if (isset($jqErrors) && is_array($jqErrors)) {
    foreach ($jqErrors as $field_name) {
        $error_field_names[] = '#' . $field_name;
    }
}
$checkout_data = array('zones' => Cart66Common::getZones(), 'same_as_billing' => $same_as_billing, 'shipping_address_display' => $shipping_address_display, 'billing_country' => $billing_country, 'shipping_country' => $shipping_country, 'billing_state' => isset($b['state']) ? $b['state'] : '', 'shipping_state' => $s['state'], 'card_type' => isset($p['cardType']) ? $p['cardType'] : '', 'form_name' => '#' . $gatewayName . '_form', 'error_field_names' => $error_field_names, 'text_state' => __('State', 'cart66'), 'text_zip_code' => __('Zip code', 'cart66'), 'text_post_code' => __('Post code', 'cart66'), 'text_province' => __('Province', 'cart66'));
$path = CART66_URL . '/js/checkout.js';
wp_enqueue_script('checkout_js', $path, array('jquery'), false, true);
wp_localize_script('checkout_js', 'C66', $checkout_data);
コード例 #22
0
 /**
  * Save a PayPal IPN order from a Website Payments Pro cart sale.
  *
  * @param array $pp Urldecoded array of IPN key value pairs
  */
 public function saveOrder($pp)
 {
     global $wpdb;
     // NEW Parse custom value
     $referrer = false;
     $ouid = $pp['custom'];
     if (strpos($ouid, '|') !== false) {
         list($ouid, $referrer, $gfData) = explode('|', $ouid);
     }
     $order = new Cart66Order();
     $order->loadByOuid($ouid);
     if ($order->id > 0 && $order->status == 'checkout_pending') {
         $hasDigital = false;
         // Calculate subtotal
         $subtotal = 0;
         $numCartItems = $pp['num_cart_items'] > 0 ? $pp['num_cart_items'] : 1;
         for ($i = 1; $i <= $numCartItems; $i++) {
             // PayPal in not consistent in the way it passes back the item amounts
             $amt = 0;
             if (isset($pp['mc_gross' . $i])) {
                 $amt = $pp['mc_gross' . $i];
             } elseif (isset($pp['mc_gross_' . $i])) {
                 $amt = $pp['mc_gross_' . $i];
             }
             $subtotal += $amt;
         }
         $statusOptions = Cart66Common::getOrderStatusOptions();
         $status = $statusOptions[0];
         // Parse Gravity Forms ids
         $gfIds = array();
         if (!empty($gfData)) {
             $forms = explode(',', $gfData);
             foreach ($forms as $f) {
                 list($itemId, $formEntryId) = explode(':', $f);
                 $gfIds[$itemId] = $formEntryId;
             }
         }
         // Look for discount amount
         $discount = 0;
         if (isset($pp['discount'])) {
             $discount = $pp['discount'];
         }
         $data = array('bill_first_name' => $pp['first_name'], 'bill_last_name' => $pp['last_name'], 'bill_address' => $pp['address_street'], 'bill_city' => $pp['address_city'], 'bill_state' => $pp['address_state'], 'bill_zip' => $pp['address_zip'], 'bill_country' => $pp['address_country'], 'ship_first_name' => $pp['address_name'], 'ship_address' => $pp['address_street'], 'ship_city' => $pp['address_city'], 'ship_state' => $pp['address_state'], 'ship_zip' => $pp['address_zip'], 'ship_country' => $pp['address_country'], 'email' => $pp['payer_email'], 'phone' => $pp['contact_phone'], 'shipping' => $pp['mc_handling'], 'tax' => $pp['tax'], 'subtotal' => $subtotal, 'total' => $pp['mc_gross'], 'discount_amount' => $discount, 'trans_id' => $pp['txn_id'], 'ordered_on' => date('Y-m-d H:i:s', Cart66Common::localTs()), 'status' => $status);
         foreach ($data as $key => $value) {
             $data[$key] = is_null($value) ? '' : $value;
         }
         // Verify the first items in the IPN are for products managed by Cart66. It could be an IPN from some other type of transaction.
         $productsTable = Cart66Common::getTableName('products');
         $orderItemsTable = Cart66Common::getTableName('order_items');
         $sql = "SELECT id from {$productsTable} where item_number = '" . $pp['item_number1'] . "'";
         $productId = $wpdb->get_var($sql);
         if (!$productId) {
             Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] about to throw an exception, this is not an IPN that should be managed by cart66 because the item number does not match up");
             throw new Exception("This is not an IPN that should be managed by Cart66");
         }
         // Look for the 100% coupons shipping item and move it back to a shipping costs rather than a product
         if ($data['shipping'] == 0) {
             for ($i = 1; $i <= $numCartItems; $i++) {
                 $itemNumber = strtoupper($pp['item_number' . $i]);
                 if ($itemNumber == 'SHIPPING') {
                     $data['shipping'] = isset($pp['mc_gross_' . $i]) ? $pp['mc_gross_' . $i] : $pp['mc_gross' . $i];
                 }
             }
         }
         $order->setData($data);
         $order->save();
         $orderId = $order->id;
         // Handle email receipts
         if (CART66_PRO && CART66_EMAILS && Cart66Setting::getValue('enable_advanced_notifications') == 1) {
             $notify = new Cart66AdvancedNotifications($orderId);
             $notify->sendAdvancedEmailReceipts();
         } elseif (CART66_EMAILS) {
             $notify = new Cart66Notifications($orderId);
             $notify->sendEmailReceipts();
         }
         // Process affiliate reward if necessary
         if ($referrer && CART66_PRO) {
             Cart66Common::awardCommission($order->id, $referrer);
             // End processing affiliate information
             if (isset($_COOKIE['ap_id']) && $_COOKIE['ap_id']) {
                 setcookie('ap_id', $referrer, time() - 3600, "/");
                 unset($_COOKIE['ap_id']);
             }
             Cart66Session::drop('app_id');
         }
         if (CART66_PRO) {
             // Begin iDevAffiliate Tracking
             if (CART66_PRO && ($url = Cart66Setting::getValue('idevaff_url'))) {
                 require_once CART66_PATH . "/pro/idevaffiliate-award.php";
             }
             // End iDevAffiliate Tracking
         }
     } else {
         $orderTable = Cart66Common::getTableName('orders');
         // Make sure the transaction id is not already in the database
         $sql = "SELECT count(*) as c from {$orderTable} where trans_id=%s";
         $sql = $wpdb->prepare($sql, $pp['txn_id']);
         $count = $wpdb->get_var($sql);
         if ($count < 1) {
             $hasDigital = false;
             // Calculate subtotal
             $subtotal = 0;
             $numCartItems = $pp['num_cart_items'] > 0 ? $pp['num_cart_items'] : 1;
             for ($i = 1; $i <= $numCartItems; $i++) {
                 // PayPal in not consistent in the way it passes back the item amounts
                 $amt = 0;
                 if (isset($pp['mc_gross' . $i])) {
                     $amt = $pp['mc_gross' . $i];
                 } elseif (isset($pp['mc_gross_' . $i])) {
                     $amt = $pp['mc_gross_' . $i];
                 }
                 $subtotal += $amt;
             }
             $statusOptions = Cart66Common::getOrderStatusOptions();
             $status = $statusOptions[0];
             $ouid = md5($pp['txn_id'] . $pp['address_street']);
             // Parse custom value
             $referrer = false;
             $deliveryMethod = $pp['custom'];
             if (strpos($deliveryMethod, '|') !== false) {
                 list($deliveryMethod, $referrer, $gfData, $coupon) = explode('|', $deliveryMethod);
             }
             // Parse Gravity Forms ids
             $gfIds = array();
             if (!empty($gfData)) {
                 $forms = explode(',', $gfData);
                 foreach ($forms as $f) {
                     list($itemId, $formEntryId) = explode(':', $f);
                     $gfIds[$itemId] = $formEntryId;
                 }
             }
             // Look for discount amount
             $discount = 0;
             if (isset($pp['discount'])) {
                 $discount = $pp['discount'];
             }
             // Look for coupon code
             $coupon_code = "none";
             if (isset($coupon) && $coupon != "") {
                 $coupon_code = $coupon;
             }
             $data = array('bill_first_name' => $pp['first_name'], 'bill_last_name' => $pp['last_name'], 'bill_address' => $pp['address_street'], 'bill_city' => $pp['address_city'], 'bill_state' => $pp['address_state'], 'bill_zip' => $pp['address_zip'], 'bill_country' => $pp['address_country'], 'ship_first_name' => $pp['address_name'], 'ship_address' => $pp['address_street'], 'ship_city' => $pp['address_city'], 'ship_state' => $pp['address_state'], 'ship_zip' => $pp['address_zip'], 'ship_country' => $pp['address_country'], 'shipping_method' => $deliveryMethod, 'email' => $pp['payer_email'], 'phone' => $pp['contact_phone'], 'shipping' => $pp['mc_handling'], 'tax' => $pp['tax'], 'subtotal' => $subtotal, 'total' => $pp['mc_gross'], 'coupon' => $coupon_code, 'discount_amount' => $discount, 'trans_id' => $pp['txn_id'], 'ordered_on' => date('Y-m-d H:i:s', Cart66Common::localTs()), 'status' => $status, 'ouid' => $ouid);
             $data = Cart66Common::deNullArrayValues($data);
             // Verify the first items in the IPN are for products managed by Cart66. It could be an IPN from some other type of transaction.
             $productsTable = Cart66Common::getTableName('products');
             $orderItemsTable = Cart66Common::getTableName('order_items');
             $sql = "SELECT id from {$productsTable} where item_number = '" . $pp['item_number1'] . "'";
             $productId = $wpdb->get_var($sql);
             if (!$productId) {
                 throw new Exception("This is not an IPN that should be managed by Cart66");
             }
             // Look for the 100% coupons shipping item and move it back to a shipping costs rather than a product
             if ($data['shipping'] == 0) {
                 for ($i = 1; $i <= $numCartItems; $i++) {
                     $itemNumber = strtoupper($pp['item_number' . $i]);
                     if ($itemNumber == 'SHIPPING') {
                         $data['shipping'] = isset($pp['mc_gross_' . $i]) ? $pp['mc_gross_' . $i] : $pp['mc_gross' . $i];
                     }
                 }
             }
             $wpdb->insert($orderTable, $data);
             $orderId = $wpdb->insert_id;
             $product = new Cart66Product();
             for ($i = 1; $i <= $numCartItems; $i++) {
                 $sql = "SELECT id from {$productsTable} where item_number = '" . $pp['item_number' . $i] . "'";
                 $productId = $wpdb->get_var($sql);
                 if ($productId > 0) {
                     $product->load($productId);
                     // Decrement inventory
                     $info = $pp['item_name' . $i];
                     if (strpos($info, '(') > 0) {
                         $info = strrchr($info, '(');
                         $start = strpos($info, '(');
                         $end = strpos($info, ')');
                         $length = $end - $start;
                         $variation = substr($info, $start + 1, $length - 1);
                         Cart66Common::log("PayPal Variation Information: {$variation}\n{$info}");
                     }
                     $qty = $pp['quantity' . $i];
                     Cart66Product::decrementInventory($productId, $variation, $qty);
                     if ($hasDigital == false) {
                         $hasDigital = $product->isDigital();
                     }
                     // PayPal is not consistent in the way it passes back the item amounts
                     $amt = 0;
                     if (isset($pp['mc_gross' . $i])) {
                         $amt = $pp['mc_gross' . $i];
                     } elseif (isset($pp['mc_gross_' . $i])) {
                         $amt = $pp['mc_gross_' . $i] / $pp['quantity' . $i];
                     }
                     // Look for Gravity Form Entry ID
                     $formEntryId = '';
                     if (is_array($gfIds) && !empty($gfIds) && isset($gfIds[$i])) {
                         $formEntryId = $gfIds[$i];
                         if (class_exists('RGFormsModel')) {
                             if ($lead = RGFormsModel::get_lead($formEntryId)) {
                                 $lead['status'] = 'active';
                                 RGFormsModel::update_lead($lead);
                             }
                         }
                     }
                     $duid = md5($pp['txn_id'] . '-' . $orderId . '-' . $productId);
                     $data = array('order_id' => $orderId, 'product_id' => $productId, 'item_number' => $pp['item_number' . $i], 'product_price' => $amt, 'description' => $pp['item_name' . $i], 'quantity' => $pp['quantity' . $i], 'duid' => $duid, 'form_entry_ids' => $formEntryId);
                     $wpdb->insert($orderItemsTable, $data);
                 }
             }
             // Handle email receipts
             if (CART66_PRO && CART66_EMAILS && Cart66Setting::getValue('enable_advanced_notifications') == 1) {
                 $notify = new Cart66AdvancedNotifications($orderId);
                 $notify->sendAdvancedEmailReceipts();
             } elseif (CART66_EMAILS) {
                 $notify = new Cart66Notifications($orderId);
                 $notify->sendEmailReceipts();
             }
             $promotion = new Cart66Promotion();
             $promotion->loadByCode($coupon_code);
             if ($promotion) {
                 $promotion->updateRedemptions();
             }
             // Process affiliate reward if necessary
             if ($referrer) {
                 Cart66Common::awardCommission($orderId, $referrer);
             }
         }
         // end transaction id check
     }
 }
コード例 #23
0
 public function populatePayPalCartItems()
 {
     $items = Cart66Session::get('Cart66Cart')->getItems();
     // An array of Cart66CartItem objects
     $promotion = Cart66Session::get('Cart66Promotion');
     $shipping = Cart66Session::get('Cart66Cart')->getShippingCost();
     foreach ($items as $i) {
         if ($i->isPayPalSubscription()) {
             $plan = $i->getPayPalSubscription();
             $itemData = array('BILLINGAGREEMENTDESCRIPTION' => $plan->name . ' ' . str_replace('&nbsp;', ' ', strip_tags($plan->getPriceDescription($plan->offerTrial > 0, '(trial)'))));
             $this->addItem($itemData);
             $chargeAmount = $i->getProductPrice();
             if ($chargeAmount > 0) {
                 $itemData = array('NAME' => $i->getFullDisplayName(), 'AMT' => $chargeAmount, 'NUMBER' => $i->getItemNumber(), 'QTY' => $i->getQuantity());
             }
             $this->addItem($itemData);
         } else {
             $itemData = array('NAME' => $i->getFullDisplayName(), 'AMT' => $i->getProductPrice(), 'NUMBER' => $i->getItemNumber(), 'QTY' => $i->getQuantity());
             $this->addItem($itemData);
         }
     }
     // Add a coupon discount if needed
     //$discount = number_format(Cart66Session::get('Cart66Cart')->getDiscountAmount(), 2, '.', '');
     $discount = Cart66Session::get('Cart66Cart')->getDiscountAmount();
     if (is_object($promotion) && $promotion->apply_to == 'total') {
         $itemTotal = Cart66Session::get('Cart66Cart')->getNonSubscriptionAmount();
         $itemDiscount = Cart66Session::get('Cart66Cart')->getDiscountAmount();
         if ($itemDiscount > 0) {
             $itemTotal = $itemTotal - $itemDiscount;
         }
         if ($itemTotal <= 0) {
             $discount = Cart66Session::get('Cart66Cart')->getNonSubscriptionAmount();
             $shipping = $shipping + $itemTotal;
             $itemTotal = 0;
         }
     }
     if (is_object($promotion) && ($promotion->apply_to == 'products' || $promotion->apply_to == 'subtotal')) {
         $itemTotal = Cart66Session::get('Cart66Cart')->getNonSubscriptionAmount() - Cart66Session::get('Cart66Cart')->getDiscountAmount();
     }
     if (is_object($promotion) && $promotion->apply_to == 'shipping') {
         $shipping = $shipping - Cart66Session::get('Cart66Cart')->getDiscountAmount();
         $discount = 0;
     }
     if (isset($itemTotal) && $itemTotal == 0 && $shipping > 0) {
         Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] adding shipping as an item");
         $itemData = array('NAME' => 'Shipping', 'AMT' => number_format($shipping, 2, '.', ''), 'NUMBER' => 'SHIPPING', 'QTY' => '1');
         $this->addItem($itemData);
         $shipping = 0;
     }
     if ($discount > 0) {
         $negDiscount = 0 - number_format($discount, 2, '.', '');
         $itemData = array('NAME' => 'Discount', 'AMT' => $negDiscount, 'NUMBER' => 'DSC', 'QTY' => 1);
         $this->addItem($itemData);
     }
 }
コード例 #24
0
 function doSale()
 {
     // This function actually processes the payment.  This function will
     // load the $response array with all the returned information.
     // The response code values are:
     // 1 - Approved
     // 2 - Declined
     // 3 - Error
     $sale = false;
     if ($this->fields['x_amount'] > 0) {
         // Construct the fields string to pass to authorize.net
         foreach ($this->fields as $key => $value) {
             $this->field_string .= "{$key}=" . urlencode($value) . "&";
         }
         if (!Cart66Setting::getValue('disable_authorizenet_items')) {
             $items = Cart66Session::get('Cart66Cart')->getItems();
             foreach ($items as $i) {
                 $itemNumber = str_replace("\t", " ", substr($i->getItemNumber(), 0, 31));
                 $product = new Cart66Product($i->getProductId());
                 $itemName = str_replace("\t", " ", substr($product->name, 0, 31));
                 $itemOptions = str_replace("\t", " ", substr($i->getOptionInfo(), 0, 29));
                 if ($itemOptions != '') {
                     $itemOptions = '(' . $itemOptions . ')';
                 }
                 $itemQuantity = $i->getQuantity();
                 $itemTaxable = $product->taxable == 1 ? 'Y' : 'N';
                 $itemPrice = number_format($i->getProductPrice(), 2, '.', '');
                 $this->field_string .= "x_line_item=" . urlencode("{$itemNumber}<|>{$itemName}<|>{$itemOptions}<|>{$itemQuantity}<|>{$itemPrice}<|>{$itemTaxable}") . "&";
             }
         }
         Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] string: " . $this->field_string);
         // Execute the HTTPS post via CURL
         $ch = curl_init($this->gateway_url);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim($this->field_string, "& "));
         // Do not worry about checking for SSL certs
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
         $this->response_string = urldecode(curl_exec($ch));
         if (curl_errno($ch)) {
             $this->response['Response Reason Text'] = curl_error($ch);
         } else {
             curl_close($ch);
         }
         // Load a temporary array with the values returned from authorize.net
         $temp_values = explode('|', $this->response_string);
         // Load a temporary array with the keys corresponding to the values
         // returned from authorize.net (taken from AIM documentation)
         $temp_keys = array("Response Code", "Response Subcode", "Response Reason Code", "Response Reason Text", "Approval Code", "AVS Result Code", "Transaction ID", "Invoice Number", "Description", "Amount", "Method", "Transaction Type", "Customer ID", "Cardholder First Name", "Cardholder Last Name", "Company", "Billing Address", "City", "State", "Zip", "Country", "Phone", "Fax", "Email", "Ship to First Name", "Ship to Last Name", "Ship to Company", "Ship to Address", "Ship to City", "Ship to State", "Ship to Zip", "Ship to Country", "Tax Amount", "Duty Amount", "Freight Amount", "Tax Exempt Flag", "PO Number", "MD5 Hash", "Card Code (CVV2/CVC2/CID) Response Code", "Cardholder Authentication Verification Value (CAVV) Response Code");
         // Add additional keys for reserved fields and merchant defined fields
         for ($i = 0; $i <= 27; $i++) {
             array_push($temp_keys, 'Reserved Field ' . $i);
         }
         $i = 0;
         while (sizeof($temp_keys) < sizeof($temp_values)) {
             array_push($temp_keys, 'Merchant Defined Field ' . $i);
             $i++;
         }
         // combine the keys and values arrays into the $response array.  This
         // can be done with the array_combine() function instead if you are using
         // php 5.
         for ($i = 0; $i < sizeof($temp_values); $i++) {
             $this->response["{$temp_keys[$i]}"] = $temp_values[$i];
         }
         // $this->dump_response();
         // Prepare to return the transaction id for this sale.
         if (str_replace('"', "", $this->response['Response Code']) == 1) {
             $sale = str_replace('"', "", $this->response['Transaction ID']);
         }
     } else {
         // Process free orders without sending to the Auth.net gateway
         $this->response['Transaction ID'] = 'MT-' . Cart66Common::getRandString();
         $sale = $this->response['Transaction ID'];
     }
     return $sale;
 }
コード例 #25
0
<?php

$url = trim($url);
$saleAmt = $order->subtotal - $order->discount_amount;
$saleAmt = number_format($saleAmt, 2, '.', '');
$url = str_replace('idev_saleamt=XXX', 'idev_saleamt=' . $saleAmt, $url);
$url = str_replace('idev_ordernum=XXX', 'idev_ordernum=' . $order->trans_id, $url);
$ip = $_SERVER['REMOTE_ADDR'];
if ($order->ip != '') {
    $ip = $order->ip;
}
Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] order ip: {$ip}");
$url .= '&ip_address=' . $ip;
$promotionCode = Cart66Session::get('Cart66PromotionCode');
if (Cart66Setting::getValue('idev_coupon_codes') && $promotionCode) {
    $url .= '&coupon_code=' . $promotionCode;
}
Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Commission notification sent to: {$url}");
Cart66Common::curl($url);
コード例 #26
0
        if ($create_account) {
            $account->save();
            $accountId = $account->id;
            Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Just created account with id: {$accountId}");
            $product = new Cart66Product();
            $product->load($data['attrs']['product']);
            if ($product->id <= 0) {
                $product->loadByItemNumber($data['attrs']['product']);
            }
            if ($product->id > 0) {
                $account->attachMembershipProduct($product, $account->firstName, $account->lastName);
                $accountId = $account->id;
                Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Attached membership to account id: {$accountId}");
            }
            if ($account->login($acctData['username'], $acctData['password'])) {
                Cart66Session::set('Cart66AccountId', $account->id);
            }
            if (isset($data['attrs']['url'])) {
                wp_redirect($data['attrs']['url']);
                exit;
            }
        }
    }
}
$cartImgPath = Cart66Setting::getValue('cart_images_url');
if ($cartImgPath) {
    if (strpos(strrev($cartImgPath), '/') !== 0) {
        $cartImgPath .= '/';
    }
    $createAccountImgPath = $cartImgPath . 'create-account.png';
}
コード例 #27
0
 public function initCheckout($total)
 {
     Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] PayPal Pro Checkout init total: {$total}");
     $this->setCreditCardData();
     $this->setPayerInfo();
     $this->setPayerName();
     $this->setAddress();
     $this->setShipToAddress();
     // Calculate tax
     $tax = $this->getTaxAmount();
     // Calculate total cost of all items in cart, not including tax and shipping
     $itemSubTotal = Cart66Session::get('Cart66Cart')->getSubTotal() - Cart66Session::get('Cart66Cart')->getDiscountAmount() - Cart66Session::get('Cart66Cart')->getSubscriptionAmount();
     $itemTotal = number_format($itemSubTotal, 2, '.', '');
     $itemTotal = $itemTotal < 0 ? 0 : $itemTotal;
     // Calculate shipping costs
     $shipping = Cart66Session::get('Cart66Cart')->getShippingCost();
     // Set payment information
     // 'NOTIFYURL' => $ipnUrl
     $currencyCode = Cart66Setting::getValue('currency_code');
     if ($currencyCode == false) {
         $currencyCode = 'USD';
     }
     $payment = array('AMT' => $total, 'ITEMAMT' => $itemTotal, 'SHIPPINGAMT' => $shipping, 'TAXAMT' => $tax, 'CURRENCYCODE' => $currencyCode, 'BUTTONSOURCE' => 'Reality66_SP');
     // Add cart items to PayPal
     $items = Cart66Session::get('Cart66Cart')->getItems();
     // An array of Cart66CartItem objects
     foreach ($items as $i) {
         if ($i->isSpreedlySubscription()) {
             $amount = $i->getBaseProductPrice();
         } else {
             $amount = $i->getProductPrice();
         }
         $itemData = array('NAME' => $i->getFullDisplayName(), 'AMT' => $amount, 'NUMBER' => $i->getItemNumber(), 'QTY' => $i->getQuantity());
         $this->addItem($itemData);
     }
     // Add a coupon discount if needed
     $discount = Cart66Session::get('Cart66Cart')->getDiscountAmount();
     if ($discount > 0) {
         $negDiscount = 0 - $discount;
         $itemData = array('NAME' => 'Discount', 'AMT' => $negDiscount, 'NUMBER' => 'DSC', 'QTY' => 1);
         $this->addItem($itemData);
     }
     // Store the shipping price as an "item" if the item total is $0.00. Otherwise paypal will not accept the transaction.
     if ($payment['ITEMAMT'] == 0 && $payment['SHIPPINGAMT'] > 0) {
         $payment['ITEMAMT'] = $payment['SHIPPINGAMT'] + ($itemSubTotal < 0 ? $itemSubTotal : 0);
         $itemData = array('NAME' => 'Shipping', 'AMT' => $payment['SHIPPINGAMT'], 'NUMBER' => 'SHIPPING', 'QTY' => 1);
         $this->addItem($itemData);
         $payment['SHIPPINGAMT'] = 0;
     }
     $this->setPaymentDetails($payment);
 }
コード例 #28
0
 public function updatePromoRedemptions()
 {
     $promotion = Cart66Session::get('Cart66Promotion');
     $promotion->updateRedemptions();
 }
コード例 #29
0
 public function getDiscountAmount()
 {
     if (Cart66Session::get('Cart66Cart')) {
         return Cart66Session::get('Cart66Cart')->getDiscountAmount();
     }
 }
コード例 #30
0
 public function getDiscountAmount($cartObject = null, $taxed_products = false)
 {
     $p = new Cart66Product();
     //Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Running getDiscountAmount()");
     $discount = 0;
     if (!$cartObject) {
         $cartObject = Cart66Session::get('Cart66Cart');
     }
     if ($this->apply_to == "products" && !empty($cartObject)) {
         // coupon applies to products
         $products = explode(',', $this->products);
         $cartItems = $cartObject->getItems();
         Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] The number of items in the cart: " . count($cartItems));
         $usedThisOrder = 0;
         if (empty($this->products)) {
             // all products
             // apply coupon to every item in the cart
             $counter = 0;
             foreach ($cartItems as $item) {
                 $p->load($item->getProductId());
                 if (!$taxed_products || $taxed_products && $p->taxable == 1) {
                     $basePrice = $item->getBaseProductPrice();
                     $stayPositivePrice = $this->stayPositive($basePrice, $this->getAmount($basePrice));
                     $quantity = $item->getQuantity();
                     for ($i = 1; $i <= $quantity; $i++) {
                         if (empty($this->max_uses_per_order)) {
                             $discount += $stayPositivePrice;
                             Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Max uses per order is empty. Discount: {$discount}");
                         } elseif ($counter < $this->max_uses_per_order) {
                             $discount += $stayPositivePrice;
                             Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Max uses per order is NOT empty. Discount: {$discount} :: Stay Positive: {$stayPositivePrice}");
                         }
                         $counter++;
                     }
                 }
             }
         } else {
             // coupon applies to specific products
             foreach ($cartItems as $item) {
                 $p->load($item->getProductId());
                 if (!$taxed_products || $taxed_products && $p->taxable == 1) {
                     if ($this->exclude_from_products == 0) {
                         if (in_array($item->getProductId(), $products)) {
                             // add up discount
                             $itemQuantity = $item->getQuantity();
                             if ($this->max_uses_per_order > 0) {
                                 $usesRemaining = $this->max_uses_per_order - $usedThisOrder;
                                 $allowedQuantity = $usesRemaining <= $itemQuantity ? $usesRemaining : $itemQuantity;
                             } else {
                                 $allowedQuantity = $itemQuantity;
                             }
                             $productDiscount = $this->getAmount($item->getBaseProductPrice());
                             $discount += $allowedQuantity * $this->stayPositive($item->getBaseProductPrice(), $productDiscount);
                         }
                     } elseif ($this->exclude_from_products == 1) {
                         if (!in_array($item->getProductId(), $products)) {
                             // add up discount
                             $itemQuantity = $item->getQuantity();
                             if ($this->max_uses_per_order > 0) {
                                 $usesRemaining = $this->max_uses_per_order - $usedThisOrder;
                                 $allowedQuantity = $usesRemaining <= $itemQuantity ? $usesRemaining : $itemQuantity;
                             } else {
                                 $allowedQuantity = $itemQuantity;
                             }
                             $productDiscount = $this->getAmount($item->getBaseProductPrice());
                             $discount += $allowedQuantity * $this->stayPositive($item->getBaseProductPrice(), $productDiscount);
                         }
                     }
                 }
             }
         }
     }
     if ($this->apply_to == "shipping") {
         $shipping = $cartObject->getShippingCost();
         $discount = $shipping - $this->getAmount($shipping) < 0 ? $shipping : $this->getAmount($shipping);
     }
     if ($this->apply_to == "total") {
         $shipping = $cartObject->getShippingCost();
         $products = $cartObject->getSubTotal();
         $discount = $this->getAmount($shipping + $products, $shipping + $products);
     }
     if ($this->apply_to == "subtotal") {
         // coupon applies to subtotal
         $products = explode(',', $this->products);
         $cartItems = $cartObject->getItems();
         if (empty($this->products)) {
             $products = $cartObject->getSubTotal($taxed_products);
             $discount = $this->getAmount($products, $products);
         } else {
             $itemSubtotal = 0;
             // coupon applies to specific products
             foreach ($cartItems as $item) {
                 $p->load($item->getProductId());
                 if (!$taxed_products || $taxed_products && $p->taxable == 1) {
                     if ($this->exclude_from_products == 0) {
                         if (in_array($item->getProductId(), $products)) {
                             // add up discount
                             $itemSubtotal += $item->getProductPrice() * $item->getQuantity();
                         }
                     } elseif ($this->exclude_from_products == 1) {
                         if (!in_array($item->getProductId(), $products)) {
                             // add up discount
                             $itemSubtotal += $item->getProductPrice() * $item->getQuantity();
                         }
                     }
                 }
             }
             Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] item subtotal: {$itemSubtotal}");
             $discount = $this->getAmount($itemSubtotal, $itemSubtotal);
             $discount = $this->stayPositive($itemSubtotal, $discount);
         }
     }
     // format
     $discount = number_format($discount, 2, '.', '');
     return $discount;
 }