簡體   English   中英

如何使用 PayPal 智能按鈕在商品缺貨時顯示售罄消息

[英]How to display sold out message once an itemruns out of stock with PayPal smart button

我目前正在為我的網站開發商店。 我正在使用 PayPal 智能按鈕進行付款。 我想知道如何添加庫存數量,以便當庫存編號為 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');

先感謝您!

您的問題更多是關於“我如何更新我當前的股票”和“我如何獲得我目前的股票”

Javascript 運行客戶端,因為您在客戶端沒有當前庫存編號,您需要讓 Javascript 與您的服務器通信。

一種方法是通過 ajax。 您可以使用fetch-api來完成此操作。

這是你必須做的:

在顯示按鈕(php-code)之前:

<?php
    // your code ...
    // check stock before you echo. Only echo when $stock is > 0
    
    $stock = /* get current stock-amount */;

    if ($stock > 0) {
        echo "paypal.Buttons([...";
    }

在確認付款后更新您的庫存:

// your current code
localStorage.clear();
window.location.href = 'http://localhost/website/thankyou.php';
// alert('Transaction completed by ' + details.payer.name.given_name + '!');
// $stock = 0;

// add something like this
const formData = new FormData();
formData.append('amountOrdered', /* number as string */);

// maybe use await to block further processing until stock has been updated
fetch('update_stock.php', {
     method: 'POST',
     body: formData
});

在您的新update_stock.php

<?php
    // update your stock-source by reducing it by $_POST['amountOrdered']

您需要的最后一步是在創建訂單 (JS) 之前檢查您的庫存:

// async here needed so you can use await
createOrder: async function(data, actions) {
    // check stock here
    let stock = (await fetch('get_current_stock.php')).json();
    let currentStock = stock['current'];

    // you may want to check for amoutTryingToOrder instead of 1
    if (currentStock < 1) {
        alert('Out of stock, sorry :(');
        return false;
    }

    return actions.order.create({

在您的get_current_stock.php中:

<?php
    header('Content-Type: application/json');

    $currentStock = /* get current stock */;
    
    echo json_encode([
        'current' => $currentStock
    ]);

您的 createOrder function 可以在沒有庫存時返回 false,而不是繼續執行 actions.order.create

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM