1.Controller层
<?php
namespace app\api\controller\user;
use app\api\controller\Controller;
use app\api\model\Order as OrderModel;
class Order extends Controller
{
public function express($order_id)
{
$order = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
if (!$order['express_no']) {
return $this->renderError('没有物流信息');
}
$model = $order['express'];
$express = $model->dynamic($model['express_name'], $model['express_code'], $order['express_no']);
if ($express === false) {
return $this->renderError($model->getError());
}
return $this->renderSuccess(compact('express'));
}
2.Model层
<?php
namespace app\common\model;
use think\Request;
use app\common\library\express\Kuaidi100;
class Express extends BaseModel
{
protected $name = 'express';
public function dynamic($express_name, $express_code, $express_no)
{
$data = [
'express_name' => $express_name,
'express_no' => $express_no
];
$config = Setting::getItem('store');
$Kuaidi100 = new Kuaidi100($config['kuaidi100']);
$data['list'] = $Kuaidi100->query($express_code, $express_no);
if ($data['list'] === false) {
$this->error = $Kuaidi100->getError();
return false;
}
return $data;
}
}
3.Server层
<?php
namespace app\common\library\express;
use think\Cache;
class Kuaidi100
{
private $config;
private $error;
public function __construct($config)
{
$this->config = $config;
}
public function query($express_code, $express_no)
{
$cacheIndex = 'express_' . $express_code . '_' . $express_no;
if ($data = Cache::get($cacheIndex)) {
return $data;
}
$postData = [
'customer' => $this->config['customer'],
'param' => json_encode([
'resultv2' => '1',
'com' => $express_code,
'num' => $express_no
])
];
$postData['sign'] = strtoupper(md5($postData['param'] . $this->config['key'] . $postData['customer']));
$url = 'http://poll.kuaidi100.com/poll/query.do';
$result = curlPost($url, http_build_query($postData));
$express = json_decode($result, true);
if (isset($express['returnCode']) || !isset($express['data'])) {
$this->error = isset($express['message']) ? $express['message'] : '查询失败';
return false;
}
Cache::set($cacheIndex, $express['data'], 300);
return $express['data'];
}
public function getError()
{
return $this->error;
}
}