Issue
I am currently working on the store for my website. I am using the PayPal Smart button for payments. I was wondering how I can add a stock amount so that when stock number is 0, the ability to purchase becomes unavailable. I've searched everywhere around the internet and could not find any answers for my question. Here is my current code:
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');
Thank you in advance!
Solution
Your question is more about "how do i update my current stock" and "how do i get my current stock"
Javascript runs client-side, since you dont have your current stock-number on client-side, you will need to make Javascript communicate with your server.
One way to do this is via ajax. You can use the fetch-api to accomplish this.
This is what you have to do:
Before you display the button (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([...";
}
Update your stock on confirmed payment:
// 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
});
In your new update_stock.php
:
<?php
// update your stock-source by reducing it by $_POST['amountOrdered']
The last step you will need is to check your stock right before you create an order (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({
In your get_current_stock.php
:
<?php
header('Content-Type: application/json');
$currentStock = /* get current stock */;
echo json_encode([
'current' => $currentStock
]);
Answered By - SirPilan Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.