【问题标题】:javascript retreive fetch response from a phpjavascript 从 php 中检索响应
【发布时间】:2019-11-29 17:15:42
【问题描述】:

我正在尝试实施贝宝快速结帐。 所以我实现了按钮并将结果写入我的数据库。没什么特别的,就是他们给的剧本。

<script>
paypal.Buttons({
    createOrder: function(data, actions) {
      return actions.order.create({
        purchase_units: [{
          amount: {
            value: '0.01'
          }
        }]
      });
    },
    onApprove: function(data, actions) {
      return actions.order.capture().then(function(details) {
        // Call your server to save the transaction
        return fetch('recordDatabase.php', {
          method: 'post',
          mode: "same-origin",
          credentials: "same-origin",
          headers: {"Content-Type": "application/json"},
          body: JSON.stringify({
              orderID: data.orderID, 
              time: details.create_time, 
              status: details.status, 
              nom: details.payer.name.given_name, 
              prenom: details.payer.name.surname, 
              pays: details.payer.address.country_code, 
              valeur:details.purchase_units[0].amount.value
          })
        })
      });
    }
  }).render('#paypal-button-container');
</script>

要记录在数据库中的php:

<?php
$link = connect();

$date = date('Y-m-d H:i:s');
//Receive the RAW post data.
$contentType = isset($_SERVER["CONTENT_TYPE"]) ?trim($_SERVER["CONTENT_TYPE"]) : '';

if ($contentType === "application/json") {
    //Receive the RAW post data.
    $content = trim(file_get_contents("php://input"));
    $decoded = json_decode($content, true);

    //If json_decode failed, the JSON is invalid.
    if(! is_array($decoded)) {
        //echo "error";
    } else {
        $name = $decoded['nom'];
        $time = $decoded['time'];
        $id = $decoded['orderID'];
        $stat = $decoded['status'];
        $pays = $decoded['pays'];
        $val = $decoded['valeur'];

        $secQuery = "INSERT INTO myDatabase(PSEUDO,PASSWORD,CONNECTION,INSCRIPTION,ANNIVERSAIRE,MAIL,IDPAYPAL,STATPAYPAL,NOMPAYER,PAYS,VALEUR) VALUES ('essai','123456',0,'$date','$time','email@mail','$id','$stat','$name','$pays','$val') ";
        if (mysqli_query($link,$secQuery)) {
            //echo "ok";
        } else {
            //echo "error";
        }

    }
} else {
    //echo "error";
}

所以,我数据库中的记录工作正常,但我的问题是:

如何在 javascript 中检索 echo 错误或 ok 以确认用户一切正常,或者是否发生错误。

我尝试了另一种解决方案,将用户从 php 重定向并添加到 php:

header("Location: confirmation web page"); 或
echo "&lt;script&gt;window.location = 'confirmation web page'&lt;/script&gt;";

但两种解决方案都不起作用。没有重定向发生

【问题讨论】:

    标签: javascript php


    【解决方案1】:

    如果我错了,请纠正,recordDatabase.php 是您存储交易的 php 文件。

    所以,return fetch('recordDatabase.php', { 正在从这个文件返回响应,你的 echo 'ok';,echo 'error';,获取是异步的,所以它会返回一个承诺。

    将header('Content-Type: application/json'); 添加到您的 php 文件中,以便它返回一个 json 响应。 还将您的回声更改为echo '{"status":"ok"}'; 和echo '{"status":"error"}';

    现在修改你的 fetch 函数,

    return fetch('recordDatabase.php', {
         //same info here
    })
    .then((response) => response.json())
    .then((responseData) => {
          if(responseData.status == "ok"){
               alert("it worked");
          }else{
               alert("it didn't work");
          }
    })
    

    【讨论】:

    • 感谢response.json() 和responseData.status == "ok" 的想法,现在我正在使用response.text() 和response.includes('&lt;response form text to find&gt;') 作为我的联系表单,即posting 到submit 上的同一页面。
    【解决方案2】:

    return fetch('codes/paypalapi.php', { method: 'post', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ orderID: data.orderID })
    });

    它将完美运行 我也有同样的情况

    【讨论】:

      【解决方案3】:

      我刚刚解决了你的问题,试试这段代码看看它是如何工作的 贝宝脚本 API

      <script>
        paypal.Buttons({
          createOrder: function(data, actions) {
            return actions.order.create({
              purchase_units: [{
                amount: {
                  value: '0.01'
                }
              }]
            });
          },
          onApprove: function(data, actions) {
            return actions.order.capture().then(function(details) {
              alert('Transaction completed by ' + details.payer.name.given_name+' ApplicationId <?php echo $id; ?> :payerID'+data.payerID);
      
              // Call your server to save the transaction
              return fetch('payments.php', {
                method: 'post',
                headers: {
                  'content-type': 'application/json'
                },
                body: JSON.stringify({
                    orderID: data.orderID, 
                    time: details.create_time, 
                    status: details.status, 
                    nom: details.payer.name.given_name, 
                    prenom: details.payer.name.surname, 
                    pays: details.payer.address.country_code, 
                    valeur:details.purchase_units[0].amount.value
                })
              }).then(data => data.ok && data.json()).then(response => {
                  alert(response.status);
              });         
            });
          }
        }).render('#paypal-button-container');
      </script>
      

      PHP 脚本 (payments.php)

       <?php
          header('Content-Type: application/json');
      
      $date = date('Y-m-d H:i:s');
          //Receive the RAW post data.
          $contentType = isset($_SERVER["CONTENT_TYPE"]) ?trim($_SERVER["CONTENT_TYPE"]) : '';
      
          if ($contentType === "application/json") {
              //Receive the RAW post data.
              $content = trim(file_get_contents("php://input"));
              $decoded = json_decode($content, true);
      
              //If json_decode failed, the JSON is invalid.
              if(! is_array($decoded)) {
                  //echo "error";
              } else {
                  $name = $decoded['nom'];
                  $time = $decoded['time'];
                  $id = $decoded['orderID'];
                  $stat = $decoded['status'];
                  $pays = $decoded['pays'];
                  $val = $decoded['valeur'];
      
                echo '{"status":"ok"}';
      
              }
          } else {
              echo '{"status":"error"}';
          }
      
          ?>
      

      【讨论】:

        猜你喜欢
        • 2021-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 2023-03-15
        • 2017-05-09
        • 1970-01-01
        相关资源
        最近更新 更多