将API调用的返回值保存到现有数据库

时间:2016-08-20 11:11:23

标签: php sql parsing curl response

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

首先,我保存本地数据库中的所有详细信息,以及从上一个表单传递的代理和时间戳的名称。 保存数据后,我会使用他们的API将所有相关数据发送到服务提供。我使用curl发布数据。

如果一切顺利,我会收到以下回复

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

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

而不是这条冗长的啰嗦讯息。
  

数据已成功提交。此次促销的交易ID为:   SS_100526

"在同一页面而不是一个新的空白窗口。 此外,我想将返回的交易ID保存在同一本地表中,我在调用API之前保存销售详细信息。

我尝试使用各种JSON选项,并将其用作解析字符串,但似乎无法使其工作。 知道如何正确显示返回响应并将返回的事务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);

?>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

首先,我建议您使用框架而不是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注入并不安全。恶意用户可能会破坏您的webapp的安全性。使用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[]的数组。移除(string)之前的curl_exec

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