[英]How to pass variable from js to php in PayPal checkout Integration?
我正在用HTML和PHP创建购物网站。 这是我第一次进行Web开发。
我正在尝试将PayPal Checkout添加到我的网站。 我从Paypal开发人员那里获得了代码,并且可以成功付款。 如果付款成功,我需要使用php将订单数据插入数据库。
如何传递我定义的javascript变量来指示对PHP的付款批准?
我已经看到它用ajax完成,但我不知道如何实现它。
这是我的代码。 我添加了jQuery CDN,因为它似乎是必需的,但我不知道是否需要其他任何东西。
<!DOCTYPE html> <head> <!-- Add meta tags for mobile and IE --> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <!-- Set up a container element for the button --> <div id="paypal-button-container"></div> <!-- Include the PayPal JavaScript SDK --> <script src="https://www.paypal.com/sdk/js?client-id=sb¤cy=USD"></script> <script> // Render the PayPal button into #paypal-button-container paypal.Buttons({ style: { layout: 'horizontal', color: 'blue', shape: 'rect' }, // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '17' } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(details) { // Show a success message to the buyer alert('Transaction completed by ' + details.payer.name.given_name + '!'); //Variable to confirm successful payment on php //? //? }); } }).render('#paypal-button-container'); </script> </body>
PHP仅在服务器上可见。 因此,您应该使用fetch(推荐)或XMLHTTPRequest将值发送到服务器。
创建一个PHP文件,您可以在其中接收$_GET
或$_POST
变量并处理其余的付款。 在此示例中,我将文件ajax_file.php
,但您可以根据需要命名。
将fetch
添加到onApprove
方法中。 我们将使用POST
方法进行发送,以便通过body
属性发送数据更加容易。 GET
也可以做到,但工作方式略有不同。
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Show a success message to the buyer
alert('Transaction completed by ' + details.payer.name.given_name + '!');
// URL which to send the value to.
const url = 'http://yoursite.com/ajax_file.php';
// Message to send. In this example an object with a state property.
// You can change the properties to whatever you want.
const message = { status: 'success' };
// Send it to the URL with the POST method
// and send the message in JSON format.
fetch(url, {
method: 'POST',
body: JSON.stringify(message)
}).catch(function(error) {
console.log(error); // Display error if there is one.
});
});
}
在您的PHP文件中,例如ajax_file.php
。
在此检查值。 查看它是否已发送以及它是否是正确的值,然后从那里继续流程。
// Check if status send.
$status = isset( $_POST[ 'status'] ) ? $_POST[ 'status' ] : false;
// Check the value of status
if ( $status === 'succes' ) {
// Status is a success.
// Continue your form flow.
}
您的问题尚不明确下一步该怎么办,但我希望您可以从这里弄清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.