Stripe 收费后获得 JSON 响应

Get JSON response after a Stripe charge is made

我正在使用 Stripe 元素构建一个简单的结帐。成功收费后,我想从 Stripe 检索 JSON 响应。根据我的理解,每次收费后都应该创建一个收费对象。

简单示例 - 收费后,如何在结帐表单本身上显示感谢消息?我的理由是,在拉动 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, …}

在控制台中展开它也没有帮助我。我是一个设计师,懂点代码,但离这个水平还差得很远

这里是 JSPHP 文件的相关部分。

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();
}

?>

在@viney 的有用评论后设法解决了它。出于某种原因,我认为 JSON 响应会自动发生,我不需要采取任何行动。

这是我添加到 charge.php 的代码,现在它回显 JSON 响应。

// Response
$success = true;
$err = '';
$recipient_name = $_POST['recipient_name'];
$recipient_email = $_POST['recipient_email'];

try
{
  $charge = \Stripe\Charge::create(array(
    'source'  => $token,
    'amount'  => $amount,
    'currency' => $currency,
    'description' => $item_name,
    'metadata' => array(
      'order_id' => $order_id
  )
  ));
}
catch(\Stripe\Error\Card $e) {
  $success = false;
  $err = "Declined - $e";
}

echo json_encode(array('success' => $success, 'err' => $err, 'recipient_name' => $recipient_name, 'recipient_email' => $recipient_email));

对于 charge.js 我解析了对 JSON 的响应,因为响应是一个 ReadableStream 对象。

       fetch(backendUrl, {
          method: "POST",
          mode: "same-origin",
          credentials: "same-origin",
          body: formData
        })
        .then(function(response) {
          return response.json();
        })
        .then(function(jsonData) {
         let data = jsonData;
         if(data.success == true){
          form.querySelector('.title').textContent = `
          Thank you ${data.recipient_name}, your payment was successful and we have 
         sent an email receipt to ${data.recipient_email}. `
         }
         else{
        errorElement.textContent = `There was an error with payment, please try again 
        or contact us at help@web.com`
       console.log(data.err)
       }
        });