我有一个PHP脚本,它将根据输入的订单ID从Magento API返回订单信息。我在表单中为API用户名和密码添加了两个额外的输入字段,以便它们不会存储在PHP脚本文件中。
这很好用,除了我需要能够让脚本捕获API用户名和/或密码不正确时引起的错误。
这是一个成功的查询:
底线是点击提交时返回的内容。如果查询不成功,脚本将不会返回到初始表单页面,如下所示:
请参阅下面的代码:
表单页
<?php
session_start();
?>
<html>
<head>
<title>Retrieve Order</title>
<link rel="stylesheet" type="text/css" href="/matt/api.css">
</head>
<body>
<form class="get_value" action="get_order.php" method="post">
Enter username and password.
<input type="text" name="api_user">
<input type="password" name="api_pass"><br><br>
Enter an order ID to retrieve the grand total order value.<br><br>
<input type="text" name="order_id">
<input type="submit" class="form_submit">
</form>
</body>
</html>
<?php
if (isset($_SESSION['query_result'])) {
echo $_SESSION['query_result'];
unset($_SESSION['query_result']);
}
?>
PHP脚本
<link rel="stylesheet" type="text/css" href="/matt/api.css">
<?php
$order_id = $_POST['order_id'];
$user = $_POST['api_user'];
$pass = $_POST['api_pass'];
$client = new SoapClient('https://ts564737-container.zoeysite.com/api/v2_soap/?wsdl');
$session = $client->login($user, $pass);
$filter = array('filter' => array(array('key' => 'order_id', 'value' => $order_id)));
$result = $client->salesOrderList($session, $filter);
session_start();
if ($result) {
foreach ($result as $returned_order) {
$_SESSION['query_result'] = 'The grand total of order ID <b>' . $order_id . '</b> is <span style="color: #ff0000; font-weight: bold;">£' . round($returned_order->grand_total, 2) . '</span>';
}
} else {
$_SESSION['query_result'] = 'Order ID <b>' . $order_id . '</b> does not exist in the database.';
}
header('Location: xxx/enter_order_id.php');
?>
我怎样才能抓住&#34;错误,以便它作为query_result
会话变量的一部分返回?非常感谢您的见解。
答案 0 :(得分:0)
将变量和语句包装在try-catch异常处理程序中。工作代码:
<?php
session_start();
try {
$order_id = $_POST['order_id'];
$user = $_POST['api_user'];
$pass = $_POST['api_pass'];
$client = new SoapClient('https://ts564737-container.zoeysite.com/api/v2_soap/?wsdl');
$session = $client->login($user, $pass);
$filter = array('filter' => array(array('key' => 'order_id', 'value' => $order_id)));
$result = $client->salesOrderList($session, $filter);
if ($result) {
foreach ($result as $returned_order) {
$_SESSION['query_result'] = '<span class="success_box">The grand total of order ID <b>' . $order_id . '</b> is <b>£' . round($returned_order->grand_total, 2) . '</b></span>';
}
} else {
$_SESSION['query_result'] = '<span class="error_box"><b>Error:</b> Order ID <b>' . $order_id . '</b> does not exist in the database.</span>';
}
} catch(exception $e) {
$_SESSION['query_result'] = '<span class="error_box"><b>Error:</b> ' . $e->getMessage() . '</span>';
}
header('Location: xxx');
?>