进行Stripe收费后获取JSON响应

时间:2018-12-07 01:52:28

标签: javascript php json stripe-payments fetch-api

我正在使用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();
}

?>

1 个答案:

答案 0 :(得分:0)

设法解决了@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)
       }
        });