【问题标题】:Get JSON response after a Stripe charge is made收取 Stripe 费用后获取 JSON 响应
【发布时间】:2019-05-08 18:52:11
【问题描述】:

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

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

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

这里是JSPHPfiles 的相关部分。

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

?>

【问题讨论】:

  • 收费是一个两步过程,当用户在条形表单中填写他的详细信息并点击输入时,第一个完成(charge.php)为第二部分。如果这也成功了,你会得到一个带有status='succeeded'的json响应,所以你只需要检查它是否可用并且等于succeeded。另外我在返回的代码中看不到json in charge.php 请贴出完整代码。
  • 感谢您让事情变得更清晰。你写的最后一部分对我来说是一个哈哈时刻。我认为它是自动发生的,请您指出正确的方向,例如解析/转换为 json 的内容以及如何将其输出回来?
  • 抱歉,回复晚了,then(response =&gt; console.log(response)) } 这部分是将响应转储到浏览器控制台的内容。如果您熟悉 js,可以访问单个键,例如 respose.status,所以只需要一个 if检查状态 ==200(或 ok== true)的语句并通过 alert() 或一些自定义
    . 显示您的消息
  • 在您了解 JSON 响应的实际工作原理之后,我设法解决了这个问题。再次感谢,你让我走上了正确的道路:)

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


【解决方案1】:

在@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)
       }
        });

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签