public function initContent() { $this->display_column_left = false; include_once _PS_MODULE_DIR_ . 'gcheckout/gcheckout.php'; include_once _PS_MODULE_DIR_ . 'gcheckout/library/googlecart.php'; include_once _PS_MODULE_DIR_ . 'gcheckout/library/googleitem.php'; include_once _PS_MODULE_DIR_ . 'gcheckout/library/googleshipping.php'; parent::initContent(); $gcheckout = new GCheckout(); /*if (_PS_VERSION_ >= '1.5' && !Context::getContext()->customer->isLogged(true)) Tools::redirect('index.php?co:q:q:qntroller=authentication&back=order.php'); else if (_PS_VERSION_ < '1.5' && !$cookie->isLogged(true)) Tools::redirect('authentication.php?back=order.php'); else if (!$gcheckout->context->cart->getOrderTotal(true, Cart::BOTH)) Tools::displayError('Error: Empty cart');*/ // Prepare payment $currency = $gcheckout->getCurrency($this->context->cart->id_currency); if ($this->context->cart->id_currency != $currency->id) { $this->context->cart->id_currency = (int) $currency->id; $this->context->cookie->id_currency = (int) $this->context->cart->id_currency; $this->context->cart->update(); //Tools::redirect('modules/'.$this->name.'/payment.php'); Tools::redirect($link->getModuleLink('gcheckout', 'payment')); } $googleCart = new GoogleCart(Configuration::get('GCHECKOUT_MERCHANT_ID'), Configuration::get('GCHECKOUT_MERCHANT_KEY'), Configuration::get('GCHECKOUT_MODE'), $currency->iso_code); foreach ($this->context->cart->getProducts() as $product) { $googleCart->AddItem(new GoogleItem(utf8_decode($product['name'] . ((isset($product['attributes']) and !empty($product['attributes'])) ? ' - ' . $product['attributes'] : '')), utf8_decode($product['description_short']), (int) $product['cart_quantity'], $product['price_wt'], strtoupper(Configuration::get('PS_WEIGHT_UNIT')), (double) $product['weight'])); } if ($wrapping = $this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING)) { $googleCart->AddItem(new GoogleItem(utf8_decode($this->l('Wrapping')), '', 1, $wrapping)); } if (_PS_VERSION_ < '1.5') { foreach ($this->context->cart->getDiscounts() as $voucher) { $googleCart->AddItem(new GoogleItem(utf8_decode($voucher['name']), utf8_decode($voucher['description']), 1, '-' . $voucher['value_real'])); } } else { foreach ($this->context->cart->getCartRules() as $cart_tule) { $googleCart->AddItem(new GoogleItem(utf8_decode($cart_tule['code']), utf8_decode($cart_tule['name']), 1, '-' . $cart_tule['value_real'])); } } if (!Configuration::get('GCHECKOUT_NO_SHIPPING')) { $carrier = new Carrier((int) $this->context->cart->id_carrier, $this->context->language->id); $googleCart->AddShipping(new GoogleFlatRateShipping(utf8_decode($carrier->name), $this->context->cart->getOrderShippingCost($this->context->cart->id_carrier))); } $googleCart->SetEditCartUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'order.php'); $googleCart->SetContinueShoppingUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'order-confirmation.php'); $googleCart->SetRequestBuyerPhone(false); $googleCart->SetMerchantPrivateData($this->context->cart->id . '|' . $this->context->cart->secure_key); $total = $this->context->cart->getOrderTotal(); $this->context->smarty->assign(array('googleCheckoutExtraForm' => $googleCart->CheckoutButtonCode(), 'total' => $total, 'googleTotal' => $total, 'GC_Link' => $this->context->link->getPageLink('order', true, NULL))); $this->setTemplate('confirm.tpl'); }
function hookPayment($params) { if (!$this->active) { return; } global $smarty; require_once 'library/googlecart.php'; require_once 'library/googleitem.php'; require_once 'library/googleshipping.php'; $currency = $this->getCurrency(); $googleCart = new GoogleCart(Configuration::get('GCHECKOUT_MERCHANT_ID'), Configuration::get('GCHECKOUT_MERCHANT_KEY'), Configuration::get('GCHECKOUT_MODE'), $currency->iso_code); foreach ($params['cart']->getProducts() as $product) { $googleCart->AddItem(new GoogleItem(utf8_decode($product['name']), utf8_decode($product['description_short']), intval($product['quantity']), Tools::convertPrice($product['price_wt'], $currency))); } if ($wrapping = $params['cart']->getOrderTotal(true, 6)) { $googleCart->AddItem(new GoogleItem(utf8_decode($this->l('Wrapping')), '', 1, Tools::convertPrice($wrapping, $currency))); } foreach ($params['cart']->getDiscounts() as $voucher) { $googleCart->AddItem(new GoogleItem(utf8_decode($voucher['name']), utf8_decode($voucher['description']), 1, '-' . Tools::convertPrice($voucher['value_real'], $currency))); } $googleCart->AddShipping(new GooglePickUp($this->l('Shipping costs'), Tools::convertPrice($params['cart']->getOrderShippingCost($params['cart']->id_carrier), $currency))); $googleCart->SetEditCartUrl(Tools::getHttpHost(true, true) . __PS_BASE_URI__ . 'order.php'); $googleCart->SetContinueShoppingUrl(Tools::getHttpHost(true, true) . __PS_BASE_URI__ . 'order-confirmation.php'); $googleCart->SetRequestBuyerPhone(false); $googleCart->SetMerchantPrivateData($params['cart']->id); $smarty->assign('CheckoutButtonCode', $googleCart->CheckoutButtonCode($this->l('Pay with GoogleCheckout'), 'LARGE')); $smarty->assign('ModulePath', $this->_path); return $this->display(__FILE__, 'payment.tpl'); }
function UseCase1($google_id, $google_key, $sandbox, $orderid = '', $shipping_check, $digital_check) { global $tableprefix, $_SESSION; $gift_coupon_flag = 0; $google_id = $google_id; // Merchant ID $google_key = $google_key; // Merchant Key $google_demo = $sandbox; // "YES" if in test mode, "NO" if in live mode $shipping_cost = number_format($_SESSION['SESS_upscost'], 2, ".", ""); $totaltaxrate = number_format($_SESSION['session_taxrate'], 2, ".", ""); $referrer = $_SERVER["HTTP_REFERER"]; if (isset($_SESSION["sess_guest_username"]) && $_SESSION["sess_guest_username"] != '') { $usertype = 'guest'; } else { $usertype = 'user'; } if (!isset($_SESSION['SESS_google_checkout'])) { $totaltopay = number_format(getCartTotal($_SESSION["sess_userid"]), 2, ".", ""); $hide_shipping_division = hideShipping(); /*-------function call to check whether cart contains digital or gift coupon products so as to hide shipping------*/ $check_shipping_enable = checkShippingEnable(); if ($check_shipping_enable == "Y" && $hide_shipping_division == 1) { $shipping_cost = $_SESSION['SHIPPING_TOTAL']; $totaltopay = number_format($totaltopay, 2, ".", ""); $totaltopay = $totaltopay + $shipping_cost; } $amountpaid = number_format($_SESSION['amount_paid'], 2, ".", ""); $sql = "INSERT INTO " . $tableprefix . "orders (\n\t\t\t\tuser_id,\n\t\t\t\tbilling_first_name,\n\t\t\t\tbilling_last_name,\n\t\t\t\tbilling_address1,\n\t\t\t\tbilling_address2,\n\t\t\t\tbilling_city,\n\t\t\t\tbilling_state,\n\t\t\t\tbilling_country,\n\t\t\t\tbilling_zip,\n\t\t\t\tbilling_fax,\n\t\t\t\tbilling_email,\n\t\t\t\tbilling_phone,\n\t\t\t\tshipping_first_name,\n\t\t\t\tshipping_last_name,\n\t\t\t\tshipping_address1,\n\t\t\t\tshipping_address2,\n\t\t\t\tshipping_city,\n\t\t\t\tshipping_state,\n\t\t\t\tshipping_country,\n\t\t\t\tshipping_zip,\n\t\t\t\tshipping_fax,\n\t\t\t\tshipping_email,\n\t\t\t\tshipping_phone,\n\t\t\t\tprefered_shippin_method,\n\t\t\t\torder_date,\n\t\t\t\torder_total_price,\n\t\t\t\ttaxrate,\n\t\t\t\torder_status,\n\t\t\t\ttransaction_id,\n\t\t\t\tvorder_currency" . $nameCouponCode . ",\n\t\t\t\tnamount_paid,\n buyer_comments,\n vpayment_status\n\t\t\t\t) VALUES(\n\t\t\t\t'" . addslashes($_SESSION["sess_userid"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessBillingFirstName"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessBillingLastName"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessBillingAddress1"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessBillingAddress2"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessBillingCity"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessBillingState"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessBillingCountry"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessBillingZIP"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessBillingFAX"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessBillingEmail"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessBillingPhone"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessShippingFirstName"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessShippingLastName"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessShippingAddress1"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessShippingAddress2"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessShippingCity"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessShippingState"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessShippingCountry"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessShippingZIP"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessShippingFAX"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessShippingEmail"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessShippingPhone"]) . "',\n\t\t\t\t'" . addslashes($_SESSION["sessShippingDisplayName"]) . "',\n\t\t\t\tnow(),\n\t\t\t\t'" . addslashes($totaltopay) . "',\n\t\t\t\t'" . addslashes($totaltaxrate) . "',\n\t\t\t\t'1',\n\t\t\t\t'" . addslashes($tx_token) . "',\n\t\t\t\t'" . $currency_attributes[2] . "'" . $valueCouponCode . ",\n\t\t\t\t'" . addslashes($amountpaid) . "',\n '" . addslashes($_SESSION["SESS_BUYER_COMMENTS"]) . "',\n 'P'\n\t\t\t\t)"; mysql_query($sql); $orderid = mysql_insert_id(); // Updating Buying Process using Gift Certificate Code if ($_SESSION['sess_giftcertificate_code'] != '' && $_SESSION['sess_gift_amount_used'] != '') { $sql_up = "UPDATE " . $tableprefix . "orders SET vgiftcertificate_code='" . addslashes($_SESSION['sess_giftcertificate_code']) . "',\n\t\t\t\t\t\tnused_gift_amount=(nused_gift_amount + " . $_SESSION['sess_gift_amount_used'] . " )WHERE order_id='" . $orderid . "' "; $rs_up = mysql_query($sql_up) or die(mysql_error()); $sql_gift = "UPDATE " . $tableprefix . "giftcertificates SET nused_gift_amount=(nused_gift_amount + " . $_SESSION['sess_gift_amount_used'] . " )\n\t\t\t\t\t\t\tWHERE vgift_coupon_code ='" . addslashes($_SESSION['sess_giftcertificate_code']) . "' "; $rs_gift = mysql_query($sql_gift) or die(mysql_error()); } // End Gift Certificate Updation // Store Coupon Code Details to Order Table // Modified By Asha ON 21-02-2011 if ($_SESSION['couponCode_det'] != '') { // Update Order with Coupon Code Discount $sql_coupon_update = "UPDATE " . $tableprefix . "orders SET couponCodeDiscount ='" . $_SESSION['couponCode_det']['ccDiscount'] . "', couponCode ='" . $_SESSION['couponCode_det']['ccCode'] . "' where order_id='" . $orderid . "' "; $rs_update_c = mysql_query($sql_coupon_update) or die(mysql_error()); // End Update } // End Coupon Code Modification $check_shipping_enable = checkShippingEnable(); if ($check_shipping_enable == "Y" && $hide_shipping_division == 1) { /*---------------inserting the shipping details----------------*/ $select_cart_products = "SELECT c.product_option_id,c.product_id,p.product_name,po.product_shipping_weight FROM " . $tableprefix . "cart c\n INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id\n INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id\n WHERE c.user_id = " . $_SESSION["sess_userid"]; $result_cart_products = mysql_query($select_cart_products) or die(mysql_error()); if (mysql_num_rows($result_cart_products) > 0) { while ($cart_obj = mysql_fetch_object($result_cart_products)) { if (isset($_SESSION["SHIPPING_DETAILS"][$cart_obj->product_option_id]['preffered_shipping'])) { $product_name = $cart_obj->product_name; $optionVal = getProductOptionsName($cart_obj->product_option_id); $shipping_name = $_SESSION["SHIPPING_DETAILS"][$cart_obj->product_option_id]['preffered_shipping']; $shipping_cost = $_SESSION["SHIPPING_DETAILS"][$cart_obj->product_option_id]['rate']; $product_shipping_weight = $cart_obj->product_shipping_weight; $ship_product_option_id = $cart_obj->product_option_id; $product_name .= $optionVal; $insert_shipping = "INSERT INTO " . $tableprefix . "shipping_details\n (\n norder_id,\n vshipping_currency,\n dshipped_date,\n nshp_status,\n user_id,\n nshp_productid,\n nproduct_option_id,\n nshp_productname,\n vshipping_name,\n nshipping_cost,\n nshipping_weight\n )\n VALUES\n (\n " . $orderid . ",\n '" . $currency_attributes[2] . "',\n now(),\n 'C',\n '" . addslashes($_SESSION["sess_userid"]) . "',\n " . $cart_obj->product_id . ",\n " . $ship_product_option_id . ",\n '" . addslashes($product_name) . "',\n '" . addslashes($shipping_name) . "',\n '" . $shipping_cost . "',\n '" . $product_shipping_weight . "'\n )\n "; mysql_query($insert_shipping) or die(mysql_error()); } } // end while } // end if } // end of shipping if /************************** Affilate payment block*********************************************/ $sql = "select * from " . $tableprefix . "users where user_id='" . addslashes($_SESSION["sess_userid"]) . "'"; $result = mysql_query($sql); $row = mysql_fetch_array($result); if ($row["affiliate_id"] != "" && $row["affiliate_id"] != "0" && $row["vaff_type"] != "paid") { $aid = $row['affiliate_id']; $userid = $row['user_id']; $txtUserName = $row['user_name']; $txtFirstName = $row['first_name']; $txtEmail = $row['email']; $txtorderdamount = $totaltopay; $sql1 = "SELECT * FROM " . $tableprefix . "settings "; $result1 = mysql_query($sql1); if (mysql_num_rows($result1) != 0) { $row1 = mysql_fetch_array($result1); /*referral charge calculation based on the currency type*/ $txtReferralCharge = $row1["referral_charge"]; } $var_aff_comm = $txtorderdamount * $txtReferralCharge / 100; $sql2 = "INSERT INTO " . $tableprefix . "affiliate_registrations (\n\t\t\t\t\t\t\t\t\t\t\taffiliate_id,\n\t\t\t\t\t\t\t\t\t\t\tuser_id,\n\t\t\t\t\t\t\t\t\t\t\torder_id,\n\t\t\t\t\t\t\t\t\t\t\tuser_name ,\n\t\t\t\t\t\t\t\t\t\t\tuser_first_name,\n\t\t\t\t\t\t\t\t\t\t\tuser_last_name,\n\t\t\t\t\t\t\t\t\t\t\tuser_email,\n\t\t\t\t\t\t\t\t\t\t\treferral_charge,\n\t\t\t\t\t\t\t\t\t\t\tregistration_date,\n\t\t\t\t\t\t\t\t\t\t\tuser_totalpurchasedamount\n\t\t\t\t\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t\t\t\t'" . addslashes($aid) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . addslashes($userid) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . addslashes($orderid) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . addslashes($txtUserName) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . addslashes($txtFirstName) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . addslashes($txtLastName) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . addslashes($txtEmail) . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . addslashes($var_aff_comm) . "',\n\t\t\t\t\t\t\t\t\t\t\tnow(),'{$totaltopay}'\n\t\t\t\t\t\t\t\t\t\t\t)"; mysql_query($sql2); $sql3 = " update " . $tableprefix . "users set vaff_type='paid' where user_id='" . addslashes($_SESSION["sess_userid"]) . "'"; $result3 = mysql_query($sql3); } // end if Affiliate Registraion /************************** Affilate payment block*********************************************/ //echo "sql==".$sql."<br><br>"; $product_download_details = "Product Download Details\r\n"; $product_download_details .= "-----------------------\r\n"; $product_download_flag = 0; $download_link = ""; $sql = "SELECT c.*,(p.product_price+po.additional_price) AS product_price,p.product_name,p.product_code,p.product_artist_id,po.discount,\n\t\t\t\t\t\tp.vdigital_product,ar.commission\n\t\t\t\tFROM " . $tableprefix . "cart c\n INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id\n INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id\n INNER JOIN " . $tableprefix . "artists ar ON ar.artist_id = p.product_artist_id\n\t\t\t\tWHERE c.user_id = '" . addslashes($_SESSION["sess_userid"]) . "' "; $res = mysql_query($sql); $product_commission_amt = 0; $gift_coupon_flag = 0; $artists = array(); if (mysql_num_rows($res) != 0) { $i = 0; while ($row = mysql_fetch_array($res)) { $productid = $row["product_id"]; $product_option_id = $row["product_option_id"]; $quantity = $row["quantity"]; /*product price is calculated based on currency type*/ $converted_price = $row["product_price"]; $productprice = number_format($converted_price, 2, ".", ""); //$productprice = $row["product_price"]; $productname = $row["product_name"]; $optionVal = getProductOptionsName($product_option_id); $productname .= $optionVal; $productcode = $row["product_code"]; $productdiscount = $row["discount"]; $artistid = $row["product_artist_id"]; /*========================================Gift Certificate Section=================================*/ $select_gift_code = "SELECT vgift_coupon_code,ngift_coupon_amount\n\t\t\t\t\t FROM " . $tableprefix . "giftcoupon_master\n\t\t\t\t\t WHERE ngift_product_id = " . $productid; $result_gift_code = mysql_query($select_gift_code) or die(mysql_error()); if (mysql_num_rows($result_gift_code) > 0) { // start of first if $gift_coupon_product_id = $productid; while ($gift_code_row = mysql_fetch_array($result_gift_code)) { // start of while 2 /*--------------------creating random gift coupon code and updating the database-----------------------*/ $gift_coupon_code = "GC" . randomGiftCouponKey(); $giftamount = $productprice * $quantity; $insert_coupon_code = "INSERT INTO " . $tableprefix . "giftcertificates(vgift_coupon_code,ngift_product_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tngift_order_id,ngift_coupon_amount,user_id,seller_id)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES('" . $gift_coupon_code . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" . $row["product_id"] . ",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" . $orderid . ",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" . $giftamount . ",'" . $userid . "','" . $artistid . "')"; mysql_query($insert_coupon_code) or die(mysql_error()); } $gift_coupon_flag = 1; } // end of mysql number of rows check //=======================End Gift Certificate Section =================================== if ($row['vdigital_product'] == "Y") { $digital_product_id = $row["product_id"]; $select_product_digital_code = "SELECT vdigital_product_name,vdigital_product_code,ndownload_try,ndownload_expiry,ndownload_expiry_days\n\t\t\t\t\t\t\t\t\t\tFROM " . $tableprefix . "digital_product\n\t\t\t\t\t\t\t\t\t\tWHERE ndigital_productid = " . $row["product_id"] . " AND ndigital_orderid =0 "; $result_product_digital_code = mysql_query($select_product_digital_code); if (mysql_num_rows($result_product_digital_code) > 0) { while ($product_digital_code_row = mysql_fetch_array($result_product_digital_code)) { /*--------------------creating random product download code and updating the database-----------------------*/ $digital_product_code = randomDigitalProduct(); $expiry_days = $product_digital_code_row['ndownload_expiry_days']; $valid_date_upto = date("Y-m-d H:s:m", mktime(date("H"), date("i"), date("s"), date("m"), date("d") + $expiry_days, date("Y"))); /*-------Calculating the download expiry days----------*/ /*$update_product_digital_code = "UPDATE ".$tableprefix."digital_product SET vdigital_product_code = '".$digital_product_code."', ndigital_orderid = ".$orderid.", ndownload_expiry = '".$valid_date_upto."' WHERE ndigital_productid = ".$row["product_id"]; mysql_query($update_product_digital_code) or die(mysql_error());*/ /*---------selecting the download try and download expiry date-----------*/ $select_digital_product_details = "SELECT ndownload_try,ndownload_expiry\n\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\t FROM " . $tableprefix . "digital_product WHERE ndigital_productid = " . $productid; $result_digital_product_details = mysql_query($select_digital_product_details) or die(mysql_error()); $digital_product_details_row = mysql_fetch_assoc($result_digital_product_details); $product_download_try = $digital_product_details_row["ndownload_try"]; $download_expiry_date = $digital_product_details_row["ndownload_expiry"]; /*---------selecting the download try and download expiry date-----------*/ $select_digital_count = "SELECT ndigital_id FROM " . $tableprefix . "digital_product WHERE ndigital_orderid = " . $orderid; $result_digital_count = mysql_query($select_digital_count) or die(mysql_error()); //echo "digital count = ".mysql_num_rows($result_digital_count)."\n"; //echo "order count = ".$row["quantity"]; for ($i = 1; $i <= $row["quantity"]; $i++) { /*-------Calculating the download expiry days----------*/ $expiry_days = $product_digital_code_row['ndownload_expiry_days']; $valid_date_upto = date("Y-m-d H:s:m", mktime(date("H"), date("i"), date("s"), date("m"), date("d") + $expiry_days, date("Y"))); /*-------Calculating the download expiry days----------*/ $digital_product_code = randomDigitalProduct(); $insert_product_digital_code = "INSERT INTO " . $tableprefix . "digital_product(vdigital_product_name,ndigital_productid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tndigital_orderid,vdigital_product_code,ndownload_try,ndownload_count,ndownload_expiry,ndownload_expiry_days,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tndownload_status)VALUES('" . addslashes($product_digital_code_row['vdigital_product_name']) . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" . $row["product_id"] . ",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" . $orderid . ",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $digital_product_code . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" . $product_digital_code_row['ndownload_try'] . ",0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $valid_date_upto . "'," . addslashes($product_digital_code_row['ndownload_expiry_days']) . ",0)"; mysql_query($insert_product_digital_code) or die(mysql_error()); } // end for loop //exit; } // end ehile } // emd if number of rows check $product_download_flag = 1; } // end digital product check /*----------------------------------End check Digital Products-------------------------------------------------- /*----------------------------------Updating Gift Products----------------------------------------------------------*/ $product_tax = $_SESSION["TAX_DETAILS"][$product_option_id]; // Product Based Commission Calculation $price_amt = $productprice * $quantity; if ($row['discount'] != 0) { $discountprice = $productprice - $productprice * $row["discount"] / 100; $discountprice = number_format($discountprice, 2, ".", ""); $discount_amount = $discountprice * $quantity; } else { $discount_amount = $price_amt; } $product_commission_amt = $discount_amount * $row["commission"] / 100; // Product Based Commission Calculation End $sql = "INSERT INTO " . $tableprefix . "order_details (\n\t\t\t\torder_id,\n\t\t\t\tproduct_id,\n\t\t\t\tproduct_name,\n\t\t\t\tproduct_code,\n\t\t\t\tproduct_price,\n\t\t\t\tproduct_quantity,\n\t\t\t\tproduct_discount,\n\t\t\t\tartist_id,\n\t\t\t\titem_status,\n\t\t\t\tartist_payment_status,\n product_tax,\n product_option_id,\n product_commission_amount\n\t\t\t\t)VALUES(\n\t\t\t\t'" . addslashes($orderid) . "',\n\t\t\t\t'" . addslashes($productid) . "',\n\t\t\t\t'" . addslashes($productname) . "',\n\t\t\t\t'" . addslashes($productcode) . "',\n\t\t\t\t'" . addslashes($productprice) . "',\n\t\t\t\t'" . addslashes($quantity) . "',\n\t\t\t\t'" . addslashes($productdiscount) . "',\n\t\t\t\t'" . addslashes($artistid) . "',\n\t\t\t\t'1',\n\t\t\t\t'0',\n '" . $product_tax . "',\n '" . $product_option_id . "',\n '" . $product_commission_amt . "'\n\t\t\t\t)"; mysql_query($sql); //echo "sql==".$sql."<br><br>"; $artists[$i] = $artistid; $i++; $sql = ""; if ($product_download_flag == 1) { $update_order_details = "UPDATE " . $tableprefix . "order_details\n\t\t\t\t\t\tSET item_status = 4\n\t\t\t\t\t\tWHERE order_id = " . $orderid . " AND product_id = " . $digital_product_id; mysql_query($update_order_details) or die(mysql_error()); } $reorderlevelcheck = checkSellerStock($product_option_id, $quantity); if ($reorderlevelcheck == 1) { // Send Stock Reorder Mail To Seller sendStockreordermail($product_option_id, $quantity); } } // end while } // end number of rows isset($_SESSION['SESS_orderid']) ? session_unregister('SESS_orderid') : session_register('SESS_orderid'); $_SESSION['SESS_orderid'] = $orderid; if ($gift_coupon_flag == 1) { if (isset($_SESSION['SESS_digital_product']) && $_SESSION['SESS_digital_product'] != '') { session_unregister($_SESSION['SESS_digital_product']); } $update_order_details = "UPDATE " . $tableprefix . "order_details\n\t\t\t\t\t\t\t\t\t SET item_status = 4\n\t\t\t\t\t\t\t\t\t WHERE order_id = " . $orderid . " "; mysql_query($update_order_details) or die(mysql_error()); } // end if gift flag if ($product_download_flag == 1) { $update_order_details = "UPDATE " . $tableprefix . "order_details\n\t\t\t\t\t\t\t\t\t\t SET item_status = 4\n\t\t\t\t\t\t\t\t\t\t WHERE order_id = " . $orderid . " AND product_id = " . $digital_product_id; mysql_query($update_order_details) or die(mysql_error()); } if ($product_download_flag == 1) { isset($_SESSION['SESS_digital_product']) ? session_unregister('SESS_digital_product') : session_register('SESS_digital_product'); $_SESSION['SESS_digital_product'] = 1; } // Send Giftcertificate Mails /* if($gift_coupon_flag == 1) { sendgiftCertificateMail_Buyer($orderid,$_SESSION["sess_userid"],$usertype); sendgiftCertificateMail_Seller($orderid,$_SESSION["sess_userid"]); sendgiftCertificateMail_Admin($orderid,$_SESSION["sess_userid"]); } //Send Digital Certificate Mails if($product_download_flag == 1) { sendDigitalCertificateMail_Buyer($orderid,$_SESSION["sess_userid"],$usertype); sendDigitalCertificateMail_Seller($orderid,$_SESSION["sess_userid"]); sendDigitalCertificateMail_Admin($orderid,$_SESSION["sess_userid"]); } if($product_download_flag!=1 && $gift_coupon_flag!=1) { //sendBuyerEmail($orderid,$_SESSION["sess_userid"],$usertype); //sendSellerEmail($orderid,$_SESSION["sess_userid"]); //sendAdminEmail($orderid,$_SESSION["sess_userid"]); }*/ } // end of first if condition //$cost = $total_amount_topay; // price $currency = getSettingsValue("admin_currency"); if ($google_demo == "YES") { $server_type = "sandbox"; } else { $server_type = "checkout"; } // Create a new shopping cart object $cart = new GoogleCart($google_id, $google_key, $server_type, $currency); $total = 0; $cartitems = ""; $price = 0; $sql = "SELECT c.*,(p.product_price+po.additional_price) AS product_price,p.product_name,p.product_description,p.product_code,p.product_artist_id,po.discount,p.vdigital_product,po.product_option_id\n\t\t\t\tFROM " . $tableprefix . "cart c\n INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id\n INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id\n\t\t\t\tWHERE c.user_id = '" . $_SESSION["sess_userid"] . "' "; $res = mysql_query($sql); $cart_id = 1; $discountstr = ""; $unit_price = 0; $shipping_cost = 0; $product_tax = 0; if (mysql_num_rows($res) > 0) { while ($rw = mysql_fetch_array($res)) { $cart_no = "item_" . $cart_id; $ship_no = "ship_" . $cart_id; $restriction_no = "restriction_" . $cart_id; $product_option_id = $rw["product_option_id"]; $productname = $rw["product_name"]; $rate = $rw["product_price"]; $qty = $rw["quantity"]; $price = $qty * $rate; if ($rw["discount"] != "0") { $price = $price - $price * $rw["discount"] / 100; //$discountstr="<br>discount(".$rw["discount"]."%)"; } $check_shipping_enable = checkShippingEnable(); $hide_shipping_division = hideShipping(); if ($check_shipping_enable == "Y" && $hide_shipping_division == 1) { if (!empty($_SESSION["SHIPPING_DETAILS"])) { $shipping_cost = $_SESSION["SHIPPING_DETAILS"][$product_option_id]['rate']; } } if (!empty($_SESSION["TAX_DETAILS"])) { $product_tax = $_SESSION["TAX_DETAILS"][$product_option_id]; } $unit_price = $price + $shipping_cost + $product_tax; $cart_no = new GoogleItem($productname, $rw["product_description"], 1, $unit_price); // Unit price $cart->AddItem($cart_no); $cart_id++; } } $_SESSION['google_order_id'] = ''; $_SESSION['gift_coupon_flag'] = ''; $_SESSION['product_download_flag'] = ''; $_SESSION['google_order_id'] = $orderid; $_SESSION['gift_coupon_flag'] = $gift_coupon_flag; $_SESSION['product_download_flag'] = $product_download_flag; $merchantdata = $orderid . "@" . $gift_coupon_flag . "@" . $product_download_flag; $cart->SetMerchantPrivateData($merchantdata); // continue link page $cart->SetContinueShoppingUrl(SITE_URL . "/google_checkout_payment.php?google_check=1"); $cart->AddRoundingPolicy("HALF_UP", "PER_LINE"); // Display XML data // Display Google Checkout button echo $cart->CheckoutButtonCode("LARGE"); //$_SESSION["SHIPPING_DETAILS"] = array(); //$_SESSION['SHIPPING_TOTAL'] = 0; }
/** * Sets appropriate parameters for checking out to google * * @param array $params name value pair of contribution datat * * @param $component * @throws Exception * @return void */ function doTransferCheckout(&$params, $component) { $component = strtolower($component); $url = rtrim($this->_paymentProcessor['url_site'], '/') . '/cws/v2/Merchant/' . $this->_paymentProcessor['user_name'] . '/checkout'; //Create a new shopping cart object // Merchant ID $merchant_id = $this->_paymentProcessor['user_name']; // Merchant Key $merchant_key = $this->_paymentProcessor['password']; $server_type = $this->_mode == 'test' ? 'sandbox' : ''; $cart = new GoogleCart($merchant_id, $merchant_key, $server_type); $item1 = new GoogleItem($params['item_name'], '', 1, $params['amount'], $params['currencyID']); $cart->AddItem($item1); if ($component == "event") { $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},eventID={$params['eventID']},participantID={$params['participantID']},invoiceID={$params['invoiceID']}"; } elseif ($component == "contribute") { $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},invoiceID={$params['invoiceID']}"; $membershipID = CRM_Utils_Array::value('membershipID', $params); if ($membershipID) { $privateData .= ",membershipID={$membershipID}"; } $relatedContactID = CRM_Utils_Array::value('related_contact', $params); if ($relatedContactID) { $privateData .= ",relatedContactID={$relatedContactID}"; $onBehalfDupeAlert = CRM_Utils_Array::value('onbehalf_dupe_alert', $params); if ($onBehalfDupeAlert) { $privateData .= ",onBehalfDupeAlert={$onBehalfDupeAlert}"; } } } // Allow further manipulation of the arguments via custom hooks .. CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $privateData); $cart->SetMerchantPrivateData($privateData); if ($component == "event") { $returnURL = CRM_Utils_System::url('civicrm/event/register', "_qf_ThankYou_display=1&qfKey={$params['qfKey']}", TRUE, NULL, FALSE); } elseif ($component == "contribute") { $returnURL = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey={$params['qfKey']}", TRUE, NULL, FALSE); } $cart->SetContinueShoppingUrl($returnURL); $cartVal = base64_encode($cart->GetXML()); $signatureVal = base64_encode($cart->CalcHmacSha1($cart->GetXML())); $googleParams = array('cart' => $cartVal, 'signature' => $signatureVal); require_once 'HTTP/Request.php'; $params = array('method' => HTTP_REQUEST_METHOD_POST, 'allowRedirects' => FALSE); $request = new HTTP_Request($url, $params); foreach ($googleParams as $key => $value) { $request->addPostData($key, $value); } $result = $request->sendRequest(); if (PEAR::isError($result)) { CRM_Core_Error::fatal($result->getMessage()); } if ($request->getResponseCode() != 302) { CRM_Core_Error::fatal(ts('Invalid response code received from Google Checkout: %1', array(1 => $request->getResponseCode()))); } CRM_Utils_System::redirect($request->getResponseHeader('location')); exit; }
public function start_ipn($data, $config) { require_once 'assets/google-checkout/library/googlecart.php'; require_once 'assets/google-checkout/library/googleitem.php'; require_once 'assets/google-checkout/library/googleshipping.php'; require_once 'assets/google-checkout/library/googletax.php'; $merchant_id = $config['merchant_id']; // Your Merchant ID $merchant_key = $config['merchant_key']; // Your Merchant Key $server_type = $config['sandbox']; $currency = "USD"; $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); $cart->SetMerchantPrivateData(new MerchantPrivateData(array("transaction_id" => $data['transaction_id']))); $i = 1; foreach ($data["cart"]["items"] as $items) { ${'item_' . $i} = new GoogleItem($items['title'], "", $items['quantity'], $this->_currency_round($items["price"])); ${'item_' . $i}->SetMerchantItemId($items["product_id"]); $cart->AddItem(${'item_' . $i}); $i++; } // Applying a discount if ($data['cart_discount'] != 0) { ${'item_' . $i} = new GoogleItem("Discount Applied", "", 1, "-" . $this->_currency_round($data['cart_discount'])); $cart->AddItem(${'item_' . $i}); } // Calculating the Tax by taking the subtotal, subtracting the discount and // dividing by the pre-calculated rate. // -- Then formatting the number by 2 decimal places if ($data['cart_tax'] == 0) { $taxrate = 0; } else { $taxrate = number_format($data['cart_subtotal'] - $data['cart_discount'] / $data['cart_tax'], 2); } $tax_rule = new GoogleDefaultTaxRule($taxrate); $tax_rule->SetWorldArea(true); $cart->AddDefaultTaxRules($tax_rule); $ship_1 = new GoogleFlatRateShipping("Shipping", $data['cart_shipping']); $cart->AddShipping($ship_1); // Specify <edit-cart-url> $cart->SetEditCartUrl($data['return']); // Specify "Return to xyz" link $cart->SetContinueShoppingUrl($data['cancel_return']); // Define rounding policy $cart->AddRoundingPolicy("CEILING", "TOTAL"); echo ' <html> <head> <title>Google Checkout</title> </head> <body onLoad="document.forms[\'gateway_form\'].submit();"> <form method="post" name="gateway_form" action="' . $cart->checkout_url . '"> <input type="hidden" name="cart" value="' . base64_encode($cart->GetXML()) . '"/> <input type="hidden" name="signature" value="' . base64_encode($cart->CalcHmacSha1($cart->GetXML())) . '" /> <p style="text-align:center;"> Your order is being processed... will be redirected to the payment website. <br /> <br /> If you are not automatically redirected to Google Checkout within 5 seconds...<br /><br /> <input type="submit" value="Click Here"> </p> </form> </body> </html>'; }
public static function google_redirect($description, $amount, $user_id, $invoice_payment_id, $invoice_id, $currency_id) { chdir(dirname(__FILE__)); //'includes/plugin_paymethod_google/'); require_once 'library/googlecart.php'; require_once 'library/googleitem.php'; $server_type = self::is_sandbox() ? "sandbox" : ''; $currency = module_config::get_currency($currency_id); self::add_payment_data($invoice_payment_id, 'log', 'Starting payment of ' . $server_type . ' in currency ' . $currency['code']); $cart = new GoogleCart(self::get_merchant_id(), self::get_merchant_key(), $server_type, $currency['code']); $total_count = 1; // Check this URL for more info about the two types of digital Delivery // http://code.google.com/apis/checkout/developer/Google_Checkout_Digital_Delivery.html // Key/URL delivery self::add_payment_data($invoice_payment_id, 'log', 'Adding ' . $total_count . 'x ' . $description . ' (' . $amount . ' ' . $currency['code'] . ')'); $item_1 = new GoogleItem($description, "", $total_count, $amount); // Unit price //$item_1->SetURLDigitalContent(module_invoice::link_receipt($invoice_payment_id), $item_1->SetURLDigitalContent(module_invoice::link_public_print($invoice_id), '', _l("Payment Receipt")); $cart->AddItem($item_1); $private_data = new MerchantPrivateData(array('invoice_id' => $invoice_id, 'amount' => $amount, 'currency_id' => $currency_id, 'invoice_payment_id' => $invoice_payment_id)); $cart->SetMerchantPrivateData($private_data); // Specify <edit-cart-url> $cart->SetEditCartUrl(module_invoice::link_public($invoice_id)); // Specify "Return to xyz" link $cart->SetContinueShoppingUrl(module_invoice::link_public($invoice_id)); // Request buyer's phone number //$cart->SetRequestBuyerPhone(true); // This will do a server-2-server cart post and send an HTTP 302 redirect status // This is the best way to do it if implementing digital delivery // More info http://code.google.com/apis/checkout/developer/index.html#alternate_technique list($status, $error) = $cart->CheckoutServer2Server(); // if i reach this point, something was wrong echo "An error had ocurred: <br />HTTP Status: " . $status . ":"; echo "<br />Error message:<br />"; echo $error; exit; }
function generate_checkout_btn($item_name, $item_description, $item_qty, $item_price, $diamonds, $callback_url = NULL) { // Create a new shopping cart object $merchant_id = MERCHANT_ID; // Your Merchant ID $merchant_key = MERCHANT_KEY; // Your Merchant Key $server_type = CHECKOUT_SERVER_TYPE; $currency = CHECKOUT_CURRENCY; $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); // Create an item to be added in cart $item_1 = new GoogleItem($item_name, $item_description, $item_qty, $item_price); // Add <merchant-private-item-data> //$item_1->SetMerchantPrivateItemData(new MerchantPrivateItemData(array("user-id" => $_SESSION['udid']))); $item_1->SetMerchantPrivateItemData(new MerchantPrivateItemData(array("user-id" => $_SESSION['udid'], "diamonds" => $diamonds))); // Add items to the cart $cart->AddItem($item_1); // Add <merchant-private-data> //$cart->SetMerchantPrivateData(new MerchantPrivateData(array("user-id" => $_SESSION['userID']))); // Specify "Return to xyz" link if ($callback_url != NULL) { $cart->SetContinueShoppingUrl($callback_url); } else { $cart->SetContinueShoppingUrl(CHECKOUT_COUNTINUE_URL . "?success=1&amount=" . $diamonds); } // Display a small size button return $cart->CheckoutButtonCode("small", true, "en_US", false); }
function toSubmit($payment) { $merId = $this->getConf($payment["M_OrderId"], 'member_id'); $ikey = $this->getConf($payment["M_OrderId"], 'PrivateKey'); $this->submitUrl = "https://checkout.google.com/cws/v2/Merchant/" . $merId . "/checkout"; $this->callbackUrl = str_replace("http://", "https://", $this->callbackUrl); $ordAmount = number_format($payment["M_Amount"], 2, ".", ""); //number_format($order->M_Amount, 2, ".", ""); $cart = new GoogleCart($merId, $ikey, "checkout"); $item1 = new GoogleItem($payment["M_OrderId"], $payment["M_OrderNO"], 1, $ordAmount); //($order->M_OrderId, $order->M_OrderNO, 1, $ordAmount); $cart->AddItem($item1); $return = $cart->getArr("large"); return $return; }
function GoogleSubscription() { echo "<h2>Google Handled Subscription Request</h2>"; $merchant_id = ""; // Your Merchant ID $merchant_key = ""; // Your Merchant Key $server_type = "sandbox"; // or production $currency = "USD"; $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); $item = new GoogleItem("fee", "sign up fee", 1, 12.0); $subscription_item = new GoogleSubscription("google", "DAILY", 30.0); $recurrent_item = new GoogleItem("fee", "recurring fee", 1, 30.0); $subscription_item->SetItem($recurrent_item); $item->SetSubscription($subscription_item); $cart->AddItem($item); echo $cart->CheckoutButtonCode("MEDIUM"); }
function Usecase() { $merchant_id = ""; // Your Merchant ID $merchant_key = ""; // Your Merchant Key $server_type = "sandbox"; $currency = "USD"; $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); $total_count = 1; $certificate_path = ""; // set your SSL CA cert path // Check this URL for more info about the two types of digital Delivery // http://code.google.com/apis/checkout/developer/Google_Checkout_Digital_Delivery.html // Key/URL delivery $item_1 = new GoogleItem("Download Digital Item1", "With S/N", $total_count, 10.99); // Unit price $item_1->SetURLDigitalContent('http://example.com/download.php?id=15', 'S/N: 123.123123-3213', "Download Item1"); $cart->AddItem($item_1); // Email delivery $item_2 = new GoogleItem("Email Digital Item2", "An email will be sent by the merchant", $total_count, 9.19); // Unit price $item_2->SetEmailDigitalDelivery('true'); $cart->AddItem($item_2); // Add tax rules $tax_rule = new GoogleDefaultTaxRule(0.05); $tax_rule->SetStateAreas(array("MA", "FL", "CA")); $cart->AddDefaultTaxRules($tax_rule); // Specify <edit-cart-url> $cart->SetEditCartUrl("https://www.example.com/cart/"); // Specify "Return to xyz" link $cart->SetContinueShoppingUrl("https://www.example.com/goods/"); // Request buyer's phone number $cart->SetRequestBuyerPhone(true); // Add analytics data to the cart if its setted if (isset($_POST['analyticsdata']) && !empty($_POST['analyticsdata'])) { $cart->SetAnalyticsData($_POST['analyticsdata']); } // This will do a server-2-server cart post and send an HTTP 302 redirect status // This is the best way to do it if implementing digital delivery // More info http://code.google.com/apis/checkout/developer/index.html#alternate_technique list($status, $error) = $cart->CheckoutServer2Server('', $certificate_path); // if i reach this point, something was wrong echo "An error had ocurred: <br />HTTP Status: " . $status . ":"; echo "<br />Error message:<br />"; echo $error; // }
function nzshpcrt_shopping_basket_internals($cart, $quantity_limit = false, $no_title = false) { global $wpdb; if (get_option('permalink_structure') != '') { $seperator = "?"; } else { $seperator = "&"; } if (get_option('show_sliding_cart') == 1) { if (is_numeric($_SESSION['slider_state'])) { if ($_SESSION['slider_state'] == 0) { $collapser_image = 'plus.png'; } else { $collapser_image = 'minus.png'; } $fancy_collapser = "<a href='#' onclick='return shopping_cart_collapser()' id='fancy_collapser_link'><img src='" . WPSC_URL . "/images/{$collapser_image}' title='' alt='' id='fancy_collapser' /></a>"; } else { if ($_SESSION['nzshpcrt_cart'] == null) { $collapser_image = 'plus.png'; } else { $collapser_image = 'minus.png'; } $fancy_collapser = "<a href='#' onclick='return shopping_cart_collapser()' id='fancy_collapser_link'><img src='" . WPSC_URL . "/images/{$collapser_image}' title='' alt='' id='fancy_collapser' /></a>"; } } else { $fancy_collapser = ""; } $current_url = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; if (get_option('cart_location') == 4) { $no_title = true; } switch (get_option('cart_location')) { case 1: if ($no_title !== true) { $output .= "<h2>" . TXT_WPSC_SHOPPINGCART . " {$fancy_collapser}</h2>"; $output .= "<span id='alt_loadingindicator'><img id='alt_loadingimage' src='" . WPSC_URL . "/images/indicator.gif' alt='Loading' title='Loading' /> " . TXT_WPSC_UDPATING . "...</span></strong><br />"; } $spacing = ""; break; case 3: if ($no_title !== true) { $output .= "<strong class='cart_title'>" . TXT_WPSC_SHOPPINGCART . " {$fancy_collapser}</strong>"; } //$output .= "<a href='#' onclick='return shopping_cart_collapser()' class='cart_title' id='fancy_collapser_link'>".TXT_WPSC_SHOPPINGCART." </a>"; break; case 4: if ($no_title !== true) { if (is_array($GLOBALS['registered_sidebars'])) { $sidebar_args = end($GLOBALS['registered_sidebars']); } else { $sidebar_args['before_title'] = "<h2>"; $sidebar_args['after_title'] = "</h2>"; } $output .= $sidebar_args['before_title'] . TXT_WPSC_SHOPPINGCART . " {$fancy_collapser}" . $sidebar_args['after_title']; } break; default: if ($no_title !== true) { //$output .= "<strong class='cart_title'>".TXT_WPSC_SHOPPINGCART." $fancy_collapser</strong>"; } break; } $cart_count = 0; foreach ((array) $cart as $item) { $cart_count += $item->quantity; } $output .= "<div id='sliding_cart'>"; if ($cart != null) { if ($quantity_limit == true || $_SESSION['out_of_stock'] == true) { $output .= "<span class='items'><span class='numberitems'>" . TXT_WPSC_NUMBEROFITEMS . ": </span><span class='cartcount'>" . $cart_count . "</span></span>"; $output .= "<span class='nomore'>" . TXT_WPSC_NOMOREAVAILABLE . "</span>"; $_SESSION['out_of_stock'] = false; } else { $output .= "<span class='items'><span class='numberitems'>" . TXT_WPSC_NUMBEROFITEMS . ": </span><span class='cartcount'>" . $cart_count . "</span></span>"; } $output .= "<table class='shoppingcart'>\n\r"; $output .= "<tr><th id='thproduct'>" . TXT_WPSC_PRODUCT . "</th><th id='thqty'>" . TXT_WPSC_QUANTITY_SHORT . "</th><th id='thprice'>" . TXT_WPSC_PRICE . "</th></tr>\n\r"; $all_donations = true; $all_no_shipping = true; $tax = 0; //written by allen $merchant_id = get_option('google_id'); // Your Merchant ID $merchant_key = get_option('google_key'); // Your Merchant Key $server_type = get_option('google_server_type'); $currency = get_option('google_cur'); if (get_option('payment_gateway') == 'google') { $google_cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); } foreach ($cart as $cart_item) { $product_id = $cart_item->product_id; $quantity = $cart_item->quantity; //echo("<pre>".print_r($cart_item->product_variations,true)."</pre>"); $product = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "product_list` WHERE `id` = '{$product_id}' LIMIT 1", ARRAY_A); if ($product['donation'] == 1) { if (get_option('payment_gateway') == 'google') { $google_unit_price = $cart_item->donation_price; } $price = $quantity * $cart_item->donation_price; } else { if (get_option('payment_gateway') == 'google') { $google_unit_price = calculate_product_price($product_id, $cart_item->product_variations, 'stay', $cart_item->extras); } $price = $quantity * calculate_product_price($product_id, $cart_item->product_variations, 'stay', $cart_item->extras); if ($product['notax'] != 1) { $tax += nzshpcrt_calculate_tax($price, $_SESSION['selected_country'], $_SESSION['selected_region']) - $price; } $all_donations = false; } if ($product['no_shipping'] != 1) { $all_no_shipping = false; } if ($_SESSION['delivery_country'] != null) { $total_shipping += nzshpcrt_determine_item_shipping($product['id'], $quantity, $_SESSION['delivery_country']); } $total += $price; //exit(utf8_encode('™')); $product['name'] = str_replace("™", "™", $product['name']); $product['description'] = str_replace("™", "™", $product['description']); if (get_option('payment_gateway') == 'google') { $google_item = new GoogleItem(utf8_decode($product['name']), utf8_decode($product['description']), $quantity, $google_unit_price); $google_item->SetMerchantItemId($product['id']); $google_cart->SetMerchantCalculations(get_option('siteurl'), "false", "false", "false"); //echo serialize($cart_item->product_variations); $google_item->SetMerchantPrivateItemData("some variations"); $google_cart->AddItem($google_item); } $output .= "<tr>"; if (get_option("hide_name_link") == '1') { $output .= "<td class='tdproduct'>" . $product['name'] . "</td>"; } else { $output .= "<td><a href='" . wpsc_product_url($product['id']) . "' >" . stripslashes($product['name']) . "</a></td>"; } $output .= "<td class='tdqty'>" . $quantity . "</td>"; $output .= "<td class='tdprice'>" . nzshpcrt_currency_display($price, 1) . "</td>"; $output .= "</tr>\n\r"; } //google checkout stuff. // if (get_option('payment_gateway') == 'google') { // $google_shipping = new GoogleFlatRateShipping("Flat Rate Shipping", $total_shipping); // $Gfilter = new GoogleShippingFilters(); // $google_checkout_shipping=get_option("google_shipping_country"); // $google_shipping_country_ids = implode(",",(array)$google_checkout_shipping); // if($google_shipping_country_ids != null) { // $google_shipping_country = $wpdb->get_var("SELECT isocode FROM ".$wpdb->prefix."currency_list WHERE id IN (".$google_shipping_country_ids.")"); // } // $Gfilter->AddAllowedPostalArea($google_shipping_country); // $google_shipping->AddShippingRestrictions($Gfilter); // $google_cart->AddShipping($google_shipping); // // if ($_SESSION['selected_country']=='US'){ // $tax_rule = new GoogleDefaultTaxRule(0.05); // $state_name = $wpdb->get_var("SELECT name FROM ".$wpdb->prefix."region_tax WHERE id='".$_SESSION['selected_region']."'"); // $tax_rule->SetStateAreas(array($state_name)); // $tax_rule->AddPostalArea($google_shipping_country); // $google_cart->AddDefaultTaxRules($tax_rule); // } // } //end of google checkout. $output .= "</table>"; if ($_SESSION['delivery_country'] != null) { $total_shipping = nzshpcrt_determine_base_shipping($total_shipping, $_SESSION['delivery_country']); $output .= "<span class='subtotal'><span class='subtotalhead'>" . TXT_WPSC_SUBTOTAL . ":</span>" . nzshpcrt_currency_display($total, 1) . "</span>"; if (get_option('do_not_use_shipping') != 1 && $all_donations == false && $all_no_shipping == false) { $output .= "<span class='postage'><span class='postagehead'>" . TXT_WPSC_POSTAGE . ":</span>" . nzshpcrt_currency_display($total_shipping, 1) . "</span> "; } if ($tax > 0) { $output .= "<span class='tax'><span class='taxhead'>" . TXT_WPSC_TAX . ":</span> " . nzshpcrt_currency_display($tax, 1) . "</span>"; } if ($_SESSION['coupon_num']) { $overall_total = nzshpcrt_overall_total_price_numeric($_SESSION['selected_country'], true); $discount = $overall_total - nzshpcrt_apply_coupon($overall_total, $_SESSION['coupon_num']); $total_after_discount = $overall_total - $discount; $_SESSION['wpsc_discount'] = $discount; } else { $_SESSION['wpsc_discount'] = 0; } if ($discount > 0) { $output .= "<span class='discount'><span class='discounthead'>" . TXT_WPSC_DISCOUNT . ":</span>" . nzshpcrt_currency_display($discount, 1) . "</span>"; } $output .= "<span class='total'><span class='totalhead'>" . TXT_WPSC_TOTAL . ":</span>" . nzshpcrt_overall_total_price($_SESSION['delivery_country'], true) . "</span>"; } else { if ($discount > 0) { $output .= "<span class='discount'><span class='discounthead'>" . TXT_WPSC_DISCOUNT . ":</span>" . nzshpcrt_currency_display($discount, 1) . "</span>"; } $output .= "<span class='total'><span class='totalhead'>" . TXT_WPSC_TOTAL . ":</span>" . nzshpcrt_overall_total_price($_SESSION['delivery_country'], true) . "</span>"; } if (get_option('permalink_structure') != '') { $seperator = "?"; } else { $seperator = "&"; } if ($discount > 0) { if (get_option('payment_gateway') == 'google') { $google_item = new GoogleItem(utf8_decode("Coupon Code: '" . $_SESSION['coupon_num'] . "'"), utf8_decode("A coupon redeem"), 1, -$discount); $google_item->SetMerchantPrivateItemData("Coupon Deduction"); $google_cart->AddItem($google_item); } } if (get_option('payment_gateway') == 'google') { if (!$total_shipping) { $total_shipping = 0; } $pnp = $wpdb->get_var("SELECT SUM(pnp) FROM " . $wpdb->prefix . "product_list WHERE id IN (" . $google_product_id . ")"); $local_shipping_price = nzshpcrt_determine_base_shipping($total_shipping, get_option('base_country')); $google_local_shipping = new GoogleFlatRateShipping("Local Shipping", $local_shipping_price + $pnp); $international_shipping_price = nzshpcrt_determine_base_shipping($total_shipping, get_option('base_country') . "-"); $google_international_shipping = new GoogleFlatRateShipping("International Shipping", $international_shipping_price + $pnp); $Gfilter2 = new GoogleShippingFilters(); $Gfilter = new GoogleShippingFilters(); $google_checkout_shipping = get_option("google_shipping_country"); if (!empty($google_checkout_shipping)) { $google_shipping_country_ids = implode(",", (array) $google_checkout_shipping); $google_shipping_country = $wpdb->get_results("SELECT isocode FROM " . $wpdb->prefix . "currency_list WHERE id IN (" . $google_shipping_country_ids . ")", ARRAY_A); } //exit(print_r($google_shipping_country,1)); foreach ((array) $google_shipping_country as $country) { $Gfilter->AddAllowedPostalArea($country['isocode']); $Gfilter2->AddAllowedPostalArea($country['isocode']); $Gfilter2->AddExcludedPostalArea(get_option('base_country')); if ($country['isocode'] != get_option('base_country')) { $Gfilter->AddExcludedPostalArea($country['isocode']); } } $google_local_shipping->AddShippingRestrictions($Gfilter); $google_international_shipping->AddShippingRestrictions($Gfilter2); $google_cart->AddShipping($google_local_shipping); $google_cart->AddShipping($google_international_shipping); $local_tax = $wpdb->get_var("SELECT tax from " . $wpdb->prefix . "currency_list WHERE isocode='" . get_option('base_country') . "'"); //exit($local_tax); $tax_rule = new GoogleDefaultTaxRule($local_tax / 100); if ($_SESSION['selected_country'] == 'US' && get_option('base_country') == 'US') { $state_name = $wpdb->get_var("SELECT name FROM " . $wpdb->prefix . "region_tax WHERE id='" . $_SESSION['selected_region'] . "'"); //foreach ($state_name as $state) $tax_rule->SetStateAreas(array($state_name)); } else { $tax_rule->AddPostalArea(get_option('base_country')); } $google_cart->AddDefaultTaxRules($tax_rule); $alter_tax_rule = new GoogleDefaultTaxRule(0.0); foreach ((array) $google_shipping_country as $country) { if (get_option('base_country') != $country['isocode']) { $alter_tax_rule->AddPostalArea($country['isocode']); } } if ($alter_tax_rule != '') { $google_cart->AddDefaultTaxRules($alter_tax_rule); } } $output .= "<span class='emptycart'><a href='" . get_option('product_list_url') . $seperator . "category=" . $_GET['category'] . "&cart=empty' onclick='emptycart();return false;'>" . TXT_WPSC_EMPTYYOURCART . "</a><span>"; $output .= "<span class='gocheckout'><a href='" . get_option('shopping_cart_url') . "'>" . TXT_WPSC_GOTOCHECKOUT . "</a></span>"; if (get_option('payment_gateway') == 'google') { if (get_option('google_button_size') == '0') { $google_button_size = 'BIG'; } elseif (get_option('google_button_size') == '1') { $google_button_size = 'MEDIUM'; } elseif (get_option('google_button_size') == '2') { $google_button_size = 'SMALL'; } $google_cart->SetMerchantCalculations(get_option('siteurl'), "false", "false"); $google_cart->SetRequestBuyerPhone("true"); $google_session = md5(time()); $_SESSION['google_session'] = $google_session; if (!preg_match("/\\?/", get_option('product_list_url'))) { $seperator = "?"; } else { $seperator = "&"; } $continueshoppingurl = get_option('product_list_url') . $seperator . "action=bfg&session=" . $google_session; $google_cart->SetContinueShoppingUrl($continueshoppingurl); $google_cart->SetEditCartUrl(get_option('shopping_cart_url')); $_SESSION['google_shopping_cart'] = serialize($google_cart); // $output .= $google_cart->getXML(); $output .= "<br>" . $google_cart->CheckoutButtonCode($google_button_size); } //$output .= "<a href='".get_option('product_list_url')."'>".TXT_WPSC_CONTINUESHOPPING."</a>"; } else { $output .= $spacing; $output .= "<p class='empty'>" . TXT_WPSC_YOURSHOPPINGCARTISEMPTY . ".</p>"; $output .= "<p class='visitshop'><a href='" . get_option('product_list_url') . "'>" . TXT_WPSC_VISITTHESHOP . "</a></p>"; } $output .= "</div>"; return $output; }
function UseCase3() { //Create a new shopping cart object $merchant_id = ""; //Your Merchant ID $merchant_key = ""; //Your Merchant Key $server_type = "sandbox"; $cart = new GoogleCart($merchant_id, $merchant_key, $server_type); //Add items to the cart $item1 = new GoogleItem("Dry Food Pack AA1453", " pack of highly nutritious dried food for emergency", 1, 35); $item2 = new GoogleItem("MegaSound 2GB MP3 Player", "Portable MP3 player - stores 500 songs", 1, 178); $item3 = new GoogleItem("AA Rechargeable Battery Pack", "Battery pack containing four AA rechargeable batteries", 1, 12); $cart->AddItem($item1); $cart->AddItem($item2); $cart->AddItem($item3); //Set request buyer phone $cart->SetRequestBuyerPhone("true"); //Add merchant calculations options $cart->SetMerchantCalculations("https://www.example.com/shopping/merchantCalc", "true", "true", "true"); $ship = new GoogleShipping("merchant-calc", "merchant-calculated", 5, "USD", "ALL"); $ship->SetAllowedStateAreas(array("NY", "CA")); $cart->AddShipping($ship); $tax_rule = new GoogleTaxRule("default", 0.2); $tax_rule->SetStateAreas(array("CA", "NY")); $tax_table = new GoogleTaxTable("default"); $tax_table->AddTaxRules($tax_rule); $cart->AddTaxTables($tax_table); //Display XML data echo htmlentities($cart->GetXML()); //Display a disabled, small button with a white background echo $cart->CheckoutButtonCode("small", "white", "disabled"); }
/** * Prepares the payment form * and returns HTML Form to be displayed to the user * generally will have a message saying, 'confirm entries, then click complete order' * * Submit button target for onsite payments & return URL for offsite payments should be: * index.php?option=com_tienda&view=checkout&task=confirmPayment&orderpayment_type=xxxxxx * where xxxxxxx = $_element = the plugin's filename * * @param $data array form post data * @return string HTML to display */ function _prePayment($data) { /* * get all necessary data and prepare vars for assigning to the template */ $vars = new JObject(); $order = JTable::getInstance('Orders', 'TiendaTable'); $order->load($data['order_id']); $items = $order->getItems(); $vars->orderpayment_id = $data['orderpayment_id']; $vars->orderpayment_amount = $data['orderpayment_amount']; $vars->orderpayment_type = $this->_element; $vars->merchant_id = $this->_getParam('merchant_id'); $vars->type_id = JRequest::getInt('id'); //$vars->post_url = JRoute::_("index.php?option=com_tienda&controller=payment&task=process&ptype={$this->_element}&paction=proceed&tmpl=component"); $vars->button_url = $this->_getPostUrl(false); $vars->note = JText::_('COM_TIENDA_GOOGLECHECKOUT_NOTE_DEFAULT'); $uri = JFactory::getURI(); $url = $uri->toString(array('path', 'query', 'fragment')); $vars->r = base64_encode($url); // Include all the required files require_once dirname(__FILE__) . "/{$this->_element}/library/googlecart.php"; require_once dirname(__FILE__) . "/{$this->_element}/library/googleitem.php"; require_once dirname(__FILE__) . "/{$this->_element}/library/googleshipping.php"; require_once dirname(__FILE__) . "/{$this->_element}/library/googletax.php"; $cart = new GoogleCart($this->_getParam('merchant_id'), $this->_getParam('merchant_key'), $this->_getServerType(), $this->params->get('currency', 'USD')); $totalTax = 0; $totalPrice = 0; foreach ($items as $itemObject) { // $item_temp = new GoogleItem($itemObject->orderitem_name, $itemObject->orderitem_name, $itemObject->orderitem_quantity, $itemObject->orderitem_price + $itemObject->orderitem_attributes_price); // in argument of GoogleItem first itemname , itemDescription,quantity, unti price $cart->AddItem($item_temp); $totalPrice = $totalPrice + $itemObject->orderitem_final_price; $totalTax = $totalTax + $itemObject->orderitem_tax; } //check if coupons is not empty if (!empty($data['coupons'])) { $couponIds = array(); $couponIds = $data['coupons']; //NOTE: checking the coupon if its valid for the user is already done in the controller JModel::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/models'); $model = JModel::getInstance('Coupons', 'TiendaModel'); $model->setState('filter_ids', $couponIds); $coupons = $model->getList(); if (!empty($coupons)) { $totalDiscount = 0; foreach ($coupons as $coupon) { $orderitem_name = $coupon->coupon_code . " " . JText::_('COM_TIENDA_DISCOUNT'); if (empty($coupon->coupon_type)) { // get the value switch ($coupon->coupon_value_type) { case "1": // percentage $amount = $coupon->coupon_value / 100 * ($totalPrice + $totalTax); break; case "0": // flat-rate $amount = $coupon->coupon_value; break; } } $item_temp = new GoogleItem($orderitem_name, $orderitem_name, 1, "-" . $amount); // in argument of GoogleItem first itemname , itemDescription,quantity, unti price $cart->AddItem($item_temp); $totalDiscount = $totalDiscount + $amount; } } } if (!empty($data['shipping_plugin']) && $order->order_shipping > 0) { //check if usps plugin if ($data['shipping_plugin'] == 'shipping_usps') { $data['shipping_name'] = str_replace("®", "", $data['shipping_name']); //convert entity character to hexadecimal character //$data['shipping_name'] = str_replace("®", "<sup>&reg;</sup>", $data['shipping_name']); } // Add shipping $shipTemp = new GooglePickup($data['shipping_name'], $order->order_shipping + $order->order_shipping_tax); // shipping name and Price as an argument $cart->AddShipping($shipTemp); } //adjust the tax rate if discount is available if ($order->order_discount > 0) { $taxRate = $this->taxRateAdjustment($order->order_subtotal, $order->order_discount, $order->order_tax); } else { //compute the tax rate for default tax $totalOrder = $order->order_total - ($order->order_shipping + $order->order_shipping_tax); $taxRate = $this->calcDefaultTaxRate($totalOrder, $order->order_subtotal); } // Set default tax options $tax_rule = new GoogleDefaultTaxRule($taxRate); $tax_rule->SetWorldArea(true); $cart->AddDefaultTaxRules($tax_rule); //$reponseURL = JURI::root() ."plugins/tienda/{$this->_element}/library/responsehandler.php"; // Add merchant calculations options //$cart->SetMerchantCalculations( //"{$reponseURL}", // merchant-calculations-url // "true", // merchant-calculated tax // "false", // accept-merchant-coupons // "false"); // accept-merchant-gift-certificates $checkout_return_url = JURI::root() . "index.php?option=com_tienda&view=checkout&task=confirmPayment&orderpayment_type=" . $this->_element . "&paction=display_message"; $cart->SetContinueShoppingUrl($checkout_return_url); // set oredr id and the Data $mcprivatedata = new MerchantPrivateData(); $mcprivatedata->data = array("orderPaymentId" => $data['orderpayment_id']); $cart->SetMerchantPrivateData($mcprivatedata); $vars->cart = $cart; $html = $this->_getLayout('prepayment', $vars); return $html; }
function UseCase2() { // Create a new shopping cart object $merchant_id = ""; // Your Merchant ID $merchant_key = ""; // Your Merchant Key $server_type = "sandbox"; $currency = "USD"; $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); // Add items to the cart $item_1 = new GoogleItem("Dry Food Pack AA1453", "A pack of highly nutritious dried food for emergency", 2, 24.99); $item_1->SetTaxTableSelector("food"); $item_2 = new GoogleItem("MegaSound 2GB MP3 Player", "Portable MP3 player - stores 500 songs", 1, 175.49); $item_2->SetMerchantPrivateItemData(new MerchantPrivateItemData(array("color" => "blue", "weight" => "3.2"))); $item_2->SetMerchantItemId("Item#012345"); $cart->AddItem($item_1); $cart->AddItem($item_2); // Add shipping options $ship_1 = new GoogleFlatRateShipping("Ground", 15); $restriction_1 = new GoogleShippingFilters(); $restriction_1->SetAllowedWorldArea(true); $ship_1->AddShippingRestrictions($restriction_1); $ship_2 = new GooglePickup("Pick Up", 5); $cart->AddShipping($ship_1); $cart->AddShipping($ship_2); // Add default tax rules $tax_rule_1 = new GoogleDefaultTaxRule(0.17); $tax_rule_1->AddPostalArea("GB", "SW*"); $tax_rule_1->AddPostalArea("FR"); $tax_rule_1->AddPostalArea("DE"); $tax_rule_2 = new GoogleDefaultTaxRule(0.1); $tax_rule_2->SetWorldArea(true); $cart->AddDefaultTaxRules($tax_rule_1); $cart->AddDefaultTaxRules($tax_rule_2); // Add alternate tax table $tax_table = new GoogleAlternateTaxTable("food"); $tax_rule_1 = new GoogleAlternateTaxRule(0.05); $tax_rule_1->AddPostalArea("GB"); $tax_rule_1->AddPostalArea("FR"); $tax_rule_1->AddPostalArea("DE"); $tax_rule_2 = new GoogleAlternateTaxRule(0.03); $tax_rule_2->SetWorldArea(true); $tax_table->AddAlternateTaxRules($tax_rule_1); $tax_table->AddAlternateTaxRules($tax_rule_2); $cart->AddAlternateTaxTables($tax_table); // Add <merchant-private-data> $cart->SetMerchantPrivateData(new MerchantPrivateData(array("animals" => array("type" => "cat,dog")))); // Specify <edit-cart-url> $cart->SetEditCartUrl("http://www.example.com/edit"); // Specify "Return to xyz" link $cart->SetContinueShoppingUrl("http://www.example.com/continue"); // Request buyer's phone number $cart->SetRequestBuyerPhone(true); // Define rounding policy $cart->AddRoundingPolicy("CEILING", "TOTAL"); // Display XML data // echo "<pre>"; // echo htmlentities($cart->GetXML()); // echo "</pre>"; // Display a medium size button echo $cart->GetXML(); }
function UseCase3() { //Create a new shopping cart object $merchant_id = ""; // Your Merchant ID $merchant_key = ""; // Your Merchant Key $server_type = "sandbox"; $currency = "USD"; $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); // Add items to the cart $item = new GoogleItem("MegaSound 2GB MP3 Player", "Portable MP3 player - stores 500 songs", 1, 175.49); $item->SetMerchantPrivateItemData("<color>blue</color><weight>3.2</weight>"); $cart->AddItem($item); // Add merchant calculations options $cart->SetMerchantCalculations("http://200.69.205.154/~brovagnati/tools/unitTest/demo/responsehandlerdemo.php", "false", "true", "true"); // accept-merchant-gift-certificates // Add merchant-calculated-shipping option $ship = new GoogleMerchantCalculatedShipping("2nd Day Air", 10.0); // Default, fallback price $restriction = new GoogleShippingFilters(); $restriction->AddAllowedPostalArea("GB"); $restriction->AddAllowedPostalArea("US"); $restriction->SetAllowUsPoBox(false); $ship->AddShippingRestrictions($restriction); $address_filter = new GoogleShippingFilters(); $address_filter->AddAllowedPostalArea("GB"); $address_filter->AddAllowedPostalArea("US"); $address_filter->SetAllowUsPoBox(false); $ship->AddAddressFilters($address_filter); $cart->AddShipping($ship); // Set default tax options $tax_rule = new GoogleDefaultTaxRule(0.15); $tax_rule->SetWorldArea(true); $cart->AddDefaultTaxRules($tax_rule); $cart->AddRoundingPolicy("UP", "TOTAL"); // Display XML data // echo "<pre>"; // echo htmlentities($cart->GetXML()); // echo "</pre>"; // Display a disabled, small button echo $cart->CheckoutButtonCode("SMALL", false); }
function Usecase($seperator, $sessionid) { global $wpdb; $purchase_log_sql = "SELECT * FROM `" . $wpdb->prefix . "purchase_logs` WHERE `sessionid`= " . $sessionid . " LIMIT 1"; $purchase_log = $wpdb->get_results($purchase_log_sql, ARRAY_A); $cart_sql = "SELECT * FROM `" . $wpdb->prefix . "cart_contents` WHERE `purchaseid`='" . $purchase_log[0]['id'] . "'"; $wp_cart = $wpdb->get_results($cart_sql, ARRAY_A); $merchant_id = get_option('google_id'); $merchant_key = get_option('google_key'); $server_type = get_option('google_server_type'); $currency = get_option('google_cur'); $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); $cart->SetContinueShoppingUrl(get_option('product_list_url')); $cart->SetEditCartUrl(get_option('shopping_cart_url')); $no = 1; //exit("<pre>".print_r($wp_cart,true)."</pre>"); foreach ($wp_cart as $item) { $product_data = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "product_list` WHERE `id`='" . $item['prodid'] . "' LIMIT 1", ARRAY_A); $product_data = $product_data[0]; $prohibited = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "wpsc_productmeta` WHERE `product_id`='" . $item['prodid'] . "' AND meta_key='google_prohibited' LIMIT 1", ARRAY_A); $prohibited_data = $prohibited_data[0]; if (count($prohibited) > 0) { $_SESSION['google_prohibited'] = '1'; } else { $_SESSION['google_prohibited'] = '0'; } $variation_count = count($product_variations); $variation_sql = "SELECT * FROM `" . $wpdb->prefix . "cart_item_variations` WHERE `cart_id`='" . $item['id'] . "'"; $variation_data = $wpdb->get_results($variation_sql, ARRAY_A); $variation_count = count($variation_data); $extras_sql = "SELECT * FROM `" . $wpdb->prefix . "cart_item_extras` WHERE `cart_id`='" . $item['id'] . "'"; $extras_data = $wpdb->get_results($extras_sql, ARRAY_A); $extras_count = count($extras_data); $price = nzshpcrt_calculate_tax($item['price'], $_SESSION['selected_country'], $_SESSION['selected_region']); if ($extras_count > 0) { foreach ($extras_data as $extras_datum) { $price += $wpdb->get_var("SELECT `price` FROM `" . $wpdb->prefix . "extras_values_associations` WHERE `product_id` = '" . $item['prodid'] . "' AND `extras_id` = '" . $extras_datum['extra_id'] . "' LIMIT 1"); } } //exit("------->".$price); $local_currency_shipping = $item['pnp']; $base_shipping = $purchase_log[0]['base_shipping']; $total_shipping = $local_currency_shipping + $base_shipping; $cartitem["{$no}"] = new GoogleItem($product_data['name'], $product_data['description'], $item['quantity'], $price); // Unit price $cart->AddItem($cartitem["{$no}"]); $no++; } // Add shipping options $Gfilter = new GoogleShippingFilters(); $Gfilter->SetAllowedCountryArea('ALL'); $google_checkout_shipping = get_option("google_shipping_country"); $google_shipping_country_ids = implode(",", $google_checkout_shipping); $google_shipping_country = $wpdb->get_var("SELECT isocode FROM " . $wpdb->prefix . "currency_list WHERE id IN (" . $google_shipping_country_ids . ")"); $Gfilter->AddAllowedPostalArea($google_shipping_country); $ship_1 = new GoogleFlatRateShipping('Flat Rate Shipping', $total_shipping); $ship_1->AddShippingRestrictions($Gfilter); $cart->AddShipping($ship_1); // Add tax rules if ($_SESSION['selected_country'] == 'US') { $tax_rule = new GoogleDefaultTaxRule(0.05); $state_name = $wpdb->get_var("SELECT name FROM " . $wpdb->prefix . "region_tax WHERE id='" . $_SESSION['selected_region'] . "'"); $tax_rule->SetStateAreas(array($state_name)); $cart->AddDefaultTaxRules($tax_rule); } $_SESSION['nzshpcrt_cart'] = null; // Specify <edit-cart-url> // $cart->SetEditCartUrl("https://www.example.com/cart/"); // Specify "Return to xyz" link //$cart->SetContinueShoppingUrl("https://www.example.com/goods/"); // Request buyer's phone number //$cart->SetRequestBuyerPhone(true); // Display Google Checkout button echo $cart->CheckoutButtonCode("BIG"); }
/** * @param array $params * @param $component */ public function doRecurCheckout(&$params, $component) { $intervalUnit = CRM_Utils_Array::value('frequency_unit', $params); if ($intervalUnit == 'week') { $intervalUnit = 'WEEKLY'; } elseif ($intervalUnit == 'year') { $intervalUnit = 'YEARLY'; } elseif ($intervalUnit == 'day') { $intervalUnit = 'DAILY'; } elseif ($intervalUnit == 'month') { $intervalUnit = 'MONTHLY'; } // Merchant ID $merchant_id = $this->_paymentProcessor['user_name']; // Merchant Key $merchant_key = $this->_paymentProcessor['password']; $server_type = $this->_mode == 'test' ? 'sandbox' : ''; $itemName = CRM_Utils_Array::value('item_name', $params); $description = CRM_Utils_Array::value('description', $params); $amount = CRM_Utils_Array::value('amount', $params); $installments = CRM_Utils_Array::value('installments', $params); $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $params['currencyID']); $item = new GoogleItem($itemName, $description, 1, $amount); $subscription_item = new GoogleSubscription("merchant", $intervalUnit, $amount, $installments); $item->SetSubscription($subscription_item); $cart->AddItem($item); $this->submitPostParams($params, $component, $cart); }
function generateCartButton($settings, $data = null, $theitems = array()) { $cart = new GoogleCart($settings['merchantID'], $settings['merchantKey'], $this->_gserve, $settings['currency']); $counter = 1; if (!empty($theitems)) { $thisitems = $theitems; } else { $thisitems = $this->_items; } foreach ($thisitems as $item) { $varvar = 'item_' . $counter; // echo '<pre>'; print_r($item); die; ${$varvar} = new GoogleItem($item['title'], $item['desc'], $item['count'], $item['price']); if (isset($item['data'])) { ${$varvar}->SetMerchantPrivateItemData(new MerchantPrivateItemData($item['data'])); } if (isset($item['id'])) { ${$varvar}->SetMerchantItemId($item['id']); } $cart->AddItem(${$varvar}); } // Set the acct. name, etc. if ($data) { $cart->SetMerchantPrivateData(new MerchantPrivateData($data)); } // Specify "Return to xyz" link $cart->SetContinueShoppingUrl($this->_continueShopping); // Display Google Checkout button return $cart->CheckoutButtonCode("SMALL"); }
function process() { $this->order->load($this->order->getReference()); $results = $this->modelPayment->get_orderstatus_id($this->language->get('order_status_paid_unconfirmed'), $this->language->getId()); //$sql = "select `order_status_id` from `order_status` where `name` = '?' and `language_id` = '?'"; //$parsed = $this->database->parse($sql, $this->language->get('order_status_paid_unconfirmed'), $this->language->getId()); //$results = $this->database->getRow($parsed); if ($results) { // copy cart and order-total to a new GoogleCart object $merchantId = $this->config->get('google_merchantid'); $merchantKey = $this->config->get('google_merchantkey'); chdir('library/google'); require_once 'library/googlecart.php'; require_once 'library/googleitem.php'; require_once 'library/googleshipping.php'; require_once 'library/googletax.php'; $serverType = $this->config->get('google_test') ? 'sandbox' : 'production'; $currencyGoogle = $this->config->get('google_currency'); $currencyCart = $this->currency->getCode(); $totalCart = $this->order->get('total'); if ($currencyCart != $currencyGoogle) { $result = $this->modelPayment->get_currency($currencyCart); $baseValCart = isset($result['value']) ? $result['value'] : NULL; $result = $this->modelPayment->get_currency($currencyGoogle); $baseValGoogle = isset($result['value']) ? $result['value'] : NULL; if ($baseValCart == NULL || $baseValGoogle == NULL) { // this should never happen, we use cart's currency let GoogleCheckout return an error $totalGoogle = $totalCart; $currencyGoogle = $currencyCart; } else { // convert cart's total into the currency used by Google Checkout $totalGoogle = round($totalCart * $baseValCart / $baseValGoogle); } } else { $totalGoogle = $totalCart; } $cart = new GoogleCart($merchantId, $merchantKey, $serverType, $currencyGoogle); $item_1 = new GoogleItem($this->config->get('config_store'), 'order# ' . $this->order->getReference(), 1, $totalGoogle); $item_1->SetTaxTableSelector("including all taxes"); $cart->AddItem($item_1); $tax_table = new GoogleAlternateTaxTable("including all taxes"); $tax_rule_1 = new GoogleAlternateTaxRule(0.0); $tax_rule_1->SetWorldArea(true); $tax_table->AddAlternateTaxRules($tax_rule_1); $cart->AddAlternateTaxTables($tax_table); // $tax_rule_1 = new GoogleDefaultTaxRule(0.175); // $tax_rule_1->SetWorldArea(true); // $cart->AddDefaultTaxRules($tax_rule_1); // Have AlegroCart process the order and remove its cart from the session. // AlegroCart will store it in the database with a 'Paid Unconfirmed' order status. $this->order->process($results['order_status_id']); $this->cart->clear(); // This will do a server-to-server Google cart post and send an HTTP 302 redirect status // More info http://code.google.com/apis/checkout/developer/index.html#alternate_technique list($status, $error) = $cart->CheckoutServer2Server(); return TRUE; // If it reaches this point then something went wrong echo "An error had ocurred: <br />HTTP Status: " . $status . ":"; echo "<br />Error message:<br />"; echo $error; echo "<br />"; exit; } else { // I think it may be better to die here with a message as it is // a major configuration problem that should be found by even // the most basic testing and hence not impact upon a customer. die('Configuration error: You MUST have created an order status for "Paid Unconfirmed" for every installed language.'); // The following is a reasonable alternative but there is no way without making // changes to checkout_failure, to get a user defined message to the that page. // The message, as above, is a big help in tracking any teething problems with this code. //$this->response->redirect($this->url->ssl('checkout_failure')); } }
function Usecase($separator, $sessionid, $fromcheckout) { global $wpdb, $wpsc_cart; $purchase_log_sql = $wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid` = %s LIMIT 1", $sessionid); $purchase_log = $wpdb->get_results($purchase_log_sql, ARRAY_A); $cart_sql = $wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid` = %d", $purchase_log[0]['id']); $wp_cart = $wpdb->get_results($cart_sql, ARRAY_A); $merchant_id = get_option('google_id'); $merchant_key = get_option('google_key'); $server_type = get_option('google_server_type'); $currency = get_option('google_cur'); $transact_url = get_option('transact_url'); $returnURL = $transact_url . $separator . "sessionid=" . $sessionid . "&gateway=google"; $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); $cart->SetContinueShoppingUrl($returnURL); $cart->SetEditCartUrl(get_option('shopping_cart_url')); //google prohibited items not implemented $currency_converter = new CURRENCYCONVERTER(); $currency_code = $wpdb->get_results("SELECT `code` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `id`='" . get_option('currency_type') . "' LIMIT 1", ARRAY_A); $local_currency_code = $currency_code[0]['code']; $google_curr = get_option('google_cur'); $currentcy_rate = 1; if ($google_curr != $local_currency_code) { $currentcy_rate = $currency_converter->convert(1, $local_currency_code, $google_curr); } while (wpsc_have_cart_items()) { wpsc_the_cart_item(); $google_currency_productprice = $currentcy_rate * (wpsc_cart_item_price(false) / wpsc_cart_item_quantity()); $cart_item = new GoogleItem(wpsc_cart_item_name(), '', wpsc_cart_item_quantity(), $google_currency_productprice); $cart->AddItem($cart_item); } //If there are coupons applied add coupon as a product with negative price if ($wpsc_cart->coupons_amount > 0) { $google_currency_productprice = $currentcy_rate * $wpsc_cart->coupons_amount; $coupon = new GoogleItem('Discount', 'Discount Price', 1, '-' . $google_currency_productprice); $cart->AddItem($coupon); } $shipping_country = $purchase_log[0]['shipping_country']; $shipping_region = $purchase_log[0]['shipping_region']; if ($shipping_country == "UK") { $shipping_country = "GB"; } // Add shipping options if (wpsc_uses_shipping()) { $shipping_name = ucfirst($wpsc_cart->selected_shipping_method) . " - " . $wpsc_cart->selected_shipping_option; if ($shipping_name == "") { $shipping_name = "Calculated"; } $shipping = new GoogleFlatRateShipping($shipping_name, $wpsc_cart->calculate_total_shipping() * $currentcy_rate); if (!empty($shipping_country)) { $shipping_filter = new GoogleShippingFilters(); if (!empty($shipping_region) && is_numeric($shipping_region)) { $shipping_filter->AddAllowedPostalArea($shipping_country, wpsc_get_state_by_id($shipping_region, "code")); $shipping_filter->AddAllowedStateArea(wpsc_get_state_by_id($shipping_region, "code")); } else { $shipping_filter->AddAllowedPostalArea($shipping_country); } $shipping->AddShippingRestrictions($shipping_filter); } $cart->AddShipping($shipping); } // Add tax rules if (!empty($shipping_country)) { $tax_rule = new GoogleDefaultTaxRule(wpsc_cart_tax(false) / $wpsc_cart->calculate_subtotal()); $tax_rule->AddPostalArea($shipping_country); $cart->AddDefaultTaxRules($tax_rule); } // Display Google Checkout button if (get_option('google_button_size') == '0') { $google_button_size = 'BIG'; } elseif (get_option('google_button_size') == '1') { $google_button_size = 'MEDIUM'; } elseif (get_option('google_button_size') == '2') { $google_button_size = 'SMALL'; } echo $cart->CheckoutButtonCode($google_button_size); }
/** * Generate the Google Checkout button link **/ public function generate_googlecheckout_form($order_id) { global $woocommerce; require_once GOOGLE_CHECKOUT_LIB . 'googlecart.php'; require_once GOOGLE_CHECKOUT_LIB . 'googleitem.php'; require_once GOOGLE_CHECKOUT_LIB . 'googleshipping.php'; require_once GOOGLE_CHECKOUT_LIB . 'googletax.php'; $order = new WC_Order($order_id); $shipping_name = explode(' ', $order->shipping_method); // Check if this is a test purchase if ($this->testmode == 'yes') { $server_type = "sandbox"; } else { $server_type = "checkout"; } $merchant_id = $this->merchant_id; // Your Merchant ID $merchant_key = $this->merchant_key; // Your Merchant Key $currency = get_option('woocommerce_currency'); $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); // Specify <edit-cart-url> $cart->SetEditCartUrl(get_permalink(get_option('woocommerce_cart_page_id'))); // Specify "Return to xyz" link $cart->SetContinueShoppingUrl(add_query_arg('key', $order->order_key, add_query_arg('order', $order_id, get_permalink(get_option('woocommerce_thanks_page_id'))))); // Order key $cart->SetMerchantPrivateData(new MerchantPrivateData(array("cart-id" => $order->id))); // Request buyer's phone number $cart->SetRequestBuyerPhone(true); // Default tax - for shipping, if used if ($order->order_shipping_tax > 0) { // We manually calculate the shipping tax percentage here $calculated_shipping_tax_percentage = $order->order_shipping_tax / $order->order_shipping; $tax_rule_for_shipping = new GoogleDefaultTaxRule($calculated_shipping_tax_percentage, 'true'); $tax_rule_for_shipping->SetWorldArea(true); $cart->AddDefaultTaxRules($tax_rule_for_shipping); } // Shipping Cost if ($order->order_shipping > 0) { $ship_1 = new GoogleFlatRateShipping($order->shipping_method, number_format($order->order_shipping, 2)); $restriction_1 = new GoogleShippingFilters(); $restriction_1->SetAllowedWorldArea(true); $ship_1->AddShippingRestrictions($restriction_1); $cart->AddShipping($ship_1); } // Cart Contents $item_loop = 0; $myvat = array(); if (sizeof($order->get_items()) > 0) { foreach ($order->get_items() as $item) { $_product = new WC_Product($item['id']); if ($_product->exists() && $item['qty']) { $item_loop++; // Change tax format from 25.00 to 0.25 $item_tax_percentage = number_format($order->get_item_tax($item, false) / $order->get_item_total($item, false, false) * 100, 2, '.', ''); $item_vat = $item_tax_percentage / 100; $myvat[$item_loop] = $item_vat; ${"item_" . $item_loop} = new GoogleItem($item['name'], "", $item['qty'], $order->get_item_total($item, false, false)); // Name the alternate-tax-table $vat_name = "vat" . $item_vat; ${"item_" . $item_loop}->SetMerchantItemId($item['id']); ${"item_" . $item_loop}->SetTaxTableSelector($vat_name); $cart->AddItem(${"item_" . $item_loop}); } } } // Discount if ($order->order_discount > 0) { $item_loop++; ${"item_" . $item_loop} = new GoogleItem(__('Discount', 'woothemes'), "", "1", -$order->order_discount); ${"item_" . $item_loop}->SetTaxTableSelector("no_tax"); $cart->AddItem(${"item_" . $item_loop}); } // Tax // Loops through all tax classes that has been added to the cart and add these as Alternate tax tables to google Checkout. $taxrule_loop = 1; $no_duplicate_vat = array_unique($myvat); foreach ($no_duplicate_vat as $value) { // Name the alternate-tax-table $vat_name = "vat" . $value; $tax_table = new GoogleAlternateTaxTable($vat_name); ${"tax_rule_" . $taxrule_loop} = new GoogleAlternateTaxRule($value); ${"tax_rule_" . $taxrule_loop}->SetWorldArea(true); $tax_table->AddAlternateTaxRules(${"tax_rule_" . $taxrule_loop}); $cart->AddAlternateTaxTables($tax_table); $taxrule_loop++; } // The form return $cart->CheckoutButtonCode("SMALL") . '<script type="text/javascript"> jQuery(function(){ jQuery("body").block( { message: "<img src=\\"' . $woocommerce->plugin_url() . '/assets/images/ajax-loader.gif\\" alt=\\"Redirecting...\\" />' . __('Thank you for your order. We are now redirecting you to Google Checkout to make payment.', 'woothemes') . '", overlayCSS: { background: "#fff", opacity: 0.6 }, css: { padding: 20, textAlign: "center", color: "#555", border: "3px solid #aaa", backgroundColor:"#fff", cursor: "wait", lineHeight: "32px" } }); jQuery("#submit_googlecheckout_payment_form").click(); }); </script>'; }
function googlecheckout() { if ($this->input->post('googlesubmit')) { $this->load->model('payment_model'); $paymentGateways_google = $this->payment_model->getPaymentSettings(); $payment_amount = $this->input->post('item_price_1'); $tr_id = $this->input->post('trans'); $this->session->set_userdata('tr_id', $tr_id); $merchant_id = $paymentGateways_google['gch']['mail_id']; // Your Merchant ID $merchant_key = $paymentGateways_google['gch']['url']; // Your Merchant Key if ($paymentGateways_google['gch']['url_status'] == 0) { $server_type = "sandbox"; } else { $server_type = "Live"; } $currency = "USD"; $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); $total_count = 1; // Check this URL for more info about the two types of digital Delivery // http://code.google.com/apis/checkout/developer/Google_Checkout_Digital_Delivery.html //Get the language details $item_1 = new GoogleItem($this->config->item('site_name') . 'Account Deposit', ' Account Deposit ', '1', $payment_amount); // Unit price // $item_1->SetURLDigitalContent('http://example.com/download.php?id=15','S/N: 123.123123-3213', "Download Item1"); $cart->AddItem($item_1); $cart->SetMerchantPrivateData(new MerchantPrivateData(array("transaction-id" => $tr_id))); // Specify "Return to xyz" link $cart->SetContinueShoppingUrl(site_url('payment/checkoutSuccess')); // Request buyer's phone number $cart->SetRequestBuyerPhone(true); // Add analytics data to the cart if its setted if (isset($_POST['analyticsdata']) && !empty($_POST['analyticsdata'])) { $cart->SetAnalyticsData($_POST['analyticsdata']); } // This will do a server-2-server cart post and send an HTTP 302 redirect status // This is the best way to do it if implementing digital delivery // More info http://code.google.com/apis/checkout/developer/index.html#alternate_technique list($status, $error) = $cart->CheckoutServer2Server(); // if i reach this point, something was wrong echo "An error had ocurred: <br />HTTP Status: " . $status . ":"; echo "<br />Error message:<br />"; echo $error; // } }
function process_button() { global $osC_ShoppingCart, $osC_Tax, $osC_Language, $osC_Currencies, $osC_Session; require_once 'includes/classes/product.php'; require_once 'ext/googlecheckout/googlecart.php'; require_once 'ext/googlecheckout/googleitem.php'; require_once 'ext/googlecheckout/googleshipping.php'; $cart = new GoogleCart(MODULE_PAYMENT_GCHECKOUT_MERCHANT_ID, MODULE_PAYMENT_GCHECKOUT_MERCHANT_KEY, MODULE_PAYMENT_GCHECKOUT_SERVER, MODULE_PAYMENT_GCHECKOUT_CURRENCY); //transfer the whole cart if (MODULE_PAYMENT_GCHECKOUT_TRANSFER_CART == '1') { //products $products = $osC_ShoppingCart->getProducts(); foreach ($products as $product) { $name = $product['name']; //gift certificate if ($product['type'] == PRODUCT_TYPE_GIFT_CERTIFICATE) { $name .= "\n" . ' - ' . $osC_Language->get('senders_name') . ': ' . $product['gc_data']['senders_name']; if ($product['gc_data']['type'] == GIFT_CERTIFICATE_TYPE_EMAIL) { $name .= "\n" . ' - ' . $osC_Language->get('senders_email') . ': ' . $product['gc_data']['senders_email']; } $name .= "\n" . ' - ' . $osC_Language->get('recipients_name') . ': ' . $product['gc_data']['recipients_name']; if ($product['gc_data']['type'] == GIFT_CERTIFICATE_TYPE_EMAIL) { $name .= "\n" . ' - ' . $osC_Language->get('recipients_email') . ': ' . $product['gc_data']['recipients_email']; } $name .= "\n" . ' - ' . $osC_Language->get('message') . ': ' . $product['gc_data']['message']; } //variants $variants_array = array(); if ($osC_ShoppingCart->hasVariants($product['id'])) { foreach ($osC_ShoppingCart->getVariants($product['id']) as $variants) { $variants_array[$variants['groups_id']] = $variants['variants_values_id']; $name .= "\n" . ' - ' . $variants['groups_name'] . ': ' . $variants['values_name']; } } //get tax $tax = $osC_Tax->getTaxRate($product['tax_class_id'], $osC_ShoppingCart->getTaxingAddress('country_id'), $osC_ShoppingCart->getTaxingAddress('zone_id')); if (DISPLAY_PRICE_WITH_TAX == '1') { $price = $osC_Currencies->addTaxRateToPrice($product['final_price'], $tax); } else { $price = $product['final_price'] + osc_round($product['final_price'] * ($tax / 100), $osC_Currencies->currencies[DEFAULT_CURRENCY]['decimal_places']); } $osC_Product = new osC_Product($product['id']); $gitem = new GoogleItem($name, $osC_Product->getDescription(), intval($product['quantity']), $price); $gitem->SetMerchantPrivateItemData(new MerchantPrivateItemData(array('item' => base64_encode(serialize($product))))); $gitem->SetMerchantItemId($product['id']); $cart->AddItem($gitem); } //add order totals modules into gcheckout cart as item such as: coupon, gift certificate, low order fee //exclude modules: sub_total, tax, total and shipping module $shipping_cost = 0; foreach ($osC_ShoppingCart->getOrderTotals() as $total) { if (!in_array($total['code'], $this->_ignore_order_totals) && strstr($total['code'], 'shipping') === FALSE) { $gitem = new GoogleItem($total['title'], '', '1', $total['value'] + $total['tax']); $gitem->SetMerchantPrivateItemData(new MerchantPrivateItemData(array('order_total' => base64_encode(serialize($total))))); $cart->AddItem($gitem); } else { if (strstr($total['code'], 'shipping') !== FALSE) { $shipping_cost = $total['value'] + $total['tax']; } } } //shipping method $cart->AddShipping(new GooglePickUp($osC_ShoppingCart->getShippingMethod('title'), $shipping_cost)); } else { $gitem = new GoogleItem(STORE_NAME, '', 1, $osC_ShoppingCart->getTotal()); $gitem->SetMerchantPrivateItemData(new MerchantPrivateItemData(array('item' => base64_encode(serialize(STORE_NAME))))); $cart->AddItem($gitem); } //continue shopping url $cart->SetContinueShoppingUrl(osc_href_link(FILENAME_CHECKOUT, 'process', 'NOSSL', null, null, true)); //edit cart url $cart->SetEditCartUrl(osc_href_link(FILENAME_CHECKOUT, '', 'NOSSL', null, null, true)); // Request buyer's phone number $cart->SetRequestBuyerPhone(false); $private_data = $osC_Session->getID() . ';' . $osC_Session->getName(); $cart->SetMerchantPrivateData(new MerchantPrivateData(array('orders_id' => $this->_order_id, 'session-data' => $private_data))); // Display Google Checkout button return $cart->CheckoutButtonCode(); }
public function preparePayment() { require_once dirname(__FILE__) . '/library/googlecart.php'; require_once dirname(__FILE__) . '/library/googleitem.php'; require_once dirname(__FILE__) . '/library/googleshipping.php'; $currency = $this->getCurrency($this->context->cart->id_currency); if ($this->context->cart->id_currency != $currency->id) { $this->context->cart->id_currency = (int) $currency->id; $this->context->cookie->id_currency = (int) $this->context->cart->id_currency; $this->context->cart->update(); Tools::redirect('modules/' . $this->name . '/payment.php'); } $googleCart = new GoogleCart(Configuration::get('GCHECKOUT_MERCHANT_ID'), Configuration::get('GCHECKOUT_MERCHANT_KEY'), Configuration::get('GCHECKOUT_MODE'), $currency->iso_code); foreach ($this->context->cart->getProducts() as $product) { $googleCart->AddItem(new GoogleItem(utf8_decode($product['name'] . ((isset($product['attributes']) and !empty($product['attributes'])) ? ' - ' . $product['attributes'] : '')), utf8_decode($product['description_short']), (int) $product['cart_quantity'], $product['price_wt'], strtoupper(Configuration::get('PS_WEIGHT_UNIT')), (double) $product['weight'])); } if ($wrapping = $this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING)) { $googleCart->AddItem(new GoogleItem(utf8_decode($this->l('Wrapping')), '', 1, $wrapping)); } if (_PS_VERSION_ < '1.5') { foreach ($this->context->cart->getDiscounts() as $voucher) { $googleCart->AddItem(new GoogleItem(utf8_decode($voucher['name']), utf8_decode($voucher['description']), 1, '-' . $voucher['value_real'])); } } else { foreach ($this->context->cart->getCartRules() as $cart_tule) { $googleCart->AddItem(new GoogleItem(utf8_decode($cart_tule['code']), utf8_decode($cart_tule['name']), 1, '-' . $cart_tule['value_real'])); } } if (!Configuration::get('GCHECKOUT_NO_SHIPPING')) { $carrier = new Carrier((int) $this->context->cart->id_carrier, $this->context->language->id); $googleCart->AddShipping(new GoogleFlatRateShipping(utf8_decode($carrier->name), $this->context->cart->getOrderShippingCost($this->context->cart->id_carrier))); } $googleCart->SetEditCartUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'order.php'); $googleCart->SetContinueShoppingUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'order-confirmation.php'); $googleCart->SetRequestBuyerPhone(false); $googleCart->SetMerchantPrivateData($this->context->cart->id . '|' . $this->context->cart->secure_key); $total = $this->context->cart->getOrderTotal(); $this->context->smarty->assign(array('googleCheckoutExtraForm' => $googleCart->CheckoutButtonCode($this->l('Pay with GoogleCheckout'), 'LARGE'), 'total' => $total, 'googleTotal' => $total, 'GC_Link' => _PS_VERSION_ >= '1.5' ? $this->context->link->getPageLink('order', true, NULL) : $this->context->link->getPageLink('order.php', true))); }
function Usecase($seperator, $sessionid, $fromcheckout) { global $wpdb, $wpsc_cart; $purchase_log_sql = "SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= " . $sessionid . " LIMIT 1"; $purchase_log = $wpdb->get_results($purchase_log_sql, ARRAY_A); $cart_sql = "SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`='" . $purchase_log[0]['id'] . "'"; $wp_cart = $wpdb->get_results($cart_sql, ARRAY_A); $merchant_id = get_option('google_id'); $merchant_key = get_option('google_key'); $server_type = get_option('google_server_type'); $currency = get_option('google_cur'); $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); $transact_url = get_option('transact_url'); $returnURL = $transact_url . $seperator . "sessionid=" . $sessionid . "&gateway=google"; $cart->SetContinueShoppingUrl($returnURL); $cart->SetEditCartUrl(get_option('shopping_cart_url')); $no = 1; //exit("<pre>".print_r($wpsc_cart,true)."</pre>"); //new item code $no = 0; // $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); // foreach($wpsc_cart->cart_items as $item){ //google prohibited items not implemented $curr = new CURRENCYCONVERTER(); $currency_code = $wpdb->get_results("SELECT `code` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `id`='" . get_option('currency_type') . "' LIMIT 1", ARRAY_A); $local_currency_code = $currency_code[0]['code']; // exit('<pre>'.print_r($_REQUEST,true).'</pre>'); $google_curr = get_option('google_cur'); while (wpsc_have_cart_items()) { wpsc_the_cart_item(); if ($google_curr != $local_currency_code) { $google_currency_productprice = $curr->convert(wpsc_cart_item_price(false) / wpsc_cart_item_quantity(), $google_curr, $local_currency_code); $google_currency_shipping = $curr->convert($wpsc_cart->selected_shipping_amount, $google_curr, $local_currency_code); } else { $google_currency_productprice = wpsc_cart_item_price(false) / wpsc_cart_item_quantity() + wpsc_cart_item_shipping(false); $google_currency_shipping = $wpsc_cart->selected_shipping_amount; } // exit('<pre>'.print_r(wpsc_cart_item_name(),true).'</pre>'); $cartitem["{$no}"] = new GoogleItem(wpsc_cart_item_name(), '', wpsc_cart_item_quantity(), $google_currency_productprice); $cart->AddItem($cartitem["{$no}"]); $no++; } //If there are coupons applied add coupon as a product with negative price if ($wpsc_cart->coupons_amount > 0) { if ($google_curr != $local_currency_code) { $google_currency_productprice = $curr->convert($wpsc_cart->coupons_amount, $google_curr, $local_currency_code); } else { $google_currency_productprice = $wpsc_cart->coupons_amount; } $cartitem[$no] = new GoogleItem('Discount', 'Discount Price', 1, '-' . $google_currency_productprice); // Unit price $cart->AddItem($cartitem[$no]); } // } // Add shipping options if (wpsc_uses_shipping() && $google_currency_shipping > 0) { $Gfilter = new GoogleShippingFilters(); $google_checkout_shipping = get_option("google_shipping_country"); $googleshippingcountries = count($google_checkout_shipping); //exit('<pre>'.print_r($googleshipping, true).'</pre>'); if ($googleshippingcountries == 242) { $Gfilter->SetAllowedWorldArea(true); } else { if (is_array($google_checkout_shipping)) { $google_shipping_country_ids = implode(",", $google_checkout_shipping); } $google_shipping_country = $wpdb->get_col("SELECT `isocode` FROM " . WPSC_TABLE_CURRENCY_LIST . " WHERE id IN (" . $google_shipping_country_ids . ")"); foreach ($google_shipping_country as $isocode) { //exit($isocode); $Gfilter->AddAllowedPostalArea($isocode); if ($isocode == 'US') { $Gfilter->SetAllowedCountryArea('ALL'); } } } $Gfilter->SetAllowUsPoBox(false); $ship_1 = new GoogleFlatRateShipping('Flat Rate Shipping', $google_currency_shipping); $ship_1->AddShippingRestrictions($Gfilter); $cart->AddShipping($ship_1); } //wpsc_google_shipping_quotes(); // Add tax rules //if ($_SESSION['wpsc_selected_country']=='US'){ //set default tax //exit('<pre>'.print_r($_SESSION,true).'</pre>'); $sql = "SELECT `name`, `tax` FROM " . WPSC_TABLE_REGION_TAX . " WHERE id='" . $_SESSION['wpsc_selected_region'] . "'"; //exit('<pre>'.print_r($sql, true).'</pre>'); $state_name = $wpdb->get_row($sql, ARRAY_A); //exit('<pre>'.print_r($state_name, true).'</pre>'); $defaultTax = $state_name['tax'] / 100; $tax_rule = new GoogleDefaultTaxRule($defaultTax); $sql = "SELECT `code` FROM " . WPSC_TABLE_REGION_TAX . " WHERE `country_id`='136' AND `tax` = " . $state_name['tax']; $states = $wpdb->get_col($sql); //exit('<pre>'.print_r($states, true).'</pre>'); $tax_rule->SetStateAreas((array) $states); $cart->AddDefaultTaxRules($tax_rule); //get alternative tax rates $sql = "SELECT DISTINCT `tax` FROM " . WPSC_TABLE_REGION_TAX . " WHERE `tax` != 0 AND `tax` !=" . $state_name['tax'] . " AND `country_id`='136' ORDER BY `tax`"; $othertax = $wpdb->get_col($sql); $i = 1; //exit('<pre>'.print_r($othertax, true).'</pre>'); foreach ($othertax as $altTax) { $sql = "SELECT `code` FROM " . WPSC_TABLE_REGION_TAX . " WHERE `country_id`='136' AND `tax`=" . $altTax; $alt = $wpdb->get_col($sql); $altTax = $altTax / 100; $alt_google_tax = new GoogleDefaultTaxRule($altTax); $alt_google_tax->SetStateAreas($alt); //$g = new GoogleAlternateTaxTable('Alt Tax'.$i); //$g->AddAlternateTaxRules($alt_google_tax); $cart->AddDefaultTaxRules($alt_google_tax); // exit(print_r($alt,true)); $i++; } //} if (get_option('google_button_size') == '0') { $google_button_size = 'BIG'; } elseif (get_option('google_button_size') == '1') { $google_button_size = 'MEDIUM'; } elseif (get_option('google_button_size') == '2') { $google_button_size = 'SMALL'; } // Display Google Checkout button //echo '<pre>'.print_r($cart, true).'</pre>'; //unset($_SESSION['wpsc_sessionid']); //if($fromCheckout){ echo $cart->CheckoutButtonCode($google_button_size); //} }
function showCart() { session_start(); $user = $_SESSION['userid']; $cart = $_SESSION[$user . 'cart']; //No payment Checkout //---------------------------------- $genericCart = new GenericCart(); //---------------------------------- //Google Checkout //---------------------------------- $config_file = "checkout/google_checkout/google.conf"; $comment = "#"; $fp = fopen($config_file, "r"); while (!feof($fp)) { $line = trim(fgets($fp)); if ($line && !ereg("^{$comment}", $line)) { list($option, $value) = split("=", $line, 2); $config_values[$option] = $value; } } fclose($fp); $merchant_id = $config_values['CONFIG_MERCHANT_ID']; $merchant_key = $config_values['CONFIG_MERCHANT_KEY']; $server_type = $config_values['CONFIG_SERVER_TYPE']; $currency = $config_values['CONFIG_CURRENCY']; $editCartURL = $config_values['CONFIG_EDIT_URL']; $continueShoppingURL = $config_values['CONFIG_CONTINUE_URL']; $googlecart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency); $googlecart->SetEditCartUrl($editCartURL); $googlecart->SetContinueShoppingUrl($continueShoppingURL); //---------------------------------- if ($cart) { $items = explode(',', $cart); $contents = array(); foreach ($items as $item) { $contents[$item] = isset($contents[$item]) ? $contents[$item] + 1 : 1; } $formattedShopCartItems = array(); $result = array(); foreach ($contents as $i => $qty) { $type = substr($i, 0, 1); $id = substr($i, 2); $item = refactored_db_getItem($id); $subtotal = $item['price'] * $qty; $scitem = array($item['name'], $item['description'], $item['price'], $qty, $i, $subtotal, $item['id'], $type); array_push($formattedShopCartItems, $scitem); //No payment Checkout //---------------------------------- if (!$item['billable']) { $genericItem = new GenericItem($item['name'], $item['description'], $qty, 0); // Unit price $genericCart->AddItem($genericItem); } //---------------------------------- //Google Checkout //---------------------------------- if ($item['billable']) { $googleitem = new GoogleItem($item['name'], $item['description'], $qty, $item['price']); // Unit price $googleitem->SetMerchantItemId($item['id']); //TODO:Change email to order email $googleitem->SetEmailDigitalDelivery("*****@*****.**"); $googlecart->AddItem($googleitem); } //---------------------------------- } } //Checkout Buttons $output[] = '<div id="checkoutButtonsContainer">'; $buttonsCount = 0; if (count($genericCart->item_arr)) { $buttonsCount++; $output[] = $genericCart->CheckoutButtonCode(); } if (count($googlecart->item_arr)) { $buttonsCount++; $output[] = $googlecart->CheckoutButtonCode("SMALL"); $output[] = "<div class='ui-state-error' style='padding: 0pt 0.7em; float:left; width:30em;'><p><span class='ui-icon ui-icon-alert' style='float: left; margin-right: 0.3em;'></span>Please when you process the order with Google Checkout, <strong>DO NOT</strong> choose the option 'Keep my e-mail address confidential' because your order will be lost.</p></div>"; } $output[] = '</div>'; $shoppingCart = $formattedShopCartItems; $checkoutButtons = join('', $output); $response = array("shoppingCart" => json_encode($formattedShopCartItems), "checkoutButtons" => $checkoutButtons, "buttonsCount" => $buttonsCount); $_SESSION[$user . 'cart'] = $cart; return $response; }
public function preparePayment() { if ($this->testmode == true) { $environment = 'sandbox'; } else { $environment = 'production'; } $Gcart = new GoogleCart($this->arr_settings['account'], $this->arr_settings['secret'], $environment, $this->arr_order['currency']); $Gcart->SetContinueShoppingUrl($this->url_return_success); $Gitem = new GoogleItem($this->arr_order['id'], "Your Purchase (Order reference #" . $this->arr_order['id'] . ")", 1, $this->arr_order['total']); $Gcart->AddItem($Gitem); $Gcart->SetMerchantPrivateData(new MerchantPrivateData(array('shopguid' => $this->arr_settings['shopguid'], 'orderguid' => $this->arr_order['guid'], 'ip-address' => $this->arr_settings['ip']))); $GcartXML = $Gcart->GetXML(); $Grequest = new GoogleRequest($Gcart->merchant_id, $Gcart->merchant_key, $environment, $Gcart->currency); list($status, $this->url_integration) = $Grequest->SendServer2ServerCart($GcartXML, false); if ($this->url_integration == "") { echo "An error occurred while sending the basket to google. Check the google checkout 'Integration console'."; die; } }