Я строю простую кассу с элементами Stripe.После успешной зарядки я хотел бы получить ответ JSON
от Stripe.Насколько я понимаю, объект начисления должен создаваться после каждого начисления.
Простой пример - после того, как начисление выполнено, как отобразить сообщение с благодарностью в самой форме оформления заказа?Мое рассуждение состояло в том, что после извлечения JSON
я мог проверить, успешно ли выполнен заряд, и действовать соответствующим образом.
РЕДАКТИРОВАТЬ: я забыл упомянуть, ответ, который я получаю сейчас, - это то, что я не могу расшифровать в консоли.
Response {type: "basic", url: "http://localhost/iq-test/charge.php", redirected: false, status: 200, ok: true, …}
Response {type: "basic", url: "http://localhost/iq-test/charge.php", redirected: false, status: 200, ok: true, …}
Расширение этого в консоли мне тоже не помогло.Я дизайнер, который знает некоторый код, но далеко от этого уровня.
Здесь приведены соответствующие части файлов JS
и PHP
.
charge.js
// Handle form submission.
const form = document.getElementById('payment-form');
const errorElement = document.getElementById('card-errors')
form.addEventListener('submit', function(event) {
event.preventDefault();
// here we lock the form
form.classList.add('processing');
stripe.createToken(card).then(function(result) {
if (result.error) {
// here we unlock the form again if there's an error
form.classList.remove('processing');
// Inform the user if there was an error.
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
}
});
});
// Submit the form with the token ID.
function stripeTokenHandler(token) {
// Let's add name, email and phone to be sent alongside token
const recipient_name = form.querySelector('input[name=recipient-
name]').value;
const recipient_email = form.querySelector('input[name=recipient-
email]').value;
const recipient_phone = form.querySelector('input[name=recipient-
phone]').value;
let formData = new FormData();
formData.append('stripeToken', token.id);
formData.append('recipient_email', recipient_email);
formData.append('recipient_name', recipient_name);
formData.append('recipient_phone', recipient_phone);
// grab the form action url
const backendUrl = form.getAttribute('action');
// Post the info via fetch
fetch(backendUrl, {
method: "POST",
mode: "same-origin",
credentials: "same-origin",
body: formData
})
.then(response => response)
.then(response => console.log(response))
}
charge.php
<?php
require_once "vendor/autoload.php";
\Stripe\Stripe::setApiKey('xxx');
$token = $_POST['stripeToken'];
$amount = 299;
//item meta
$item_name = 'IQ Test Score Results';
$item_price = $amount;
$currency = "usd";
$order_id = uniqid();
try
{
$charge = \Stripe\Charge::create(array(
'source' => $token,
'amount' => $amount,
'currency' => $currency,
'description' => $item_name,
'metadata' => array(
'order_id' => $order_id
)
));
}
catch(Exception $e)
{
$error = $e->getMessage();
show__errorPayment($error);
}
if($charge->status == 'succeeded') {
echo "Charge Created";
$charge_json = $charge->__toJSON();
}
?>