将 API 调用中的 return 值保存到现有数据库

Saving the return value from an API call to an existing Database

我有一个表格,我们在输入详细信息后提交。 提交后,它会将数据发送到 PHP 文件,该文件包含对我的服务提供商的 API 调用。

首先,我将所有详细信息以及代理名称和时间戳记保存在本地数据库中,这些信息是从之前的表单中传递过来的。 保存数据后,我使用 API 将所有相关数据发送到服务提供商。我使用 curl 来 post 数据。

如果一切顺利,我会收到以下响应

HTTP/1.1 100 Continue HTTP/1.1 200 OK Server: nginx/1.8.0 Date: Fri, 19 Aug 2016 16:38:16 GMT Content-Type: application/json Transfer-Encoding: chunked Connection: keep-alive Access-Control-Allow-Headers: Authorization, Content-Type Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET, POST {"success":true,"message":"1 row successfully inserted","warnings":[],"data":{"TRANSACTIONID":"SS_100526","STATUS":"Accepted, Verifying Funds"}}

现在,我只想显示一行 - "

,而不是这个冗长的消息

Data submitted successfully. Transaction ID for this sale is: SS_100526

" 在同一页上,而不是新的空白 window。 此外,我想在调用 API.

之前将 returned 交易 ID 保存在我保存销售详细信息的同一本地 table 中

我曾尝试使用各种 JSON 选项,并将其用作要解析的字符串,但似乎无法正常工作。 知道如何正确显示 return 响应并在现有数据库中保存 returned 事务 ID 吗?

这是我目前使用的带有注释的PHP代码

<?php
 ob_start();
 session_start();
 require_once '../dbconnect.php';// to connect to the database on my server 
 
 if( !isset($_SESSION['user']) ) {
  header("Location: ../index.php"); //fetching session details 
  exit;
 }
 // select loggedin users detail
 $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
 $userRow=mysql_fetch_array($res);
 $userid=$userRow['userEmail'];
 $usernam=$userRow['userName'];
 $timestamp = date('Y-m-d G:i:s');

$apikey = 'xxxxxxxxxxxxxxx'; // Your API Key
$apiEndPoint = 'https://portalDev.example.com';  // URL for API
 
$link = mysqli_connect("localhost", "root", "", "demodata");
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

//collecting the user details to save in the database
 $source = 'client1';
    $last_name= mysqli_real_escape_string($link, $_POST['last_name']);//'Doe',
    $first_name= mysqli_real_escape_string($link, $_POST['first_name']);//'John',
    $address= mysqli_real_escape_string($link, $_POST['address']);//'123 Broadway',
    $city= mysqli_real_escape_string($link, $_POST['city']);//'New York',
    $state= mysqli_real_escape_string($link, $_POST['state']);//'NY',
    $zip= mysqli_real_escape_string($link, $_POST['zip']);//'10016',
    $amount= mysqli_real_escape_string($link, $_POST['amount']);//'5.99',
    $testmode = 0; // In test mode, you must use 1.
 $agentName = $usernam;
 $userMail = $userid;
 $saletimestamp = $timestamp;
 
 
 
// attempt insert query execution
$sql = "INSERT INTO users (source, last_name, first_name, address, city, state, zip, amount, testmode, agentName, userMail, saletimestamp) VALUES ('$source', '$last_name', '$first_name', '$address', '$city', '$state', '$zip','$amount', '$testmode', '$agentName','$userMail','$saletimestamp')";
if(mysqli_query($link, $sql)){
  echo "Records added successfully.";
 //header('Location: http://localhost/login/bsdev/success.html');
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
 
// close connection
mysqli_close($link);
 
 //collate data for sending to the service provider in the format they have shared with us.
$postFields = array(
    'SOURCE'=> 'client1',
    'LASTNAME'=> urlencode($_POST['last_name']),//'Doe',
    'FIRSTNAME'=> urlencode($_POST['first_name']),//'John',
    'ADDRESS'=> urlencode($_POST['address']),//'123 Broadway',
    'CITY'=> urlencode($_POST['city']),//'New York',
    'STATE'=> urlencode($_POST['state']),//'NY',
    'ZIPCODE'=> urlencode($_POST['zip']),//'10016',
    'AMOUNT'=> urlencode($_POST['amount']),//'5.99',
    'TESTMODE' => 1 // In test mode, you must use 1.
);
 
 
$process = curl_init($apiEndPoint . "/api/v1/transaction");
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $apikey . ":" . $apikey); // Basic Authentication using your API key
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, FALSE);
 
 
 
$response = (string)curl_exec($process);

echo $response;

//This is the response we get after curl_exec:
//Records added successfully.HTTP/1.1 100 Continue HTTP/1.1 200 OK Server: nginx/1.8.0 Date: Fri, 19 Aug 2016 13:58:57 GMT Content-Type: application/json Transfer-Encoding: chunked Connection: keep-alive Access-Control-Allow-Headers: Authorization, Content-Type Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET, POST {"success":true,"message":"1 row successfully inserted","warnings":[],"data":{"TRANSACTIONID":"SS_100526","STATUS":"Accepted, Verifying Funds"}}

curl_close($process);

?>

首先,我建议您使用框架而不是 vanilla php,因为这段代码在生产环境中使用并不安全。

$sql = "INSERT INTO users (source, last_name, first_name, address, city, state, zip, amount, testmode, agentName, userMail, saletimestamp) VALUES ('$source', '$last_name', '$first_name', '$address', '$city', '$state', '$zip','$amount', '$testmode', '$agentName','$userMail','$saletimestamp')";

当您编写这样的查询时,SQL 注入是不安全的。恶意用户可以像这样危害您的网络应用程序的安全性。使用 PDO 编写您的查询。

现在回到你的问题。我希望一旦您向 API 发出请求,您就已经知道交易 ID。

当使用 cURL 发出 HTTP 请求时,您可以使用 curl_getinfo() 从响应中获取您想要的信息。

curl_getinfo($process, $options)

$options 是您可以传递的可选数组。使用 curl_setopt_array() 将所有 cURL 设置放在一个数组中。这样你只需要使用一个函数而不是使用 curl_setopt() 七次。

curl_getinfo 的响应中检索状态代码,然后像这样写一个 if 语句。

if($statusCode === 200) {
   echo 'Data submitted successfully. Transaction ID for this sale is: ' . $id;
} else {
   echo 'Something went wrong.';
}

一旦 运行 curl_exec(),您需要关闭 cURL 会话以释放资源。使用 curl_close($process)。确保 $response 是一个像 $response[] 这样的数组。删除 curl_exec.

之前的 (string)

之后,使用 json_decode($response) 将 JSON 字符串转换为 PHP 数组,您可以使用它来检索所需的数据。