2014-09-20 53 views
0

幫助我們在頁面加載時製作頁面加載器。我正在做一些貝寶支付系統。當我看了一些頁面,當頁面指向paypal頁面時,他們在頁面正在處理時將一些加載器(ajax加載器)重定向到「Paypal網關」。我還計劃在加載時在其他頁面中放置一些Ajax加載器。所以請幫助我們。這是我的代碼。如何在頁面加載時使用ajax-loader PHP

<?php 
      $current_url = base64_encode($url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); 

       if(isset($_POST['checkoutnow'])){ 
        header('Location: checkout_now1.php'); 
       } 
       if(isset($_SESSION["products"])){ 
        $total = 0; 
        echo '<ol>'; 
        echo '<form action="paypal-express-checkout/process.php" method="POST">'; 
        $cart_items = 0; 

         foreach ($_SESSION["products"] as $cart_itm) 
    { 
     $product_code = $cart_itm["code"]; 
     $results = $mysqli->query("SELECT product_name,product_desc, price FROM products WHERE product_code='$product_code' LIMIT 1"); 
     $obj = $results->fetch_object(); 

     echo '<li class="cart-itm">'; 
     echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'">&times;</a></span>'; 
     echo '<div class="p-price">'.$currency.$obj->price.'</div>'; 
     echo '<div class="product-info">'; 
     echo '<h3>'.$obj->product_name.' (Code :'.$product_code.')</h3> '; 
     echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>'; 
     echo '<div>'.$obj->product_desc.'</div>'; 
     echo '</div>'; 
     echo '</li>'; 
     $subtotal = ($cart_itm["price"]*$cart_itm["qty"]); 
     $total = ($total + $subtotal); 

     echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->product_name.'" />'; 
     echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />'; 
     echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->product_desc.'" />'; 
     echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />'; 
     $cart_items ++; 

         } 
        echo '</ol>'; 
        echo '<strong>Total: '.$currency.$total.'</strong><br />'; 

        echo '<center> 
          <div id="check_out"> 
           <a href="checkout_now1.php"><button>Check Out with US</button></a><br />OR<br /> 
           <div class="paypal-button"><input type="image" src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckoutsm.gif"></div> 
          </center> 
          </div>'; 
           echo '</form>'; 
       }else{ 
        echo 'Your Cart is Empty<br />Go to <a href="index.php">Home</a> And Order'; 

       } 

     ?> 

回答

0

爲此,您可以使用JavaScript方法「setInterval()」在兩個或多個進程之間放置一個時間。我沒有哪裏是你條件把這個延遲,但我聯繫你我的代碼,並希望它能幫助:

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset = "utf-8" /> 
     <title> title-page </title> 
    </head> 
    <body> 
     <script type = "text/javascript"> 
      function loading() { 
       var miliSecTime = 1000; // 1 sec time between each process for example 
       document.getElementById("waitDiv").InnerHtml = "<img src = 'wait.gif' />"; 
       var timer = setInterval(function() { 
         // BEGIN : Your process 

         // END : Your process 

         // Condition to abort the process 
         // Likely when you want to stop 
         // the waiting view 
         if (leftLoading_condition) { 
          clearInterval(timer); 
          document.getElementById("waitDiv").innerHTML = ""; // Hidding the wait view 
         } 
        }, 
        miliSecTime 
       ); 
      } 
     </script> 
     <!-- This is where you want to show you wait gif --> 
     <div id = "waitDiv"> 

     </div> 
     <input type = "button" onClick = "loading()" /> 
    </body> 
</html> 

的「setInterval()」函數有兩個參數:第一個是你的作用,二是您希望在每次打勾之間放置延遲。因此,你將一個過程放入函數方法中,訣竅是放置一個左側的tick事件條件,並調用方法「clearInterval」來停止滴答。

因此,這裏是這段代碼的工作:

功能「裝載」通過點擊按鈕調用。該方法啓動包含在「function() {}」代碼中的過程。在啓動這個過程之前,我們展示了wait gif,它可以是一個加載gif或其他任何東西。然後,進程循環運行,直到左邊的刻度條件(if()調用)。如果我們已經達到了過程的結束時間,則通過清除間隔參數(通過調用「clearInterval()」方法)來中止計時器。

+0

感謝兄弟。讓我試試這個兄弟。我會和你聯繫。我希望它會加載。 :) – Believe 2014-09-20 19:39:47

+0

如果你有一個進程,並且你只是想在進程和結果之間設置一個延遲,那麼就看看「setTimeout()」的javascript函數,它與我在這個例子中使用的類似。希望你得到你想要的! – 2014-09-20 19:42:21

+0

Bro。你的代碼沒有任何改變。 :(你認爲什麼是錯的? – Believe 2014-09-20 19:46:18

0
<?php 
session_start(); 
include_once("../config.php"); 
include_once("paypal.class.php"); 

$paypalmode = ($PayPalMode=='sandbox') ? '.sandbox' : ''; 

if($_POST) //Post Data received from product list page. 
{ 
//Other important variables like tax, shipping cost 
$TotalTaxAmount  = 2.58; //Sum of tax for all items in this order. 
$HandalingCost  = 2.00; //Handling cost for this order. 
$InsuranceCost  = 1.00; //shipping insurance cost for this order. 
$ShippinDiscount = -3.00; //Shipping discount for this order. Specify this as negative number. 
$ShippinCost  = 3.00; //Although you may change the value later, try to pass in a shipping amount that is reasonably accurate. 

//we need 4 variables from product page Item Name, Item Price, Item Number and Item Quantity. 
//Please Note : People can manipulate hidden field amounts in form, 
//In practical world you must fetch actual price from database using item id. 
//eg : $ItemPrice = $mysqli->query("SELECT item_price FROM products WHERE id = Product_Number"); 
$paypal_data =''; 
$ItemTotalPrice = 0; 

foreach($_POST['item_name'] as $key=>$itmname) 
{ 
    $product_code = filter_var($_POST['item_code'][$key], FILTER_SANITIZE_STRING); 

    $results = $mysqli->query("SELECT product_name, product_desc, price FROM products WHERE product_code='$product_code' LIMIT 1"); 
    $obj = $results->fetch_object(); 

    $paypal_data .= '&L_PAYMENTREQUEST_0_NAME'.$key.'='.urlencode($obj->product_name); 
    $paypal_data .= '&L_PAYMENTREQUEST_0_NUMBER'.$key.'='.urlencode($_POST['item_code'][$key]); 
    $paypal_data .= '&L_PAYMENTREQUEST_0_AMT'.$key.'='.urlencode($obj->price);  
    $paypal_data .= '&L_PAYMENTREQUEST_0_QTY'.$key.'='. urlencode($_POST['item_qty'][$key]); 

    // item price X quantity 
    $subtotal = ($obj->price*$_POST['item_qty'][$key]); 

    //total price 
    $ItemTotalPrice = $ItemTotalPrice + $subtotal; 

    //create items for session 
    $paypal_product['items'][] = array('itm_name'=>$obj->product_name, 
             'itm_price'=>$obj->price, 
             'itm_code'=>$_POST['item_code'][$key], 
             'itm_qty'=>$_POST['item_qty'][$key] 
             ); 
} 

//Grand total including all tax, insurance, shipping cost and discount 
$GrandTotal = ($ItemTotalPrice + $TotalTaxAmount + $HandalingCost + $InsuranceCost + $ShippinCost + $ShippinDiscount); 


$paypal_product['assets'] = array('tax_total'=>$TotalTaxAmount, 
          'handaling_cost'=>$HandalingCost, 
          'insurance_cost'=>$InsuranceCost, 
          'shippin_discount'=>$ShippinDiscount, 
          'shippin_cost'=>$ShippinCost, 
          'grand_total'=>$GrandTotal); 

//create session array for later use 
$_SESSION["paypal_products"] = $paypal_product; 

//Parameters for SetExpressCheckout, which will be sent to PayPal 
$padata = '&METHOD=SetExpressCheckout'. 
      '&RETURNURL='.urlencode($PayPalReturnURL). 
      '&CANCELURL='.urlencode($PayPalCancelURL). 
      '&PAYMENTREQUEST_0_PAYMENTACTION='.urlencode("SALE"). 
      $paypal_data.    
      '&NOSHIPPING=0'. //set 1 to hide buyer's shipping address, in-case products that does not require shipping 
      '&PAYMENTREQUEST_0_ITEMAMT='.urlencode($ItemTotalPrice). 
      '&PAYMENTREQUEST_0_TAXAMT='.urlencode($TotalTaxAmount). 
      '&PAYMENTREQUEST_0_SHIPPINGAMT='.urlencode($ShippinCost). 
      '&PAYMENTREQUEST_0_HANDLINGAMT='.urlencode($HandalingCost). 
      '&PAYMENTREQUEST_0_SHIPDISCAMT='.urlencode($ShippinDiscount). 
      '&PAYMENTREQUEST_0_INSURANCEAMT='.urlencode($InsuranceCost). 
      '&PAYMENTREQUEST_0_AMT='.urlencode($GrandTotal). 
      '&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode). 
      '&LOCALECODE=GB'. //PayPal pages to match the language on your website. 
      '&LOGOIMG='. //site logo 
      '&CARTBORDERCOLOR=FFFFFF'. //border color of cart 
      '&ALLOWNOTE=1'; 

    //We need to execute the "SetExpressCheckOut" method to obtain paypal token 
    $paypal= new MyPayPal(); 
    $httpParsedResponseAr = $paypal->PPHttpPost('SetExpressCheckout', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode); 

    //Respond according to message we receive from Paypal 
    if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) 
    { 
      //Redirect user to PayPal store with Token received. 
      $paypalurl ='https://www'.$paypalmode.'.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token='.$httpParsedResponseAr["TOKEN"].''; 
      header('Location: '.$paypalurl); 
    } 
    else 
    { 
     //Show error message 
     echo '<div style="color:red"><b>Error : </b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>'; 
     echo '<pre>'; 
     print_r($httpParsedResponseAr); 
     echo '</pre>'; 
    } 

} 

//Paypal redirects back to this page using ReturnURL, We should receive TOKEN and Payer ID 
if(isset($_GET["token"]) && isset($_GET["PayerID"])) 
{ 
//we will be using these two variables to execute the "DoExpressCheckoutPayment" 
//Note: we haven't received any payment yet. 

$token = $_GET["token"]; 
$payer_id = $_GET["PayerID"]; 

//get session variables 
$paypal_product = $_SESSION["paypal_products"]; 
$paypal_data = ''; 
$ItemTotalPrice = 0; 

foreach($paypal_product['items'] as $key=>$p_item) 
{  
    $paypal_data .= '&L_PAYMENTREQUEST_0_QTY'.$key.'='. urlencode($p_item['itm_qty']); 
    $paypal_data .= '&L_PAYMENTREQUEST_0_AMT'.$key.'='.urlencode($p_item['itm_price']); 
    $paypal_data .= '&L_PAYMENTREQUEST_0_NAME'.$key.'='.urlencode($p_item['itm_name']); 
    $paypal_data .= '&L_PAYMENTREQUEST_0_NUMBER'.$key.'='.urlencode($p_item['itm_code']); 

    // item price X quantity 
    $subtotal = ($p_item['itm_price']*$p_item['itm_qty']); 

    //total price 
    $ItemTotalPrice = ($ItemTotalPrice + $subtotal); 
} 

$padata = '&TOKEN='.urlencode($token). 
      '&PAYERID='.urlencode($payer_id). 
      '&PAYMENTREQUEST_0_PAYMENTACTION='.urlencode("SALE"). 
      $paypal_data. 
      '&PAYMENTREQUEST_0_ITEMAMT='.urlencode($ItemTotalPrice). 
      '&PAYMENTREQUEST_0_TAXAMT='.urlencode($paypal_product['assets']['tax_total']). 
      '&PAYMENTREQUEST_0_SHIPPINGAMT='.urlencode($paypal_product['assets']['shippin_cost']). 
      '&PAYMENTREQUEST_0_HANDLINGAMT='.urlencode($paypal_product['assets']['handaling_cost']). 
      '&PAYMENTREQUEST_0_SHIPDISCAMT='.urlencode($paypal_product['assets']['shippin_discount']). 
      '&PAYMENTREQUEST_0_INSURANCEAMT='.urlencode($paypal_product['assets']['insurance_cost']). 
      '&PAYMENTREQUEST_0_AMT='.urlencode($paypal_product['assets']['grand_total']). 
      '&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode); 

//We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user. 
$paypal= new MyPayPal(); 
$httpParsedResponseAr = $paypal->PPHttpPost('DoExpressCheckoutPayment', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode); 

//Check if everything went ok.. 
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) 
{ 

     echo '<h2>Success</h2>'; 
     echo 'Your Transaction ID : '.urldecode($httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]); 

      /* 
      //Sometimes Payment are kept pending even when transaction is complete. 
      //hence we need to notify user about it and ask him manually approve the transiction 
      */ 

      if('Completed' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) 
      { 
       echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>'; 
      } 
      elseif('Pending' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) 
      { 
       echo '<div style="color:red">Transaction Complete, but payment is still pending! '. 
       'You need to manually authorize this payment in your <a target="_new" href="http://www.paypal.com">Paypal Account</a></div>'; 
      } 

      // we can retrive transection details using either GetTransactionDetails or GetExpressCheckoutDetails 
      // GetTransactionDetails requires a Transaction ID, and GetExpressCheckoutDetails requires Token returned by SetExpressCheckOut 
      $padata = '&TOKEN='.urlencode($token); 
      $paypal= new MyPayPal(); 
      $httpParsedResponseAr = $paypal->PPHttpPost('GetExpressCheckoutDetails', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode); 

      if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) 
      { 

       echo '<br /><b>Stuff to store in database :</b><br />'; 

       echo '<pre>'; 
       /* 
       #### SAVE BUYER INFORMATION IN DATABASE ### 
       //see (http://www.sanwebe.com/2013/03/basic-php-mysqli-usage) for mysqli usage 
       //use urldecode() to decode url encoded strings. 

       $buyerName = urldecode($httpParsedResponseAr["FIRSTNAME"]).' '.urldecode($httpParsedResponseAr["LASTNAME"]); 
       $buyerEmail = urldecode($httpParsedResponseAr["EMAIL"]); 

       //Open a new connection to the MySQL server 
       $mysqli = new mysqli('host','username','password','database_name'); 

       //Output any connection error 
       if ($mysqli->connect_error) { 
        die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error); 
       }  

       $insert_row = $mysqli->query("INSERT INTO BuyerTable 
       (BuyerName,BuyerEmail,TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY) 
       VALUES ('$buyerName','$buyerEmail','$transactionID','$ItemName',$ItemNumber, $ItemTotalPrice,$ItemQTY)"); 

       if($insert_row){ 
        print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />'; 
       }else{ 
        die('Error : ('. $mysqli->errno .') '. $mysqli->error); 
       } 

       */ 

       echo '<pre>'; 
       print_r($httpParsedResponseAr); 
       echo '</pre>'; 
      } else { 
       echo '<div style="color:red"><b>GetTransactionDetails failed:</b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>'; 
       echo '<pre>'; 
       print_r($httpParsedResponseAr); 
       echo '</pre>'; 

      } 

}else{ 
     echo '<div style="color:red"><b>Error : </b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>'; 
     echo '<pre>'; 
     print_r($httpParsedResponseAr); 
     echo '</pre>'; 
} 
} 
?> 
相關問題