Paypal - 存储值并在处理完交易后保存

时间:2015-09-08 14:01:29

标签: php paypal

计划:

  1. 填写表格
  2. 值存储在会话中
  3. 处理交易
  4. 如果转换完成,则值将存储在数据库中。
  5. 不存储其他值。
  6. 如何修复insertdata.php(最后一段代码)中的代码,以便删除错误?

    表格 http://jsfiddle.net/christa_mar/b7xpkk2p/1/

    payments.php

    <?php
    
     if ($_POST) {
    if (isset($_POST['proceedtopaypal'])){
        session_start();
    
    include 'connect.php';
    
        $_SESSION['apartment'] = mysqli_real_escape_string($conn, $_POST['apartment']);
        $_SESSION['unitprice'] = mysqli_real_escape_string($conn, $_POST['unitprice']);
        $_SESSION['first_name'] = mysqli_real_escape_string($conn, $_POST['first_name']);
        $_SESSION['last_name'] = mysqli_real_escape_string($conn, $_POST['last_name']);
        $_SESSION['payer_email'] = mysqli_real_escape_string($conn, $_POST['payer_email']);
        $_SESSION['address'] = mysqli_real_escape_string($conn, $_POST['address']);
        $_SESSION['apt_name'] = mysqli_real_escape_string($conn, $_POST['apt_name']);
        $_SESSION['mobile'] = mysqli_real_escape_string($conn, $_POST['mobile']);
        $_SESSION['pax'] = mysqli_real_escape_string($conn, $_POST['pax']);
        $_SESSION['remarks'] = mysqli_real_escape_string($conn, $_POST['remarks']);
        $_SESSION['day_from'] = mysqli_real_escape_string($conn, $_POST['day_from']);
        $_SESSION['month_from'] = mysqli_real_escape_string($conn, $_POST['month_from']);
        $_SESSION['year_from'] = mysqli_real_escape_string($conn, $_POST['year_from']);
        $_SESSION['booking_from'] = $_SESSION['year_from']."-".$_SESSION['month_from']."-".$_SESSION['day_from'];
        $_SESSION['day_to'] = mysqli_real_escape_string($conn, $_POST['day_to']);
        $_SESSION['month_to'] = mysqli_real_escape_string($conn, $_POST['month_to']);
        $_SESSION['year_to'] = mysqli_real_escape_string($conn, $_POST['year_to']);
        $_SESSION['booking_to'] = $_SESSION['year_to']."-".$_SESSION['month_to'] ."-".$_SESSION['day_to'];
        $_SESSION['no_of_nights'] = abs(strtotime($_SESSION['booking_from']) - strtotime($_SESSION['booking_to'])); 
        $_SESSION['quantity'] = floor($_SESSION['no_of_nights'] / (60*60*24));
    
        // paypal settings 
        $paypal_email = 'christabelbusuttil-facilitator@gmail.com';
        $return_url = 'http://localhost/Webdevelopment/V18/apartment-details.php?id=1';
        $cancel_url = 'http://localhost/Webdevelopment/V18/apartment-details.php?id=1';
        $notify_url = 'http://localhost/Webdevelopment/V18/paypal/payments.php';
    
        $item_amount = $_SESSION['unitprice'] * $_SESSION['quantity'];
        $item_name = "Booking at ".$_SESSION['apt_name']." from " .$_SESSION['booking_from'] ." to " .$_SESSION['booking_to'];
        $validdate = false;
        $buttonpressed = false;
        $checkin='<p>Check in date is invalid.</p>';
        $checkout='<p>Check out date is invalid</p>';
        $larger = '<p>Check in date is after check out date</p>';
        $noinfo='<p>please fill in the missing information.</p>';
        $booked='<p>The dates selected are already booked for this apartment</p>';
        $equal = '<p>You need to spend a minimum of 1 night in these apartment</p>';
        $thankyou = '<h5>Thank you</h5><p>thank you for booking an apartment with V18-apartments.</p>';
        $window = '';
    
            function IsInjected($str) {
              $injections = array('(\n+)',
                          '(\r+)',
                          '(\t+)',
                          '(%0A+)',
                          '(%0D+)',
                          '(%08+)',
                          '(%09+)'
                          );
              $inject = join('|', $injections);
              $inject = "/$inject/i";
              if(preg_match($inject,$str))
                {
                return true;
              }
              else
                {
                return false;
                }
            }
    
            if (!checkdate($_SESSION['month_from'], $_SESSION['day_from'], $_SESSION['year_from'])) {
                $window = $checkin;
                echo $window;
                $validate = true;
            }
            if (!checkdate($_SESSION['month_to'], $_SESSION['day_to'], $_SESSION['year_to'])) {
                $window = $checkout;
                $validate = true;
                echo $window;
                //echo "Check out date is invalid";
            }
            else if ($_SESSION['booking_from'] > $_SESSION['booking_to']) {
                    $window = $larger;
                    $validate = true;
                    echo $window;
                    // echo "Check in date is after check out date";
            }
            else if ($_SESSION['booking_from'] == $_SESSION['booking_to']) {
                $window = $equal;
                $validate = true;
                echo $window;
            }   
        // check if all info is filled in 
            else if (($_SESSION['first_name'] == "Name") || ($_SESSION['last_name'] == "surname") || ($_SESSION['payer_email'] == "Email") || ($_SESSION['mobile'] == "mobile") || ($_SESSION['address'] == "Address")) {
                $window = $noinfo;
                echo $window;
                $validate = true;
                // echo "Please fill in the missing information";
            }
            else if (IsInjected($payer_email)) {
                echo "Not an email";
            }
            else if ($validdate == false) {
                $final = true;
                $sql = "SELECT COUNT(*)  FROM room_nights WHERE apartmentID= '$apartment' AND dates >= '$booking_from' AND dates <= '$booking_to'";
                $result = mysqli_query($conn, $sql);
                $result = mysqli_query($conn, $sql);
                $row=mysqli_fetch_row($result);
    
                if ($row[0] > 0) {
                    $window = $booked;
                    echo $window;
                }
    
            else if ($final == true)  {
                // save to database 
                //  include 'insertdata.php';
    
                    echo $item_name;
                    // include functions
                    include ("pay_functions.php");
                    // Check if paypal request or response
                    if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){
                    // Firstly Append paypal account to querystring
                        $querystring .= "?business=".urlencode($paypal_email)."&";  
                        // Append amount& currency (£) to quersytring so it cannot be edited in html
                        //The item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable.
                        $querystring .= "item_name=".urlencode($item_name)."&";
                        $querystring .= "amount=".urlencode($item_amount)."&";
                            //loop for posted values and append to querystring
                            foreach($_POST as $key => $value){
                                $value = urlencode(stripslashes($value));
                                $querystring .= "$key=$value&";
                            }
                        // Append paypal return addresses
                        $querystring .= "return=".urlencode(stripslashes($return_url))."&";
                        $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
                        $querystring .= "notify_url=".urlencode($notify_url);
                        // Append querystring with custom field
                        //$querystring .= "&custom=".USERID;
                        // Redirect to paypal IPN
                        header('location:https://www.sandbox.paypal.com/cgi-bin/webscr'.$querystring);
                        exit();
    
                    } 
                else {
                        // Response from paypal
                        $req = 'cmd=_notify-validate';
                        foreach ($_POST as $key => $value) {
                            $value = urlencode(stripslashes($value));
                            $value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}',$value);// IPN fix
                            $req .= "&$key=$value";
                        }
    
                        // assign posted variables to locate variables
                        $data['item_name'] = $_POST['item_name'];
                        $data['item_number'] = $_POST['item_number'];
                        $data['payment_status'] = $_POST['payment_status'];
                        $data['payment_amount'] = $_POST['mc_gross'];
                        $data['payment_currency'] = $_POST['mc_currency'];
                        $data['txn_id'] = $_POST['txn_id'];
                        $data['receiver_email'] = $_POST['receiver_email'];
                        $data['payer_email'] = $_POST['payer_email'];
                        $data['custom'] = $_POST['custom'];
    
                        // post back to paypal system and validate
    
                        $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
                        $header .= "Content-Type : application/x-www-form-urlencoded\r\n";
                        $header .= "Content-Lenght: " .strlen($req) . "\r\n\r\n";
    
                        $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
    
                    if (!$fp) {
                    // HTTP error
                    } else {
                        mail('christabelbusuttil@gmail.com', '0', '0');
                        fputs ($fp, $header . $req);
                        while (!feof($fp)) {
                            $res = fgets($fp, 1024);
                            if (strcmp ($res, "VERIFIED") == 0) {
    
                                 // validate payment (check unique txnid & correct price) 
                                 $valid_txnid = check_txnid($data['txn_id']);
                                 $valid_price = check_price($data['payment_amount'], $data['item_number']);
                                 // Payment validated and verified
                                if ($valid_price && $valid_price) {
                                     $orderid = updatePayments($data);
                                    if ($orderid){
                                         // payment has been made and inserted into db
                                    } else {
                                         echo "Error";
                                    }
                                } 
                                else if (strcmp($res, "INVALID") == 0) {
                                        echo "Payment invalid";
                                }
                            }
                                 fclose($fp);
                        }
                    }
                }    
            } 
        } 
    }
    
    }
    
    ?>
    

    然后,如果payment_status = complete - &gt;使用存储在会话中的数据并保存到数据库。如果不完整,则丢弃。

      $payment_status  = isset($_POST['payment_status']) ?    $_POST['payment_status'] : '';
     if ($payment_status == 'Completed') {
    session_start();
     // Echo Value for testing purposes
    echo "Apartment Value is " . $_SESSION['apartment'] . " - " .$apartment . "<br>";
    echo "Unit Price is " . $_SESSION['unitprice'] ."<br>";
    echo "First Name is " . $_SESSION['first_name'] ."<br>";
    echo "Last Name is " . $_SESSION['last_name'] ."<br>";
    echo "Payer Email is " .$_SESSION['payer_email'] ."<br>";
    echo "Address is " . $_SESSION['address']."<br>";
    echo "Apartment Name is " . $_SESSION['apt_name'] ."<br>";
    echo "Mobile number is " .$_SESSION['mobile'] ."<br>";
    echo "Number of people" .$_SESSION['pax'] ."<br>";
    echo "Remarks " . $_SESSION['remarks'] ."<br>";
    echo "Booking From "  .$_SESSION['booking_from'] ."<br>";
    echo "Booking To " .$_SESSION['booking_to'] ."<br>";
    echo "Number of Nights ". $_SESSION['no_of_nights'] ."<br>";
    echo "Quantity " .$_SESSION['quantity'] ."<br>";
    $reason = "Booked by ".$_SESSION['first_name']." ".$_SESSION['last_name']." for ".$_SESSION['pax'] ." people";
    
        $fullname = $_SESSION['first_name'] ." ".$_SESSION['last_name'];
    
        echo $reason ."<br>";
        echo $fullname ."<br>";
    
    include 'insertdata.php';
    
    echo "Payment Completed";
    session_unset();
    
    // destroy the session
    session_destroy(); 
    }
    else {
    
    }
    

    insertdata.php

     <?php
    
    function daterange($_SESSION['booking_from'], $_SESSION['booking_to'], $step = '+1 day', $output_format = 'Y-m-d') {
      $dates = array();
      $first = new DateTime($_SESSION['booking_from']);
      $last = new DateTime($_SESSION['booking_to']);
      $last = $last->modify('+ 1 day');
      $interval = DateInterval::createFromDateString($step);
      $period = new DatePeriod($first, $interval, $last);
    
    
      foreach ($period as $date) {
          $dates[] = $date->format($output_format);
      } 
    
      return $dates;
    }
    
    $dates = daterange($_SESSION['booking_from'], $_SESSION['booking_to']);
    
    print_r($dates);
    
     include 'connect.php';
    
     if (!$conn->autocommit(FALSE)) {
        printf("Errormessage: %s\n", $conn->error);
     }
    
     if (!$conn->query("INSERT INTO client_details (clientID, name, email, address, mobile) VALUES ('', '$fullname', $_SESSION['payer_email'], $_SESSION['address'], $_SESSION['mobile'])")) {
         printf("Errormessage: %s\n", $conn->error);
     }
    
    
     if (!$conn->query("INSERT INTO bookings (bookingID, apartmentID, clientID, date_from, date_to, nights, pax, remarks) VALUES ('', '$apartment', LAST_INSERT_ID(), '$booking_from', '$booking_to', '$quantity', '$pax', '$remarks')")) {
         printf("Errormessage: %s\n", $conn->error);
     }
    
     foreach ($dates as $date) {
     if (!$conn->query("INSERT INTO room_nights (bookingID, apartmentID, dates, reason) VALUES (LAST_INSERT_ID(), '$apartment', '$date', '$reason')")) {
          printf("Errormessage: %s\n", $conn->error);
     } 
     }
    
     if (!$conn->commit()) {
         printf("Errormessage: %s\n", $conn->error);
     }
     $conn->close();
    
     ?>
    
      

    错误:致命错误:无法在第3行的C:\ xampp \ htdocs \ WebDevelopment \ V18 \ insertdata.php中重新分配自动全局变量_SESSION

1 个答案:

答案 0 :(得分:0)

function daterange($_SESSION['booking_from'], $_SESSION['booking_to'], $step = '+1 day', $output_format = 'Y-m-d') {
  $dates = array();
  $first = new DateTime($_SESSION['booking_from']);
  $last = new DateTime($_SESSION['booking_to']);
  $last = $last->modify('+ 1 day');
  $interval = DateInterval::createFromDateString($step);
  $period = new DatePeriod($first, $interval, $last);


  foreach ($period as $date) {
      $dates[] = $date->format($output_format);
  } 

  return $dates;
}

当你编写这个函数时,你试图覆盖$ _SESSION数组,你不能这样做,而不是尝试使用像$booking_from这样的变量名等,然后传入你想要的值在功能中使用。
请参阅另一个问题:Fatal error: Cannot re-assign auto-global variable