ruạṛ
<?php /** * Convert cart to order and send to payment gateway, order form or invoice * @version 0.10 * @author Robert Urquhart <programmer@activatedesign.co.nz> * @package WEP-CMS * @todo institute a check that the request for this page is coming from a valid page on-site */ //print_r($_POST); exit; //debugging //these calls will get repeated in template.php so use require_once $data_dir = $_SERVER['DOCUMENT_ROOT'].'/admin/scripts-includes/'; $template_dir = $_SERVER['DOCUMENT_ROOT'].'/resources/template/'; require_once $data_dir.'universal.php'; require_once $template_dir.'functions.php'; /* * start the session (after includes so objects stored in $_SESSION are created properly) */ session_start(); $connID = connect_to_db(); /** * suhosin workaround - load session user data * @var object $customer * @var object $cart */ $customer = user_load(); $cart = $customer->load_cart(); if($cart->num_products < 1 || $cart->cart_total <= 0) { getout('',select_one('page_data','path','page_type','cart')); exit; } /** * get form data * @var array $fields whitelist in order of email generation */ $fields = array( 'customer_name' , 'email' , 'phone' , 'delivery_address' , 'delivery_instructions' , 'payment' ); /** * order reference - will already exist if customer has returned from payment on a fail * @var int $reference using a timestamp */ $reference = ($cart->reference) ? $cart->reference : time(); $cart->reference = $reference; /** * generate customer details portion of email and form-return json * @var string $mailbody * @var array $mailsub aggregates substrings from arrays * @var array $mailexclude fields in $fields that we don't want to include in the email (ie related to processing only) * - keep these to a minimum for processing integrity * @var string $json */ $mailbody = 'Contact and delivery details '; $mailsub = array(); // $mail_exclude = array(); $json = '{'; foreach($fields as $f) { $var = str_replace('-','_',$f); $v = $cart->customer["$var"] = $_POST[$f]; $$var = clean_plain_data($v); //dynamic variable generation from $fields whitelist $mailbody .= (!in_array($f,$mail_exclude)) ? ucfirst(str_replace(array('-','_'),' ',$f)).': '.str_replace("\r\n","\n",$v)." \n\n" : ''; $n = $var; $x = str_replace('"',"'",trim($v)); $x = str_replace(array("\r\n","\n","\t"),'\n',trim($v)); // line breaks etc break the javascript $json .= '"'.$n.'":"'.$x.'",'; } $cart->customer['json'] = $json = rtrim($json,',').'}'; /** * validate * @var string $message */ $message = ''; if($customer_name == '') { $message .= 'Please enter your name <br />'; } if(!is_email($email)) { $message .= 'Please check your email address<br />'; } if($phone == '' ) { $message .= 'Please enter a phone number <br />'; } if($delivery_address == '' ) { $message .= 'Please enter a delivery address <br />'; } if($message != '') { setcookie('checkoutformJson', $json, time()+30,'/'); setcookie('formMessage', '<p class="message">'.$message.'</p>', time()+30,'/'); getout('',select_one('page_data','path','page_type','cart').'#checkout'); exit; } /** * if not a logged in user preserve contact details for next visit to checkout */ if(!$customer->user_id) { $customer->name = $customer_name; $customer->address = $delivery_address; $customer->phone = $phone; $customer->email = $email; user_save($customer); } /** * generate fees and shipping * @var string $payment if not defined in form * @todo define default in settings */ if(strpos(strtolower($payment),'paypal') !== false) { $payment = 'Paypal'; } elseif(strpos(strtolower($payment),'credit card') !== false) { $payment = 'Credit Card'; } else { $payment = 'Bank Deposit'; } /** * generate order summary * @var float $total total cost of order * @var string $format line format for spacing * @var string $break string to use for dividing lines in order * @var string $order order detais portion of email */ $total = $cart->order_total(); $format = '|%4s | %-50s|%12s |'; $break = sprintf("%'-73s",''); $order = 'Order details Reference: '.$reference.' '.$break.' '.sprintf($format, 'Qty', 'Item', 'Cost').' '.$break.' '; foreach($cart->products as $ref => $p) { $order .= sprintf($format, $p->quantity, html_entity_decode($p->name,ENT_QUOTES), format_price($p->price*$p->quantity,2))."\n"; foreach($p->selected as $o => $opt){ if($opt != '') { $opt = html_entity_decode($opt,ENT_QUOTES); //$oid = ltrim($o,'options_'); //$label = $p->product_options_fields->get_option_by_id($oid)->text; $order .= sprintf($format, ' ', $o.': '.$opt, ' ', ' ')."\n"; } } } $order .= $break.' '.sprintf($format,$cart->num_items, 'Subtotal', format_price($cart->cart_total,2)).' '.$break.' '; if($cart->transaction_fee){ $order.= sprintf($format, '', 'Transaction fee', format_price($cart->transaction_fee,2)).' '.$break.' '; } if($cart->discount_code){ $order.= sprintf($format, '', 'Discount code '.$cart->discount_code.' ('.$cart->discount_format().')', '-'.format_price($cart->discount_amount,2)).' '.$break.' '; } if($cart->ship_id){ $order.= sprintf($format, '', 'Shipping ('.$cart->shipping_location.')', format_price($cart->shipping_cost,2)).' '.$break.' '; } $order .= sprintf($format, '', 'Total', format_price($total,2)).' '.$break.' '; /** * put order summary in database * @var string $order_description summary version of order */ $k = array_keys($cart->products); $p = $cart->products["{$k[0]}"]; $order_description = $p->quantity.' of '.$p->name; if($cart->num_products > 1) { $order_description .= ' & '.($cart->num_items - $p->quantity).' other items'; } $cart->description = $order_description; if(!$insert = mysql_query("insert into orders ( order_ref , order_description , order_total , shipping_location , shipping_cost , discount_code , discount , discount_type , discount_amount , customer_id , customer_name , customer_email , customer_phone , delivery_address , delivery_instructions , payment_method , transaction_fee ) values ( '$reference' , '$order_description' , '".$cart->cart_total."' , '".$cart->shipping_location."' , '".$cart->shipping_cost."' , '".$cart->discount_code."' , '".$cart->discount_var."' , '".$cart->discount_type."' , '".$cart->discount_amount."' , '".$customer->user_id."' , '$customer_name' , '$email' , '$phone' , '$delivery_address' , '$delivery_instructions' , '$payment' , '".$cart->transaction_fee."' )")) { setcookie('checkoutformJson', $json, time()+30,'/'); setcookie('formMessage', '<p class="message">We\'re sorry, there was a problem adding your order to the database. Please try again.</p>', time()+30,'/'); getout('',select_one('page_data','path','page_type','cart')); exit; } /** * put individual items of order in database * @var int $order_id db unique id of order summary record * @var string $pInsert product values to insert */ $order_id = mysql_insert_id(); $pInsert = ''; foreach($cart->products as $ref => $p) { $qDesc = ''; //$p->price_data('quantity_description','quantity',$p->quantity); $pInsert .= "('$order_id','$ref','".$p->name ."','".$p->cat_id ."','".$p->category_name()."','".$p->price ."','".$p->quantity ."','$qDesc','".json_encode($p->selected)."'),"; } $pInsert = rtrim($pInsert,','); if(!$insert = mysql_query("insert into order_products ( order_id , product_id , product_name , category_id , category_name , price , quantity , quantity_description , options ) values $pInsert ")) { setcookie('checkoutformJson', $json, time()+30,'/'); setcookie('formMessage', '<p>We\'re sorry, there was a problem adding your order to the database. Please try again.</p>', time()+30,'/'); @mysql_query("delete from orders where order_id = '$order_id'"); //prevent duplicate orders //have to do this after any mysql_error debugging getout('',select_one('page_data','path','page_type','cart')); exit; } /** * store email body (order details) for later use and send email/s * @var string $email_address site email address * @var string $subject email subject * @var string $headers email headers */ $cart->customer['email_text'] = $mailbody = $order.' '.$mailbody; mysql_query("insert into order_temp (order_id, json, email_text) values ('$order_id', '".clean_plain_data($json)."', '".clean_plain_data($mailbody)."')");// or die('!'+mysql_error()); //echo "<pre>$mailbody</pre>"; exit; //debugging $email_address = SITE_FROM_ADDRESS; //$email_address = 'matt@activatedesign.co.nz'; //testing //$email_address = 'programmer@activatedesign.co.nz'; //development $subject = 'Order '.$reference.' placed at '.SITE_FROM_NAME.' website'; $headers = "From: $email_address" . "\n" . "Reply-To: $email_address" . "\n" . "Return-Path: $email_address" . "\n" . 'X-Mailer: PHP/' . phpversion(); $headers2 = "From: $email" . "\n" . "Reply-To: $email" . "\n" . "Return-Path: $email" . "\n" . 'X-Mailer: PHP/' . phpversion(); //to site admin mail($email_address, $subject, $mailbody, $headers2); /** * break out individual names and address portions from single form field for submission to payment gateway * @var array $names * @var array $addresses */ $names = explode(' ',$customer_name,2); $cart->customer['name'] = $customer_name; $cart->customer['first_name'] = $first_name = $names[0]; $cart->customer['last_name'] = $last_name = $names[1]; $cart->customer['phone'] = $phone; $cart->customer['email'] = $email; $cart->customer['delivery_address'] = $delivery_address; $cart->customer['delivery_instructions'] = $delivery_instructions; $addresses = explode("\n",$delivery_address); switch($payment) { //paypal case 'Paypal': /* * uses global PAYPAL_TEST_MODE */ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Redirecting to Paypal</title> <link rel="shortcut icon" href="/favicon.ico" /> <link rel="stylesheet" type="text/css" href="/resources/template/style.css" /> <script src="/resources/jquery/jquery-1.9.1.js" type="text/javascript" ></script> </head> <body style="background: #FFF none; text-align: center;"> <p><img src="/resources/template/to_paypal.gif" /> Please wait while your information is passed to PayPal.</p> <p>If it seems to be taking too long or Javascript is disabled in your browser please click the button below.</p> <p>Please return to <?php echo SITE_FROM_NAME; ?> after you have made your payment to complete your order.</p> <?php if(PAYPAL_TEST_MODE): ?> <div style="border: 1px solid #999; background:#FFF; width: 600px; margin: 0 auto;"> <h1>Testing Mode Enabled</h1> <p><a href="/processes/process-test-simulate-payment.php?order=<?php echo $order_id; ?>">Simulate payment</a></p> <p><a href="/paypal_return_false.php?order=<?php echo $order_id; ?>">Simulate failure and return to checkout</a></p> <p>Click button to proceed to Paypal sandbox</p> </div> <form name="redirect" id="redirect" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" > <?php /* testing real address ?> <input type="hidden" name="business" value="programmer@activatedesign.co.nz"> <?php // */ ?> <?php //* testing sandbox address ?> <input type="hidden" name="business" value="progra_1193784050_biz@activatedesign.co.nz"> <?php // */ ?> <?php else: //live ?> <?php /* paypal is having issues with enctype, re-add when solved enctype="multipart/form-data" */ ?> <form name="redirect" id="redirect" action="https://www.paypal.com/cgi-bin/webscr" method="post" > <input type="hidden" name="business" value="<?php echo PAYPAL_ACCOUNT_EMAIL; ?>"> <?php endif; ?> <input type="hidden" name="cmd" value="_xclick"> <input type="hidden" name="item_name" value="<?php echo $order_description; ?>"> <input type="hidden" name="amount" value="<?php echo $cart->order_total(); ?>"> <input type="hidden" name="address1" value="<?php echo $addresses[0]; ?>"> <input type="hidden" name="address2" value="<?php echo $addresses[1]; ?>"> <input type="hidden" name="city" value="<?php echo $addresses[2]; ?>"> <input type="hidden" name="country" value="NZ"> <input type="hidden" name="email" value="<?php echo $email; ?>"> <input type="hidden" name="first_name" value="<?php echo $first_name; ?>"> <input type="hidden" name="last_name" value="<?php echo $last_name; ?>"> <input type="hidden" name="invoice" value="<?php echo $reference; ?>"> <input type="hidden" name="custom" value="<?php echo $order_id; ?>"> <input type="hidden" name="return" value="http://<?php echo SITE_ROOT; ?>/paypal_return_true.php"> <input type="hidden" name="cancel_return" value="http://<?php echo SITE_ROOT ?>/paypal_return_false.php?order=<?php echo $order_id; ?>"> <input type="hidden" name="rm" value="2"> <?php // 1: return with GET , 2: return with POST ?> <input type="hidden" name="currency_code" value="NZD"> <?php /* ?> <input type="hidden" name="page_style" value=""> <?php // */ ?> <input type="submit" value="PayPal"> </form> <?php if(!PAYPAL_TEST_MODE): ?> <script type="text/javascript"> $(document).ready(function(){ $('#redirect').submit(); }); </script> <?php endif; ?> <p> </p> <p> </p> </body> </html> <?php $cart->empty_cart(); if($customer->user_id) { $customer->update_cart($cart); } else { user_save_cart($cart); } exit; // DPS case 'Credit Card': /* * uses global PXPAY_URL * uses global DPS_ID * uses global DPS_ENCRYPT */ include DOC_ROOT.'/resources/pxpay/PxPay.inc.php'; $PxPay_Url = PXPAY_URL; $PxPay_Userid = DPS_ID; $PxPay_Key = DPS_ENCRYPT; $pxpay = new PxPay_Curl( $PxPay_Url, $PxPay_Userid, $PxPay_Key ); $request = new PxPayRequest(); $http_host = getenv("HTTP_HOST"); $request_uri = getenv("SCRIPT_NAME"); $server_url = "http://$http_host"; $script_url = 'http://'.SITE_ROOT.'/catch-credit-card.php'; #Generate a unique identifier for the transaction $TxnId = uniqid("ID"); #Set PxPay properties $request->setMerchantReference($reference); $request->setAmountInput($total); $request->setTxnData1($order_description); $request->setTxnData2($order_id); $request->setTxnData3(session_id()); $request->setTxnType("Purchase"); $request->setCurrencyInput("NZD"); $request->setEmailAddress($email); $request->setUrlFail($script_url); # can be a dedicated failure page $request->setUrlSuccess($script_url); # can be a dedicated success page $request->setTxnId($TxnId); #The following properties are not used in this case # $request->setEnableAddBillCard($EnableAddBillCard); # $request->setBillingId($BillingId); # $request->setOpt($Opt); #Call makeRequest function to obtain input XML $request_string = $pxpay->makeRequest($request); #Obtain output XML $response = new MifMessage($request_string); #Parse output XML $url = $response->get_element_text("URI"); $valid = $response->get_attribute("valid"); //$_SESSION['ordered']=$cart; //store a copy of cart so this browser can create another one. On payment fail cart will be recovered from this //unset($_SESSION['cart']); $cart->empty_cart(); //leave cart full for refresh/debugging/styling if($customer->user_id) { $customer->update_cart($cart); } else { user_save_cart($cart); } #Redirect to payment page header("Location: $url"); //$content = "<p>!$request_string!$url!$valid</p><p>".nl2br($mailbody).'</p><p>'.$pInsert.'</p>'; //debugging exit; // bank deposit default: /** * send email to customer */ $mailbody = 'Dear '.$first_name.' Thank you for ordering from '.SITE_FROM_NAME.'. Your order details are below and your order will be processed as soon as payment is confirmed. Please deposit '.format_price($cart->order_total()).' to '.BANK_DETAILS.'. '.$mailbody.' - The '.SITE_FROM_NAME.' team'; mail($email, $subject, $mailbody, $headers); /** * generate page content * @var string $title * @var string $content */ $title='Please print for your records'; $script_text = '<p>Thank you for your order. An email has been sent confirming the details and your order will be processed as soon as payment is received.</p> <p>Please deposit '.format_price($cart->order_total(),2).' to '.BANK_DETAILS.'</p> <p class="message">Your basket has now been emptied. You may wish to print this page for your reference.</p> '; $content = include DOC_ROOT.'/resources/template/section_order_print.php'; mysql_query("delete from order_temp where order_id = '$order_id'"); $cart->empty_cart(); if($customer->user_id) { $customer->update_cart($cart); } else { user_save_cart($cart); } } /** * this only runs if not redirected to payment gateway in switch() above * overwrite nav * @todo figure out a way of feeding this into template.php directly */ $connID = connect_to_db(); $page_id = select_one('page_data','page_id','page_type','products'); $parent_chain = build_parent_chain($page_id); $breadcrumbs = build_breadcrumbs($parent_chain); $pages = build_menu_tree(); $nav = build_nav($pages,1,1,1); $categories = build_category_tree(); // recursive function $n = 0; //global for build_cat_nav() $pnav = build_cat_nav($categories); ob_start(); include $template_dir.'header.php'; echo $content; include $template_dir.'footer.php'; ob_end_flush(); exit; ?>
cải xoăn