javascript retreive从php获取响应

时间:2019-02-21 17:31:41

标签: javascript php

我正在尝试实施Paypal Express结帐。 所以我实现了按钮并将结果写入我的数据库。没有什么例外,他们给的脚本。

<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 "<script>window.location = 'confirmation web page'</script>";

,但两种解决方案均无效。没有重定向发生

谢谢。

3 个答案:

答案 0 :(得分:0)

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

因此,return fetch('recordDatabase.php', {正在从此文件echo 'ok';echo 'error';返回响应,由于提取是异步的,因此它将返回一个Promise。

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

现在修改您的提取功能,

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

我刚刚解决了您的情况,请尝试以下代码,看看其工作原理 贝宝脚本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"}';
    }

    ?>