0

<?php

// For test payments we want to enable the sandbox mode. If you want to put live
// payments through then this setting needs changing to `false`.
$enableSandbox = true;

// Database settings. Change these for your database configuration.
$dbConfig = [
    'host' => 'localhost',
    'username' => 'root',
    'password' => '',
    'name' => 'bluegroup'
];

// PayPal settings. Change these to your account details and the relevant URLs
// for your site.
$paypalConfig = [
    'email' => 'thebluegroup@thebluegroup.nz',
    'return_url' => 'http://localhost/ProjectBlue/payment-successful.html',
    'cancel_url' => 'http://localhost/ProjectBlue/payment-cancelled.html',
    'notify_url' => 'http://localhost/ProjectBlue/payments.php'
];

$paypalUrl = $enableSandbox ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr';

// Product being purchased.
global $db;

$ip_add = getRealIpUser();
$total = 0;
$select_cart = "select * from cart where ip_add='$ip_add'";
$run_cart = mysqli_query($db,$select_cart);
while($record = mysqli_fetch_array($run_cart)){
    $pro_id = $record['p_id'];
    $pro_qty = $record['qty'];
    $sub_total = (int)$record['p_price']*(int)$pro_qty;
    $total+=$sub_total;
}
$itemName = "name"; 
$itemAmount = (float)$total;

// Include Functions
require 'functions.php';

// Check if paypal request or response
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])) {

    // Grab the post data so that we can set up the query string for PayPal.
    // Ideally we'd use a whitelist here to check nothing is being injected into
    // our post data.
    $data = [];
    foreach ($_POST as $key => $value) {
        $data[$key] = stripslashes($value);
    }

    // Set the PayPal account.
    $data['business'] = $paypalConfig['email'];

    // Set the PayPal return addresses.
    $data['return'] = stripslashes($paypalConfig['return_url']);
    $data['cancel_return'] = stripslashes($paypalConfig['cancel_url']);
    $data['notify_url'] = stripslashes($paypalConfig['notify_url']);

    // Set the details about the product being purchased, including the amount
    // and currency so that these aren't overridden by the form data.
    $data['item_name'] = $itemName;
    $data['amount'] = $itemAmount;
    $data['currency_code'] = 'NZD';

    // Add any custom fields for the query string.
    //$data['custom'] = USERID;

    // Build the query string from the data.
    $queryString = http_build_query($data);

    // Redirect to paypal IPN
    header('location:' . $paypalUrl . '?' . $queryString);
    exit();

} else {
    // Handle the PayPal response.

    // Create a connection to the database.
    $db = new mysqli($dbConfig['host'], $dbConfig['username'], $dbConfig['password'], $dbConfig['name']);

    // Assign posted variables to local data array.
    $data = [
        'item_name' => $_POST['item_name'],
        'item_number' => $_POST['item_number'],
        'payment_status' => $_POST['payment_status'],
        'payment_amount' => $_POST['mc_gross'],
        'payment_currency' => $_POST['mc_currency'],
        'txn_id' => $_POST['txn_id'],
        'receiver_email' => $_POST['receiver_email'],
        'payer_email' => $_POST['payer_email'],
        'custom' => $_POST['custom'],
    ];

    // We need to verify the transaction comes from PayPal and check we've not
    // already processed the transaction before adding the payment to our
    // database.
    if (verifyTransaction($_POST) && checkTxnid($data['txn_id'])) {
        if (addPayment($data) !== false) {
            // Payment successfully added.
        }
    }
}

My problem is that I am trying to fetch the cart total into Paypal when checked out with Paypal, however, it is still showing me the default 0.01 NZD and not my cart amount. The tutorial I am following is https://github.com/EvolutedNewMedia/paypal-example/blob/master/payment-successful.html[1] Please let me know where is my mistakeenter image description here

<?php 
include("includes/header.php");
?>
<div id="content"><!-- #content Begin -->
    <div class="container"><!-- container Begin -->
        <div class="col-md-12"><!-- col-md-12 Begin -->
                
                <ul class="breadcrumb"><!-- breadcrumb Begin -->
                    <li>
                        <a href="index.php">Home</a>
                    </li>
                    <li>
                        Cart
                    </li>
                </ul><!-- breadcrumb Finish -->
                
            </div><!-- col-md-12 Finish -->
            <div id="cart" class="col-md-9"><!-- col-md-9 Begin -->
               
               <div class="box"><!-- box Begin -->
                    <form action="cart.php" method="post" enctype="multipart/form-data"><!-- form Begin -->
                        <h3>Shopping Cart</h3>
                        
                        <?php 
                        
                            $ip_add = getRealIpUser();
                            $select_cart = "select * from cart where ip_add='$ip_add'";
                            $run_cart = mysqli_query($con,$select_cart);
                            $count = mysqli_num_rows($run_cart);
                        
                        ?>
                        <p class="text-muted">You currently have <?php echo $count; ?> item(s) in your cart</p>
                        <div class="table-responsive"><!-- table-responsive Begin -->
                           
                           <table class="table"><!-- table Begin -->
                               <thead><!-- thead Begin -->
                                   <tr><!-- tr Begin -->
                                   
                                        <th colspan="2" >Product</th>
                                            <th>Quantity</th>
                                            <th>Price</th>
                                            <th>Remove</th>
                                            <th colspan="2">Subtotal</th>
                                   </tr><!-- tr Finish -->
                                </thead><!-- thead Finish -->
                               
                                    <tbody><!-- tbody Begin -->
                                        <?php 
                                        
                                        $total = 0;
                                   
                                        while($row_cart = mysqli_fetch_array($run_cart)){
                                            
                                          $pro_id = $row_cart['p_id'];
                                          
                                          $pro_qty = $row_cart['qty'];
                                            
                                            $get_products = "select * from products where product_id='$pro_id'";
                                            
                                            $run_products = mysqli_query($con,$get_products);
                                            
                                            while($row_products = mysqli_fetch_array($run_products)){
                                                
                                                $product_title = $row_products['product_title'];
                                                
                                                $product_img = $row_products['product_img'];
                                                
                                                $only_price = $row_products['product_price'];
                                                
                                                $sub_total = $row_products['product_price']*$pro_qty;
                                                
                                                $total += $sub_total;

                                            // $cartTotal = document.getElementById( $sub_total).value;
                                                 
                                        ?>
                                        <tr><!-- tr Begin -->
                                       
                                        <td>
                                        <div class="cart-info">
                                        <img class="img-responsive" src="admin_area/product_images/<?php echo $product_img; ?>">
                                        <td>
                                            <a href="details.php?pro_id=<?php echo $pro_id; ?>"> <?php echo $product_title; ?> </a>
                                            </td>
                                        </div>
                                        </td>
                                        <td><?php echo $pro_qty; ?></td>
                                        <td>$<?php echo $only_price; ?></td>
                                        <td> <input type="checkbox" name="remove[]" value="<?php echo $pro_id; ?>"></td>
                                        <td> $<?php echo $sub_total; ?></td>
                                       
                                   </tr><!-- tr Finish -->
                                   
                                   <?php } } ?>
                                    </tbody><!-- tbody Finish -->
                                    <tfoot><!-- tfoot Begin -->
                                   
                                        <tr><!-- tr Begin -->
                                            
                                            <th colspan="4">Total Price</th>
                                            <th colspan="2">$<?php echo $total; ?></th>
                                            
                                        </tr><!-- tr Finish -->
                                   
                                    </tfoot><!-- tfoot Finish -->
                               
                           </table><!-- table Finish -->
                           
                       </div><!-- table-responsive Finish -->
                    
                           
                       <div class="box-footer"><!-- box-footer Begin -->
                           
                           <div class="pull-left"><!-- pull-left Begin -->
                               
                               <a href="index.php" class="btn btn-default"><!-- btn btn-default Begin -->
                                   
                                   <i class="fa fa-chevron-left"></i> Continue Shopping
                                   
                               </a><!-- btn btn-default Finish -->
                               
                           </div><!-- pull-left Finish -->
                           
                           <div class="pull-right"><!-- pull-right Begin -->
                               
                               <button type="submit" name="update" value="Update Cart" class="btn btn-default"><!-- btn btn-default Begin -->
                                   
                                   <i class="fa fa-refresh"></i> Update Cart
                                   
                               </button><!-- btn btn-default Finish -->
                               
                               <a href="checkout.php"  id="paypal-button">
                                   
                               <script src="https://www.paypal.com/sdk/js?client-id=AU8TitNyYv12ygRa1Ek6c4zr0AywbO1OJ1XhMGrtgsTIbLj63BqAAYF1PwfPw0aW61NZ5TU6BmEjobpH&currency=NZD"></script>
                               <script>paypal.Buttons().render('#paypal-button');</script>
                                   
                               </a>
                              
                           </div><!-- pull-right Finish -->
                           
                       </div><!-- box-footer Finish -->
                     </form><!-- form finish -->
                </div><!-- box finish -->
                <?php 
               
                function update_cart(){
                    
                    global $con;
                    
                    if(isset($_POST['update'])){
                        
                        foreach($_POST['remove'] as $remove_id){
                            
                            $delete_product = "delete from cart where p_id='$remove_id'";
                            
                            $run_delete = mysqli_query($con,$delete_product);
                            
                            if($run_delete){
                                
                                echo "<script>window.open('cart.php','_self')</script>";
                                
                            }
                            
                        }
                        
                    }
                    
                }
               
               echo @$up_cart = update_cart();
               
               ?>
            
            </div><!-- col-md-9 finish -->
            <div class="col-md-3" style="background:#f7f7f7; border-radius: 20px ; margin-top:80px"><!-- col-md-3 Begin -->
               
               <div id="order-summary" class="box"><!-- box Begin -->
                   
                 
                       
                       <h4 style="padding:20px">Order Summary</h4>
                       
                   
                   
                   <p class="text-muted"><!-- text-muted Begin -->
                       
                       Shipping and additional costs are calculated based on value you have entered
                       
                   </p><!-- text-muted Finish -->
                   
                   <div class="table-responsive"><!-- table-responsive Begin -->
                       
                       <table class="table"><!-- table Begin -->
                           
                           <tbody><!-- tbody Begin -->
                               
                               <tr><!-- tr Begin -->
                                   
                                   <td> Order All Sub-Total </td>
                                   <td> $<?php echo $total; ?> </td>
                                   
                               </tr><!-- tr Finish -->
                               
                               <tr><!-- tr Begin -->
                                   
                                   <td> Shipping and Handling </td>
                                   <td> $0 </td>
                                   
                               </tr><!-- tr Finish -->
                               
                               <tr><!-- tr Begin -->
                                   
                                   <td> Tax </td>
                                   <td> $0 </td>
                                   
                               </tr><!-- tr Finish -->
                               
                               <tr class="total"><!-- tr Begin -->
                                   
                                   <td> Total </td>
                                   <td> $<?php echo $total; ?> </td>
                                   
                               </tr><!-- tr Finish -->
                               
                           </tbody><!-- tbody Finish -->
                           
                       </table><!-- table Finish -->
                       
                   </div><!-- table-responsive Finish -->
                   
               </div><!-- box Finish -->
               
           </div><!-- col-md-3 Finish -->
        </div><!-- container Finish -->
</div><!-- content Finish -->
Himani Gajjar
  • 43
  • 1
  • 6
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Nov 18 '21 at 08:50
  • Thank you for your comment, I am newbie and so far, I have only heard about SQL injections. I will work on it and implement it in my project. Thank you – Himani Gajjar Nov 19 '21 at 05:46
  • 1
    If you are only starting to learn PHP then you should learn PDO instead of mysqli. PDO is much easier and more suitable for beginners. Start here https://phpdelusions.net/pdo & https://websitebeaver.com/php-pdo-prepared-statements-to-prevent-sql-injection – Dharman Nov 19 '21 at 09:29

1 Answers1

0

<script>paypal.Buttons().render('#paypal-button');</script>

This code provides no information about the transaction, therefore the amount will be $0.01

Follow the Set up standard payments guide to actually specify information for the transaction.

Separately, the example appears to be using IPN or PDT to "verify information" about the transaction, so it is a very dated and bad example and you should disregard everything about it.

Instead, for a proper server integration, read the 'Add and modify the code' section in the link above, which explains how to create and capture an order from the server.


To just summarize the integration steps: Make two routes on your server, one for 'Create Order' and one for 'Capture Order', documented here. These routes should return only JSON data (no HTML or text). When a capture response is successful, store its resulting payment details in your database (particularly purchase_units[0].payments.captures[0].id, the PayPal transaction ID) and perform any necessary business logic (such as sending confirmation emails or reserving product) before sending your return JSON.

Pair those two routes with the following approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server

Preston PHX
  • 27,642
  • 4
  • 24
  • 44
  • Thank you for the response, however I am an absolute beginner and have been referring to these codes since 2 weeks, I have no idea what to do with them. And the links you gave, I don't know how to link them to my database and project. Could you please guide me on that. Thanks in advance – Himani Gajjar Nov 18 '21 at 08:16
  • The information above is everything you need as far as information on how to implement a PayPal Checkout, so if you aren't able to do it I recommend studying more about programming and your specific environment (PHP) and how to use a database. There are many resources on the internet to get started and develop your knowledge. – Preston PHX Nov 18 '21 at 10:50