一旦商品缺货,如何使用 PayPal 智能按钮显示售完消息

我目前正在为我的网站开发商店。我使用 PayPal Smart 按钮进行付款。我想知道如何添加库存数量,以便当库存数量为 0 时,无法购买。我在互联网上到处搜索,但找不到我的问题的任何答案。这是我当前的代码:


    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 + '!');

            $stock = 0;

        });

    }

}).render('#paypal-button-container');

先感谢您!


隔江千里
浏览 125回答 2
2回答

紫衣仙女

您的问题更多是关于“如何更新当前库存”和“如何获取当前库存”Javascript 在客户端运行,由于您在客户端没有当前的库存编号,因此您需要使 Javascript 与您的服务器进行通信。一种方法是通过 ajax。您可以使用fetch-api来完成此操作。这是你必须做的:在显示按钮之前(php 代码):<?php&nbsp; &nbsp; // your code ...&nbsp; &nbsp; // check stock before you echo. Only echo when $stock is > 0&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; $stock = /* get current stock-amount */;&nbsp; &nbsp; if ($stock > 0) {&nbsp; &nbsp; &nbsp; &nbsp; echo "paypal.Buttons([...";&nbsp; &nbsp; }确认付款后更新您的库存:// your current codelocalStorage.clear();window.location.href = 'http://localhost/website/thankyou.php';// alert('Transaction completed by ' + details.payer.name.given_name + '!');// $stock = 0;// add something like thisconst formData = new FormData();formData.append('amountOrdered', /* number as string */);// maybe use await to block further processing until stock has been updatedfetch('update_stock.php', {&nbsp; &nbsp; &nbsp;method: 'POST',&nbsp; &nbsp; &nbsp;body: formData});在你的新update_stock.php:<?php&nbsp; &nbsp; // update your stock-source by reducing it by $_POST['amountOrdered']您需要的最后一步是在创建订单 (JS) 之前检查您的库存:// async here needed so you can use awaitcreateOrder: async function(data, actions) {&nbsp; &nbsp; // check stock here&nbsp; &nbsp; let stock = (await fetch('get_current_stock.php')).json();&nbsp; &nbsp; let currentStock = stock['current'];&nbsp; &nbsp; // you may want to check for amoutTryingToOrder instead of 1&nbsp; &nbsp; if (currentStock < 1) {&nbsp; &nbsp; &nbsp; &nbsp; alert('Out of stock, sorry :(');&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; return actions.order.create({在你的get_current_stock.php:<?php&nbsp; &nbsp; header('Content-Type: application/json');&nbsp; &nbsp; $currentStock = /* get current stock */;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; echo json_encode([&nbsp; &nbsp; &nbsp; &nbsp; 'current' => $currentStock&nbsp; &nbsp; ]);

catspeake

当没有库存时,您的 createOrder 函数可能会返回 false,而不是继续执行 actions.order.create
打开App,查看更多内容
随时随地看视频慕课网APP