简体   繁体   中英

How to make payment unavailable when product out of stock with paypal smart button

I am using a PayPal smart button to carry out payments for my website. What can I do in order to make payments unavailable when an item is out of stock? It might be helpful to know that the items are singular items so the stock number will always be 1. Here is my current code:

    <?php
include 'pdo_connect.php';

$product_id = $_GET['product'];

$stmt = $db->prepare("SELECT * FROM products Where id = :id");
$stmt->bindParam(':id', $product_id );
$stmt->execute();

    while($row = $stmt->fetch()){
        $stock = $row['stock'];

        if ($stock > 0){
        echo 
        "<script>
        paypal.Buttons({

            style: {
                shape: 'rect',
                color: 'blue',
                layout: 'vertical',
                label: 'paypal',
                locale: 'en_CY'
            },
        
            createOrder: function(data, actions) {
                return actions.order.create({
                    purchase_units: [{
                        amount: {
                            value: ". $row['paypal_price'] .",
                            currency: 'EUR'
                        }
                    }]
                });
            },
            onApprove: function(data, actions) {
                return actions.order.capture().then(function(details) {
                    localStorage.clear();
                    window.location.href = 'http://localhost/website/thankyou.php';
                    //alert('Transaction completed by ' + details.payer.name.given_name + '!');
                });
            }
        }).render('#paypal-button-container');
      </script>";
    }
   }
 ?>

Any insight would be highly appreciated.

You already have an if statement for displaying the buttons, so you can add an else statement to display the out of stock message.

A problem with your implementation is that the button could render simultaneously for two different people, and both could initiate the purchase and hence you would get two payments for the same single item, and need to issue a refund. If this concerns you, you should communicate with your server from the createOrder function, using eg the fetch API. There is an example in this surprisingly similar question: https://stackoverflow.com/a/62961660/2069605

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM