作者 耿培杰

接口开发

/nbproject/
/runtime/*
/public/uploads/*
/application/database.php
.idea
composer.lock
*.log
... ...
<?php
namespace addons\kdniao;
use app\common\library\Menu;
use think\Addons;
/**
* 插件
*/
class Kdniao extends Addons
{
/**
* 插件安装方法
* @return bool
*/
public function install()
{
return true;
}
/**
* 插件卸载方法
* @return bool
*/
public function uninstall()
{
return true;
}
/**
* 插件启用方法
* @return bool
*/
public function enable()
{
Menu::enable('kdniao');
return true;
}
/**
* 插件禁用方法
* @return bool
*/
public function disable()
{
Menu::disable('kdniao');
return true;
}
}
... ...
if ($('.kdniao').length > 0) {
$('.kdniao').each(function () {
var code = $(this).data('code');
$(this).addClass('btn btn-xs bg-success').append('<i class="fa fa-truck"></i>' + code);
});
$('.kdniao').click(function () {
var company = $(this).data('company');
var code = $(this).data('code');
if (company && code) {
Layer.open({
type: 2,
area: ['700px', '450px'],
fixed: false, //不固定
maxmin: true,
content: '/addons/kdniao/index/query?company=' + company + '&code=' + code
});
}
});
}
\ No newline at end of file
... ...
<?php
return array (
0 =>
array (
'name' => 'EBusinessID',
'title' => '商户ID',
'type' => 'string',
'content' =>
array (
),
'value' => '1637658',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
),
1 =>
array (
'name' => 'AppKey',
'title' => 'AppKey',
'type' => 'string',
'content' =>
array (
),
'value' => 'd49772b1-339f-4641-ab29-5346ad2e4403',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
),
2 =>
array (
'name' => 'ReqURL',
'title' => 'API请求地址',
'type' => 'string',
'content' =>
array (
),
'value' => 'http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
),
);
... ...
<?php
namespace addons\kdniao\controller;
use addons\kdniao\library\Kdniao;
use think\addons\Controller;
use think\Db;
use think\response\Json;
class Index extends Controller
{
public function index()
{
if ($this->request->isPost()) {
$code = $this->request->post('code');
$company = $this->request->post('company');
$kdniao = new Kdniao();
$wuliu = $kdniao->getOrderTracesByJson($company, $code);
if ($wuliu == -1) {
$json = [
'code' => 0,
'msg' => '未设置接口配置!请在插件管理中配置!',
'data' => '',
];
return Json($json);
}
$wuliu = json_decode($wuliu, true);
$json = [
'code' => 1,
'msg' => '获取成功',
'data' => isset($wuliu['Traces']) && count($wuliu['Traces']) ? array_reverse($wuliu['Traces']) : [['AcceptStation' => '暂无物流信息', 'AcceptTime' => date('Y-m-d H:i:s', time())]]
];
//物流信息倒序
return Json($json);
} else {
$data = Db::name('kdniao')->select();
$this->assign('data', $data);
return $this->view->fetch();
}
}
/**
* 查询
*/
public function query()
{
$code = $this->request->param('code');
$company = $this->request->param('company');
$kdniao = new Kdniao();
$wuliu = $kdniao->getOrderTracesByJson($company, $code);
$wuliu = json_decode($wuliu, true);
/*if (isset($wuliu['Traces']) && count($wuliu['Traces'])) {
$this->assign('data', array_reverse($wuliu['Traces']));
}*/
$this->assign('data', isset($wuliu['Traces']) && count($wuliu['Traces']) ? array_reverse($wuliu['Traces']) : '');
return $this->view->fetch();
}
}
... ...
name = kdniao
title = 快递鸟
intro = 快递鸟API物流即时信息查询插件
author = Coder
website = http://www.kdniao.com
version = 1.0.1
state = 1
url = /addons/kdniao.html
... ...
CREATE TABLE IF NOT EXISTS `__PREFIX__kdniao` (
`company` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
`code` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='快递鸟物流编码表';
BEGIN;
INSERT INTO `__PREFIX__kdniao` (`company`, `code`) VALUES
('顺丰速运', 'SF'),
('百世快递', 'HTKY'),
('中通快递', 'ZTO'),
('申通快递', 'STO'),
('圆通速递', 'YTO'),
('韵达速递', 'YD'),
('邮政快递包裹', 'YZPY'),
('EMS', 'EMS'),
('天天快递', 'HHTT'),
('京东快递', 'JD'),
('优速快递', 'UC'),
('德邦快递', 'DBL'),
('宅急送', 'ZJS'),
('TNT快递', 'TNT'),
('UPS', 'UPS'),
('DHL', 'DHL'),
('FEDEX联邦(国内件)', 'FEDEX'),
('FEDEX联邦(国际件)', 'FEDEX_GJ');
COMMIT;
\ No newline at end of file
... ...
<?php
namespace addons\kdniao\library;
class Kdniao
{
protected $config = [];
public function __construct($options = [])
{
if ($config = get_addon_config('kdniao')) {
$this->config = array_merge($this->config, $config);
}
$this->config = array_merge($this->config, is_array($options) ? $options : []);
}
/**
* Json方式 查询订单物流轨迹
* @param string $shipper
* @param string $code
* @return int|string
*/
public function getOrderTracesByJson($shipper, $code)
{
$eBusinessID = $this->config["EBusinessID"];
$appKey = $this->config["AppKey"];
$reqURL = $this->config["ReqURL"];
if (!$eBusinessID || !$appKey || !$reqURL) {
return -1;
}
$requestData = "{'OrderCode':'','ShipperCode':'$shipper','LogisticCode':'$code'}";
$datas = array(
'EBusinessID' => $eBusinessID,
'RequestType' => '1002',
'RequestData' => urlencode($requestData),
'DataType' => '2',
);
$datas['DataSign'] = $this->encrypt($requestData, $appKey);
$result = $this->sendPost($reqURL, $datas);
//根据公司业务处理返回的信息......
return $result;
}
/**
* Post提交数据
* @param string $url 请求Url
* @param array $datas 提交的数据
* @return string 响应返回的html
*/
protected function sendPost($url, $datas)
{
$temps = array();
foreach ($datas as $key => $value) {
$temps[] = sprintf('%s=%s', $key, $value);
}
$post_data = implode('&', $temps);
$url_info = parse_url($url);
if (empty($url_info['port'])) {
$url_info['port'] = 80;
}
$httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
$httpheader .= "Host:" . $url_info['host'] . "\r\n";
$httpheader .= "Content-Type:application/x-www-form-urlencoded\r\n";
$httpheader .= "Content-Length:" . strlen($post_data) . "\r\n";
$httpheader .= "Connection:close\r\n\r\n";
$httpheader .= $post_data;
$fd = fsockopen($url_info['host'], $url_info['port']);
fwrite($fd, $httpheader);
$gets = "";
$headerFlag = true;
while (!feof($fd)) {
if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
break;
}
}
while (!feof($fd)) {
$gets .= fread($fd, 128);
}
fclose($fd);
return $gets;
}
/**
* 电商Sign签名生成
* @param string 内容
* @param string Appkey
* @return string DataSign签名
*/
protected function encrypt($data, $appkey)
{
return urlencode(base64_encode(md5($data . $appkey)));
}
}
... ...
<!DOCTYPE html>
<html>
<head>
<title>快递鸟物流即时信息查询 - {$site.name}</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap Core CSS -->
<link rel="stylesheet" href="__CDN__/assets/libs/bootstrap/dist/css/bootstrap.min.css">
<style>
.track_list {
padding: 10px;
list-style: none;
}
.track_list li {
font-size: 14px;
border-left: 1px solid #dcdcdc;
padding-bottom: 10px;
padding-left: 15px;
position: relative
}
.track_list li p.time {
font-size: 11px;
padding-bottom: 10px;
border-bottom: 1px solid #e7e7e7
}
.track_list li p:first-child {
padding-bottom: 5px
}
.track_list li.now p {
color: #00bb42
}
.track_list li.old p {
color: #9d9d9d
}
.track_list li.now .ico {
display: block;
position: absolute;
left: -8px;
top: 0;
width: 16px;
height: 16px;
background-color: #b0ffd4;
border-radius: 8px
}
.track_list li.now .ico i {
display: block;
width: 12px;
height: 12px;
background-color: #00aa2c;
border-radius: 6px;
position: absolute;
left: 2px;
top: 2px
}
.track_list li.old .ico {
display: block;
width: 10px;
height: 10px;
background-color: #dcdcdc;
border-radius: 5px;
position: absolute;
left: -5px;
top: 4px
}
.track_list li:last-child {
border-left: 0
}
.track_list li:last-child .time {
border-bottom: 0
}
.track_list li:last-child.old .ico {
left: -4px;
top: 0
}
.logistics_track .nofound {
padding: 30px 10px;
line-height: 20px;
font-size: 12px;
color: #9b9b9b
}
.track_list li p a {
color: #0d90ff
}
</style>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<h2>快递鸟物流即时信息查询</h2>
<hr>
<form action="" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="col-lg-1 control-label">物流公司</label>
<div class="col-lg-11">
<select id="company" name="company" class="form-control">
<option value="">--请选择--</option>
{volist name="data" id="vo"}
<option value="{$vo.code}">{$vo.company}</option>
{/volist}
</select>
</div>
</div>
<div class="form-group">
<label class="col-lg-1 control-label">快递编号</label>
<div class="col-lg-11">
<input type="text" class="form-control" id="code" name="code" placeholder="快递编号">
</div>
</div>
<div class="form-group">
<div class="col-lg-11 col-lg-offset-1">
<button type="button" id="btnsend" name="btnsend" class="btn btn-primary">发送</button>
<button type="reset" class="btn btn-default">重置</button>
</div>
</div>
</fieldset>
</form>
<div class="well">
<div class="row">
<blockquote>物流数据:</blockquote>
<ul class="track_list">
</ul>
</div>
</div>
</div>
<!-- jQuery -->
<script src="__CDN__/assets/libs/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
$("#btnsend").click(function () {
$.ajax({
type: "post",
url: "{:addon_url('kdniao/index/index')}",
data: {company: $("#company").val(), code: $("#code").val(), r: Math.random()},
success: function (data) {
console.log(data);
$('.track_list').html('');
if (data.code) {
$.each(data.data, function (i, n) {
var $li = $('<li class="' + (i == 0 ? 'now' : 'old') + '">' +
'<p>' + n.AcceptStation + '</p>' +
'<p>' + n.AcceptTime + '</p>' +
'<span class="ico"><i></i></span>' +
'</li>');
$('.track_list').append($li);
});
} else {
var $li = $('<li>' +
'<b>' + data.msg + '</b>' +
'</li>');
$('.track_list').append($li);
}
},
error: function () {
alert('查询失败');
},
complete: function () {
}
});
});
</script>
</body>
</html>
... ...
<!DOCTYPE html>
<html>
<head>
<title>快递鸟物流即时信息查询 - {$site.name}</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap Core CSS -->
<link rel="stylesheet" href="__CDN__/assets/libs/bootstrap/dist/css/bootstrap.min.css">
<style>
.track_list {
padding: 10px;
list-style: none;
}
.track_list li {
font-size: 14px;
border-left: 1px solid #dcdcdc;
padding-bottom: 10px;
padding-left: 15px;
position: relative
}
.track_list li p.time {
font-size: 11px;
padding-bottom: 10px;
border-bottom: 1px solid #e7e7e7
}
.track_list li p:first-child {
padding-bottom: 5px
}
.track_list li.now p {
color: #00bb42
}
.track_list li.old p {
color: #9d9d9d
}
.track_list li.now .ico {
display: block;
position: absolute;
left: -8px;
top: 0;
width: 16px;
height: 16px;
background-color: #b0ffd4;
border-radius: 8px
}
.track_list li.now .ico i {
display: block;
width: 12px;
height: 12px;
background-color: #00aa2c;
border-radius: 6px;
position: absolute;
left: 2px;
top: 2px
}
.track_list li.old .ico {
display: block;
width: 10px;
height: 10px;
background-color: #dcdcdc;
border-radius: 5px;
position: absolute;
left: -5px;
top: 4px
}
.track_list li:last-child {
border-left: 0
}
.track_list li:last-child .time {
border-bottom: 0
}
.track_list li:last-child.old .ico {
left: -4px;
top: 0
}
.logistics_track .nofound {
padding: 30px 10px;
line-height: 20px;
font-size: 12px;
color: #9b9b9b
}
.track_list li p a {
color: #0d90ff
}
</style>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="well">
<div class="row">
<blockquote>物流数据:</blockquote>
<ul class="track_list">
{volist name="data" id="item" empty="暂无物流信息"}
<li class='{if condition="$i eq 1"}now{else/}old{/if}'>
<p>{$item.AcceptStation}</p>
<p>{$item.AcceptTime}</p>
<span class="ico"><i></i></span>
</li>
{/volist}
</ul>
</div>
</div>
</div>
<!-- jQuery -->
<script src="__CDN__/assets/libs/jquery/dist/jquery.min.js"></script>
</body>
</html>
... ...
... ... @@ -173,4 +173,32 @@ function setArr($data)
$new_arr[$tmp][$k] = $goodsDepot;
}
return $new_arr;
}
/**
* 快递100查询物流轨迹
* @param $code
* @param $company
* @return mixed
*/
function kuaidi100_query($code,$company){
require_once EXTEND_PATH . 'kuaidi100/query.php';
$sendAPI = new \synQuery($code,$company);
$return = $sendAPI->query();
return $return;
}
function wpjam_array_push($array, $data=null, $key=false){
$data = (array)$data;
$offset = ($key===false)?false:array_search($key, array_keys($array));
$offset = ($offset)?$offset:false;
if($offset){
return array_merge(
array_slice($array, 0, $offset),
$data,
array_slice($array, $offset)
);
}else{ // 没指定 $key 或者找不到,就直接加到末尾
return array_merge($array, $data);
}
}
\ No newline at end of file
... ...
<?php
namespace app\api\controller;
use app\common\controller\Api;
/**
* 首页接口
*/
class Index extends Api
{
protected $noNeedLogin = ['*'];
protected $noNeedRight = ['*'];
/**
* 首页
*
*/
public function index()
{
$this->success('请求成功');
}
}
... ... @@ -2,6 +2,9 @@
namespace app\api\controller;
use app\api\model\OrderDetail;
use app\api\model\OrderInfo;
use app\api\model\Order;
use app\api\model\UserAddress;
use app\api\model\UserMoneyLog;
use app\api\model\UserScoreLog;
... ... @@ -18,6 +21,7 @@ use think\Validate;
class Member extends Api
{
protected $userModel;
public function _initialize()
{
parent::_initialize();
... ... @@ -49,7 +53,7 @@ class Member extends Api
{
$userId = $this->getUserId();
$userInfo = $this->userModel->where('id',$userId)->field('id,nickname,avatar,type,money,score')->find();
$userInfo = $this->userModel->where('id', $userId)->field('id,nickname,avatar,type,money,score')->find();
$this->success('SUCCESS', $userInfo);
}
... ... @@ -92,7 +96,7 @@ class Member extends Api
$where['user_id'] = $userId;
$where['status'] = $status;
$data = $model->selectPageData($where,$page,$limit);
$data = $model->selectPageData($where, $page, $limit);
$this->success('SUCCESS', $data);
}
... ... @@ -123,7 +127,7 @@ class Member extends Api
$where['pid'] = $userId;
$data = $this->userModel->selectPageData($where,$page,$limit);
$data = $this->userModel->selectPageData($where, $page, $limit);
$this->success('SUCCESS', $data);
}
... ... @@ -156,17 +160,17 @@ class Member extends Api
$limit = Config::get('paginate.index_rows');
$betweenTime = ['1970-1-1',date('Y-m-d')];
if ($date){
$dateArr = explode('-',$date);
$betweenTime = ['1970-1-1', date('Y-m-d')];
if ($date) {
$dateArr = explode('-', $date);
$lastDay = cal_days_in_month(CAL_GREGORIAN, $dateArr[1], $dateArr[0]);
$lastDate = $dateArr[0].'-'.$dateArr[1].'-'.$lastDay;
$betweenTime = [$date,$lastDate];
$lastDate = $dateArr[0] . '-' . $dateArr[1] . '-' . $lastDay;
$betweenTime = [$date, $lastDate];
}
$where['user_id'] = $userId;
$data = $model->selectPageData($where,$page,$limit,$betweenTime);
$data = $model->selectPageData($where, $page, $limit, $betweenTime);
$this->success('SUCCESS', $data);
}
... ... @@ -203,17 +207,96 @@ class Member extends Api
$page = $this->request->param('page');
$date = $this->request->param('date');
$limit = Config::get('paginate.index_rows');
$betweenTime = ['1970-1-1',date('Y-m-d')];
if ($date){
$dateArr = explode('-',$date);
$betweenTime = ['1970-1-1', date('Y-m-d')];
if ($date) {
$dateArr = explode('-', $date);
$lastDay = cal_days_in_month(CAL_GREGORIAN, $dateArr[1], $dateArr[0]);
$lastDate = $dateArr[0].'-'.$dateArr[1].'-'.$lastDay;
$betweenTime = [$date,$lastDate];
$lastDate = $dateArr[0] . '-' . $dateArr[1] . '-' . $lastDay;
$betweenTime = [$date, $lastDate];
}
$where['user_id'] = $userId;
$data = $model->selectPageData($where,$page,$limit,$betweenTime);
$data = $model->selectPageData($where, $page, $limit, $betweenTime);
$this->success('SUCCESS', $data);
}
/**
* @ApiTitle (我的订单)
* @ApiSummary (我的订单)
* @ApiMethod (POST)
* @ApiRoute (/api/member/getOrder)
* @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
* @ApiParams (name=type, type=string, required=true, description="1=我的订单2=我的团单")
* @ApiParams (name=page, type=string, required=true, description="页数")
* @ApiReturn({
"code": 1,
"msg": "SUCCESS",
"time": "1587560895",
"data": {
"total": 1,
"list": [
{
"score": "10.00", 变更积分
"after": "10.00", 变更后积分
"type": "type",
"createtime": "2020-04-20 16:13"
}
]
}
})
*/
public function getOrder()
{
$orderInfoModel = new OrderInfo();
$orderDetailModel = new OrderDetail();
$orderModel = new Order();
$userId = $this->getUserId();
$type = $this->request->param('type');
$page = $this->request->param('page');
$limit = Config::get('paginate.index_rows');
if (empty($type)) $this->error('缺少参数 type!');
$where = ['user_id'=>$userId];
if ($type == 1) $where['type'] = ['neq',3];
else $where['type'] = ['eq',3];
$list = $orderModel->selectPageData($where, $page, $limit);
$data = [];
foreach ($list['list'] as $k => $order) {
if ($order['status'] == -1){
$order['status_text'] = '已取消';
$order['goods_image'] = $orderInfoModel->where('order_id',$order['order_id'])->column('goods_image');
$data[] = $order;
}elseif($order['status'] == 1){
$order['status_text'] = '待付款';
if ($order['type'] == 3 && $order['team_group_status'] == 3) $order['status_text'] = '拼团失败';
$order['goods_image'] = $orderInfoModel->where('order_id',$order['order_id'])->column('goods_image');
$data[] = $order;
}elseif($order['status'] == 2){
$detailInfo = $orderDetailModel->where('order_id',$order['order_id'])->field('id,status')->select();
foreach ($detailInfo as $key => $detail){
$tmp['order_id'] = $order['order_id'];
$tmp['order_detail_id'] = $detail['id'];
$tmp['team_group_id'] = $order['team_group_id'];
$tmp['order_num'] = $order['order_num'];
$tmp['createtime'] = $order['createtime'];
$tmp['pay_total'] = 0;
$tmp['status'] = $detail['status'];
$tmp['status_text'] = $detail['status_text'];
$tmp['goods_image'] = [];
if ($order['type'] == 3 && $order['team_group_status'] == 1) $tmp['status_text'] = '待成团';
$orderInfo = $orderInfoModel->where(['order_detail_id'=>$detail['id']])->field('goods_image,goods_total')->select();
foreach ($orderInfo as $kk => $info){
$tmp['pay_total'] += $orderInfo[$kk]['goods_total'];
$tmp['goods_image'][] = $orderInfo[$kk]['goods_image'];
}
$data[] = $tmp;
}
}elseif($order['status'] == 3){
$order['status_text'] = '已退款';
$order['goods_image'] = $orderInfoModel->where('order_id',$order['order_id'])->column('goods_image');
$data[] = $order;
}
}
$this->success('SUCCESS', $data);
}
}
\ No newline at end of file
... ...
... ... @@ -2,6 +2,8 @@
namespace app\api\controller;
use addons\kdniao\library\Kdniao;
use app\api\model\OrderDetail;
use app\api\model\UserScoreLog;
use app\common\controller\Api;
use think\Db;
... ... @@ -22,6 +24,7 @@ class Order extends Api
protected $orderAddressModel;
protected $orderAddressInvoiceModel;
protected $orderInfoModel;
protected $orderDetailModel;
protected $userModel;
protected function _initialize()
... ... @@ -37,6 +40,7 @@ class Order extends Api
$this->orderAddressModel = new \app\api\model\OrderAddress();
$this->orderAddressInvoiceModel = new \app\api\model\OrderAddressInvoice();
$this->orderInfoModel = new \app\api\model\OrderInfo();
$this->orderDetailModel = new \app\api\model\OrderDetail();
$this->userModel = new \app\api\model\User();
}
... ... @@ -278,14 +282,12 @@ class Order extends Api
//获取普通商品状态
if ($goodsIds) {
$goodsList = $this->goodsModel->selectGoodsStatus(['id' => ['in', $goodsIds]]);
//判断商品是否有库存和状态
foreach ($goodsList as $k => $v) {
if ($v['status'] == 2) $this->error($v['ch_name'] . '商品已下架');
if ($v['stock_num'] == 0) $this->error($v['ch_name'] . '商品库存不足');
}
}
//获取积分商品状态
if ($goodsIntegralIds) {
$goodsIntegralList = $this->integralGoodsModel->selectGoodsStatus(['id' => ['in', $goodsIntegralIds]]);
... ... @@ -1272,4 +1274,145 @@ class Order extends Api
if ($res) $this->success('取消订单成功');
else $this->error('取消订单失败');
}
/**
* @ApiTitle (订单详情)
* @ApiSummary (订单详情)
* @ApiMethod (POST)
* @ApiRoute (/api/order/orderInfo)
* @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
* @ApiParams (name=order_id, type=string, required=true, description="订单id")
* @ApiParams (name=order_detail_id, type=string, required=false, description="订单子表id")
* @ApiReturn ({
{
"code": 1,
"msg": "success",
"time": "1588041622",
"data": {
"createtime": "2020-04-27 16:56:31", 下单时间
"order_num": "2020042710254102", 订单号
"status": "2",
"postage_date": "", 配送日期
"postage_time": "", 配送时间
"pay_type": "2", 支付类型
"pay_total": "55.65", 支付金额
"goods_total": "27.00", 商品金额
"postage_total": "30.00", 运费
"discount_price": "1.35", 折扣金额
"score": "", 积分
"ticket_price": "0.00", 优惠券金额
"ticketcode_id": 0,
"ticketcode": 0, 优惠码
"name": "", 收货人姓名
"mobile": "13752011792", 收货人手机号
"address": 123, 收货详情地址
"ch_province_name": "天津", 收货地址省
"ch_city_name": "天津市", 收货地址市
"ch_county_name": "和平区", 收货地址县
"status_text": "已完成" 订单状态
}
}
})
*/
public function orderInfo()
{
$userId = $this->getUserId();
$param = $this->request->param();
$rule = [
'order_id' => 'require',
];
$msg = [
'order_id' => '缺少参数 order_id!',
];
$validate = new Validate($rule, $msg);
$result = $validate->check($param);
if (!$result) {
$this->error(__($validate->getError()));
}
$order = $this->orderModel->getInfo(['o.id' => $param['order_id']]);
if (!$order) $this->error('订单不存在');
if (!empty($order['ticketcode_id'])) {
$order['ticketcode'] = $this->ticketCodeModel->where('id', $order['ticketcode_id'])->value('code');
}
$detailInfo = $this->orderDetailModel->where('id',$param['order_detail_id'])->field('shipper_code,logistic_code,status')->find();
if (!empty($order['team_group_status'] && $order['team_group_status'] == 1)) {
$order['status_text'] = '待成团';
} elseif (!empty($order['team_group_status'] && $order['team_group_status'] == 2 && $detailInfo['status'] == 2)) {
$order['status_text'] = '待发货';
} elseif (!empty($order['team_group_status'] && $order['team_group_status'] == 3)) {
$order['status_text'] = '拼团失败';
} elseif ($order['status'] == 2) {
$order['status_text'] = $this->orderDetailModel->where('order_id', $param['order_id'])->field('status')->find()['status_text'];
} elseif ($order['status'] == 1) {
$order['status_text'] = '待付款';
}elseif ($order['status'] == 3) {
$order['status_text'] = '已退款';
$order['refund_time'] = '2020-01-01 08:33:23';
$order['refund_remark'] = '退款至微信钱包';
$order['refund_price'] = '8888';
}
if($detailInfo['status'] == 3 || $detailInfo['status'] == 4 || $detailInfo['status'] == 5){
if (empty($detailInfo['shipper_code']) || empty($detailInfo['logistic_code'])) {
$this->error('该订单缺少物流单号或者快递公司编码参数');
}
$code = $detailInfo['shipper_code'];
$company = $detailInfo['logistic_code'];
$kdniao = new Kdniao();
$wuliu = $kdniao->getOrderTracesByJson($company, $code);
$wuliu = json_decode($wuliu, true);
$wuliu = isset($wuliu['Traces']) && count($wuliu['Traces']) ? array_reverse($wuliu['Traces']) : ['AcceptStation' => '暂无物流信息', 'AcceptTime' => date('Y-m-d H:i:s', time())];
if (!empty($wuliu[0])){
$order['wuliu'] = $wuliu[0];
}else{
$order['wuliu'] = $wuliu;
}
}
$this->success('success', $order);
}
/**
* @ApiTitle (订单物流详情)
* @ApiSummary (订单物流详情)
* @ApiMethod (POST)
* @ApiRoute (/api/order/orderLogisticsInfo)
* @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
* @ApiParams (name=order_detail_id, type=string, required=true, description="订单子表id")
* @ApiReturn ({
})
*/
public function orderLogisticsInfo()
{
$user_id = $this->getUserId();
$order_detail_id = $this->request->param('order_detail_id');
$orderDetailModel = new OrderDetail();
$where['user_id'] = ['eq', $user_id];
$where['id'] = ['eq', $order_detail_id];
$data = $orderDetailModel->where($where)->field('shipper_code,logistic_code')->find();
if (empty($data)) {
$this->error('查询为空');
}
if (empty($data['shipper_code']) || empty($data['logistic_code'])) {
$this->error('该订单缺少物流单号或者快递公司编码参数');
}
$code = $data['shipper_code'];
$company = $data['logistic_code'];
$kdniao = new Kdniao();
$wuliu = $kdniao->getOrderTracesByJson($company, $code);
$wuliu = json_decode($wuliu, true);
$wuliu = isset($wuliu['Traces']) && count($wuliu['Traces']) ? array_reverse($wuliu['Traces']) : [['AcceptStation' => '暂无物流信息', 'AcceptTime' => date('Y-m-d H:i:s', time())]];
$data['company_name'] = Db::name('kdniao')->where(['code' => $data['logistic_code']])->value('company');
$data['wuliu'] = $wuliu;
$this->success('SUCCESS', $data);
}
}
... ...
... ... @@ -22,6 +22,7 @@ class Sundry extends Api
parent::_initialize();
}
/**
* @ApiTitle (幻灯片)
* @ApiSummary (幻灯片)
... ... @@ -39,10 +40,11 @@ class Sundry extends Api
},
})
*/
public function getSlide(){
public function getSlide()
{
$slideModel = new Slide();
$data = $slideModel->selectData([]);
$this->success('SUCCESS',$data);
$this->success('SUCCESS', $data);
}
/**
... ... @@ -64,12 +66,13 @@ class Sundry extends Api
},
})
*/
public function getUserKeyword(){
$limit = $this->request->param('limit')?$this->request->param('limit'):8;
public function getUserKeyword()
{
$limit = $this->request->param('limit') ? $this->request->param('limit') : 8;
$model = new KeywordLog();
$userId = $this->getUserId();
$data = $model->selectData(['user_id'=>$userId],$limit);
$this->success('SUCCESS',$data);
$data = $model->selectData(['user_id' => $userId], $limit);
$this->success('SUCCESS', $data);
}
/**
... ... @@ -90,7 +93,8 @@ class Sundry extends Api
},
})
*/
public function getArea(){
public function getArea()
{
$areaModel = new Area();
$params = $this->request->param();
$where['pid'] = 0;
... ... @@ -99,7 +103,7 @@ class Sundry extends Api
$data = $areaModel->where($where)->field('id,name')->select();
$this->success('SUCCESS',$data);
$this->success('SUCCESS', $data);
}
/**
... ... @@ -121,7 +125,8 @@ class Sundry extends Api
},
})
*/
public function getDeliveryTime(){
public function getDeliveryTime()
{
$model = new AreaExtend();
$params = $this->request->param();
... ... @@ -131,10 +136,10 @@ class Sundry extends Api
if (!empty($params['county_id'])) $where['county_id'] = $params['county_id'];
$data = $model->where($where)->field('is_special,starttime1,endtime1,starttime2,endtime2')->find();
$startDate = date("Y-m-d",strtotime('+'.$data['starttime1'].' days',time()));
$endDate = date("Y-m-d",strtotime('+'.$data['endtime1'].' days',time()));
$data['date'] = period_date($startDate,$endDate);
$this->success('SUCCESS',$data);
$startDate = date("Y-m-d", strtotime('+' . $data['starttime1'] . ' days', time()));
$endDate = date("Y-m-d", strtotime('+' . $data['endtime1'] . ' days', time()));
$data['date'] = period_date($startDate, $endDate);
$this->success('SUCCESS', $data);
}
/**
... ... @@ -154,14 +159,49 @@ class Sundry extends Api
},
})
*/
public function getDeliveryFastTime(){
public function getDeliveryFastTime()
{
$model = new WeekTemplate();
$week = $this->request->param('week');
if (empty($week)) $this->error('缺少参数 week!');
$data = $model->selectData(['type'=>$week]);
foreach ($data as $k=>$v){
$data[$k] = $v['starttime'].'-'.$v['endtime'];
$data = $model->selectData(['type' => $week]);
foreach ($data as $k => $v) {
$data[$k] = $v['starttime'] . '-' . $v['endtime'];
}
$this->success('SUCCESS', $data);
}
/**
* @ApiTitle (获取文本)
* @ApiSummary (获取文本)
* @ApiMethod (POST)
* @ApiRoute (/api/sundry/getText)
* @ApiHeaders (name=token, type=string, required=false, description="请求的Token")
* @ApiParams (name=type, type=string, required=true, description="类型:1=会员特权文本,2=提现说明文本,3=配送详情文本")
* @ApiReturn({
"code": 1,
"msg": "SUCCESS",
"time": "1553839125",
"data": {
"id": "id",// 地区id
"name": "name",// 名称
},
})
*/
public function getText()
{
$type = $this->request->param('type');
switch ($type) {
case 1:
$data = '会员特权文本';
break;
case 2:
$data = '提现说明文本';
break;
case 3:
$data = '配送详情文本';
break;
}
$this->success('SUCCESS',$data);
$this->success('SUCCESS', $data);
}
}
... ...
... ... @@ -15,6 +15,36 @@ class Order extends Model
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
public function getCreatetimeAttr($value)
{
return date('Y-m-d H:i:s',$value);
}
public function selectPageData($where,$page,$limit)
{
$total = $this
->where($where)
->count();
$orderList = $this
->where($where)
->field('id order_id,order_num,createtime,pay_total,status,type,team_group_status,team_group_id')
->order('createtime desc')
->page($page,$limit)
->select();
return ['total' => $total, 'list' => $orderList];
}
public function getInfo($where)
{
$data = $this->alias('o')
->join('fa_order_address oa', 'oa.order_id=o.id')
->where($where)
->field('o.createtime,o.order_num,o.status,o.postage_date,o.postage_time,o.pay_type,o.pay_total,o.goods_total,o.postage_total,o.discount_price,o.score,o.team_group_status,o.ticket_price,o.ticketcode_id,oa.name,oa.mobile,oa.address,oa.ch_province_name,oa.ch_city_name,oa.ch_county_name')
->find();
return $data;
}
/**
* 余额支付
* @param $order_id 订单id
... ... @@ -49,6 +79,7 @@ class Order extends Model
//获取以仓库分好的商品
$goodsDepotList = setArr($data);
$orderInfoData = [];
$oldOrderInfoIds = []; //获取创建订单时 order_info_id
foreach ($goodsDepotList as $k => $goodsDepot) {
$detailArr = reset($goodsDepot);
$detailData = [
... ... @@ -62,8 +93,6 @@ class Order extends Model
];
//添加订单子表
$detailId = $orderDetailModel->insertGetId($detailData);
$oldOrderInfoIds = []; //获取创建订单时 order_info_id
foreach ($goodsDepot as $key => $goodsDepotInfo) {
$where = [
'order_id' => $order_id,
... ... @@ -72,7 +101,7 @@ class Order extends Model
'type' => $order['type'] == 3 ? 3 : $goodsDepotInfo['type'],
];
$orderInfo = $orderInfoModel->where($where)->find();
$oldOrderInfoIds[] = $orderInfo['id'];
if (!in_array($orderInfo['id'],$oldOrderInfoIds)) $oldOrderInfoIds[] = $orderInfo['id'];
$orderInfoData[] = [
'pay_type' => $orderInfo['pay_type'], //余额支付
'order_id' => $order_id,
... ... @@ -177,6 +206,158 @@ class Order extends Model
}
}
/**
* 微信支付回调
* @param $order_id 订单id
* @param $user_id 用户id
* @param $money 支付金额
* @return boolean
*/
public function WXPay($order_id, $user_id, $money, $goodsList)
{
$goodsModel = new \app\api\model\Goods();
$userScoreLogModel = new \app\api\model\UserScoreLog();
$orderDetailModel = new \app\api\model\OrderDetail();
$orderInfoModel = new \app\api\model\OrderInfo();
Db::startTrans();
try {
$areaId = Db::name('order_address')->where('order_id', $order_id)->value('province_id');
$oldscore = Db::name('user')->where('id', $user_id)->value('score');
$integral_total = 0; //购买商品所需积分
//获取订单
$order = $this->where('id', $order_id)->field('id,pay_total,postage_total,ticket_price,ticketcode_price,type,team_group_id,team_group_status')->find();
foreach ($goodsList as $key => $goods) {
$integral_total += $goods['score']; //累计积分总数
if ($goods['type'] == 3) $goods['type'] = '1';
//根据仓库进行拆单
$data[] = $goodsModel->getDepot($goods['goods_id'], $areaId, $goods['number'], $goods['type']);
if (!$data[$key]) return ['code' => -1, 'msg' => $goods['ch_goods_name'] . ' 库存不足'];
}
//获取以仓库分好的商品
$goodsDepotList = setArr($data);
$orderInfoData = [];
$oldOrderInfoIds = []; //获取创建订单时 order_info_id
foreach ($goodsDepotList as $k => $goodsDepot) {
$detailArr = reset($goodsDepot);
$detailData = [
'order_id' => $order_id,
'user_id' => $user_id,
'pay_type' => 2, //余额支付
'depot_id' => $detailArr['depots_id'],
'status' => 2, //代发货
'createtime' => time(),
'updatetime' => time(),
];
//添加订单子表
$detailId = $orderDetailModel->insertGetId($detailData);
foreach ($goodsDepot as $key => $goodsDepotInfo) {
$where = [
'order_id' => $order_id,
'user_id' => $user_id,
'goods_id' => $goodsDepotInfo['goods_id'],
'type' => $order['type'] == 3 ? 3 : $goodsDepotInfo['type'],
];
$orderInfo = $orderInfoModel->where($where)->find();
if (!in_array($orderInfo['id'],$oldOrderInfoIds)) $oldOrderInfoIds[] = $orderInfo['id'];
$orderInfoData[] = [
'pay_type' => $orderInfo['pay_type'], //余额支付
'order_id' => $order_id,
'order_detail_id' => $detailId,
'user_id' => $user_id,
'goods_id' => $goodsDepotInfo['goods_id'],
'type' => $goodsDepotInfo['type'],
'ch_goods_name' => $orderInfo['ch_goods_name'],
'en_goods_name' => $orderInfo['en_goods_name'],
'goods_image' => $orderInfo['goods_image'],
'number' => $goodsDepotInfo['number'],
'goods_total' => round($orderInfo['goods_total'] / $orderInfo['number'] * $goodsDepotInfo['number'], 2),
'pay_total' => $orderInfo['pay_total'],
'postage_total' => $orderInfo['postage_total'],
'score' => $orderInfo['score'] / $orderInfo['number'] * $goodsDepotInfo['number'],
];
//减仓库库存
Db::name('depot')->where('id', $goodsDepotInfo['depots_id'])->setDec('stock_num', $goodsDepotInfo['number']);
//判断商品类型减去库存 加销量
if ($goodsDepotInfo['type'] == 2) {
Db::name('integral_goods')->where('id', $goodsDepotInfo['goods_id'])->setDec('stock_num', $goodsDepotInfo['number']);
Db::name('integral_goods')->where('id', $goodsDepotInfo['goods_id'])->setInc('sales_actual', $goodsDepotInfo['number']);
} else {
Db::name('goods')->where('id', $goodsDepotInfo['goods_id'])->setDec('stock_num', $goodsDepotInfo['number']);
Db::name('goods')->where('id', $goodsDepotInfo['goods_id'])->setInc('sales_actual', $goodsDepotInfo['number']);
}
}
}
//添加订单详情
$orderInfoModel->saveAll($orderInfoData);
//删除之前订单详情
$orderInfoModel->where(['id' => ['in', $oldOrderInfoIds]])->delete();
//有积分商品减积分
if ($integral_total != 0) {
$userScoreLogModel->setDecScore($user_id, $integral_total);
}
//将订单状态修改为已支付
$this->where('id', $order_id)->update(['status' => 2, 'paytime' => time()]);
//积分变动表记录
$oldscore = Db::name('user')->where('id', $user_id)->value('score');
$scoredata = [
'user_id' => $user_id,
'type' => 1, //购物返积分
'score' => intval($money),
'before' => $oldscore,
'after' => $oldscore + intval($money),
'createtime' => time(),
];
Db::name('user_score_log')->insert($scoredata);
Db::name('user')->where('id', $user_id)->setInc('score', intval($money));
$user_pid = Db::name('user')->where('id', $user_id)->value('pid');
//判断是否有上级进行返利 团购订单不在这里返利
if ($user_pid && $order['type'] != 3) {
if (!empty($order['ticket_price'])) $order['pay_total'] += $order['ticket_price'];
if (!empty($order['ticketcode_price'])) $order['pay_total'] += $order['ticketcode_price'];
if (!empty($order['postage_total'])) $order['pay_total'] -= $order['postage_total'];
$parentInfo = Db::name('user')->where('id', $user_pid)->find();
//普通用户无返利
if ($parentInfo['type'] != 1) {
$rebateMoney = get_rebate($order['pay_total'], $parentInfo['type']);
$rebatedata = [
'user_id' => $user_pid,
'type' => 4, //佣金收入(返利)
'money' => $rebateMoney,
'before' => $parentInfo['money'],
'after' => $parentInfo['money'] + $rebateMoney,
'createtime' => time(),
];
Db::name('user_money_log')->insert($rebatedata);
Db::name('user')->where('id', $user_pid)->setInc('money', $rebateMoney);
}
}
if ($order['type'] == 3 && !empty($order['team_group_id'])) {
//参团
$this->joinTeam($order, $user_id);
} elseif ($order['type'] == 3) {
//开团
$this->createTeam($order, $user_id);
}
Db::commit();
return true;
} catch (Exception $e) {
Db::rollback();
return false;
}
}
/**
* 开团
* @param $order
* @param $user_id
* @return bool
*/
public function createTeam($order, $user_id)
{
$goods_id = Db::name('order_info')->where(['order_id' => $order['id']])->value('goods_id');
... ... @@ -237,6 +418,12 @@ class Order extends Model
Db::name('team_group_info')->insertGetId($teamInfoData);
}
/**
* 参团
* @param $order
* @param $user_id
* @return bool
*/
public function joinTeam($order, $user_id)
{
$user_info = Db::name('user')->where(['id' => $user_id])->field('id,avatar,nickname,pid')->find();
... ... @@ -292,8 +479,14 @@ class Order extends Model
$this->where(['team_group_id' => $order['team_group_id'],'user_id'=>['not in',$ids]])->update(['team_group_status' => 3]);
}
return true;
}
/**
* 取消订单
* @param $order
* @return bool
*/
public function orderCancel($order){
$userTicketModel = new UserTicket();
$ticketcodeModel = new Ticketcode();
... ... @@ -315,4 +508,13 @@ class Order extends Model
return false;
}
}
/**
* 订单退款
* @param $order
*/
public function orderRefund($order){
$this->where('id',$order['id'])->update(['status'=>4]);
}
}
... ...
... ... @@ -14,5 +14,21 @@ class OrderDetail extends Model
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
// 追加属性
protected $append = [
'status_text'
];
public function getStatusList()
{
//状态:-1=已取消,1=待支付,2=待发货,3=待收货,4=待评价,5=已完成
return ['-1' => '已取消', '1' => '待支付', '2' => '待发货', '3' => '待收货', '4' => '待评价', '5' => '已完成'];
}
public function getStatusTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
$list = $this->getStatusList();
return isset($list[$value]) ? $list[$value] : '';
}
}
... ...
此 diff 太大无法显示。
define([], function () {
//修改上传的接口调用
if ($('.kdniao').length > 0) {
$('.kdniao').each(function () {
var code = $(this).data('code');
$(this).addClass('btn btn-xs bg-success').append('<i class="fa fa-truck"></i>' + code);
});
$('.kdniao').click(function () {
var company = $(this).data('company');
var code = $(this).data('code');
if (company && code) {
Layer.open({
type: 2,
area: ['700px', '450px'],
fixed: false, //不固定
maxmin: true,
content: '/addons/kdniao/index/query?company=' + company + '&code=' + code
});
}
});
}
//修改上传的接口调用
require(['upload'], function (Upload) {
var _onUploadResponse = Upload.events.onUploadResponse;
Upload.events.onUploadResponse = function (response) {
... ...