牟新芬 4 years ago
parent
commit
97b5878291

+ 35 - 0
app/AddressValidate.php

@@ -0,0 +1,35 @@
+<?php
+namespace app;
+
+use think\Validate;
+
+/**
+ * 用户地址验证类
+ * Class AddressValidate
+ * @package app\http\validates\user
+ */
+class AddressValidate extends  Validate
+{
+    //移动
+    protected $regex = [ 'phone' => '/^1[3456789]\d{9}|([0-9]{3,4}-)?[0-9]{7,8}$/'];
+
+    protected $rule = [
+        'real_name'  =>  'require|max:25',
+        'phone'  =>  'require|regex:phone',
+        'province'  =>  'require',
+        'city'  =>  'require',
+        'district'  =>  'require',
+        'detail'  =>  'require',
+    ];
+
+    protected $message  =   [
+        'real_name.require' => '名称必须填写',
+        'real_name.max'     => '名称最多不能超过25个字符',
+        'phone.require' => '手机号必须填写',
+        'phone.regex' => '手机号格式错误',
+        'province.require' => '省必须填写',
+        'city.require' => '市名称必须填写',
+        'district.require' => '区/县名称必须填写',
+        'detail.require' => '详细地址必须填写',
+    ];
+}

+ 4 - 0
app/Request.php

@@ -5,4 +5,8 @@ namespace app;
 class Request extends \think\Request
 {
 
+    /**
+     * @var mixed|null
+     */
+    private $user;
 }

+ 301 - 0
app/api/controller/v1/Order.php

@@ -0,0 +1,301 @@
+<?php
+
+namespace app\api\controller\v1;
+
+use app\BaseController;
+use app\model\api\ExpCost;
+use app\model\api\MemberDetail;
+use app\model\Api\MemberShop;
+use app\model\api\Order as OrderModel;
+use app\model\api\OrderInfo;
+use app\model\api\Product;
+use app\model\api\SiteProduct;
+use app\model\api\UserAddress;
+use app\model\api\Warehouse;
+use app\model\system\ProductAttr;
+use app\Request;
+use library\services\UtilService;
+use library\utils\Region;
+use think\db\exception\DbException;
+use think\facade\Db;
+
+class Order extends BaseController
+{
+    /**
+     * 获取产品信息
+     */
+    public function getProductInfo(Request $request){
+        $where = UtilService::getMore([
+            ['product_id', 0],
+            ['unique', '']
+        ], $request);
+        $data = Db::name('ProductAttrValue')->where('product_id', $where['product_id'])->where('unique', $where['unique'])->find();
+        if($data['price'] == '0.00'){
+            $data['price'] = round($data['ot_price'] * 1.15, 2);
+        }
+        $data['store_name'] = Db::name('Product')->where('id', $where['product_id'])->value('store_name');
+        return app('json')->success($data);
+    }
+
+    /**
+     * 买样订单
+     * @param Request $request
+     */
+    public function buyOrder(Request $request)
+    {
+        $data = UtilService::getMore([
+            ['pro_id', '', 'empty', '参数错误'],
+            ['unique', '', 'empty', '参数错误'],
+            ['num', '', 'empty', '参数错误'],
+            ['addressId', '', 'empty', '参数错误'],
+            ['pro_price', 0],
+            ['postage', 0],
+            ['all_price', 0],
+            ['mono', '']
+        ], $request);
+        try {
+            OrderModel::beginTrans();
+            $addressId = $data['addressId'];
+            unset($data['addressId']);
+            $data['order_id'] = 'TF' . time() . sprintf('%04d', rand(0, 1000)) . $request->user['uid']; //订单号
+            $data['uid'] = $request->user['uid'];
+            $data['time'] = time();
+            $oId = OrderModel::insertGetId($data);
+            $address = UserAddress::find($addressId);
+            $save['o_id'] = $oId;
+            $save['uid'] = $request->user['uid'];
+            $save['name'] = $address['real_name'];
+            $save['mobile'] = $address['phone'];
+            $save['address'] = $address['province'] . $address['city'] . $address['district'] . $address['detail'];
+            $save['money'] = $data['all_price'];
+            $save['pro_price'] = $data['pro_price'];
+            $save['pro_id'] = $data['pro_id'];
+            $save['exp_price'] = $data['postage'];
+            $save['time'] = time();
+            OrderInfo::insert($save);
+            OrderModel::commitTrans();
+        } catch (DbException $db) {
+            OrderModel::rollbackTrans();
+            return app('json')->fail("下单失败,原因:" . $db->getMessage());
+        }
+        return app('json')->success([
+            'order_id' => $data['order_id'],
+            'price'    => $data['all_price']
+        ]);
+    }
+
+    /**
+     * 代发订单
+     * @param Request $request
+     */
+    public function subOrder(Request $request)
+    {
+        [$orderAr, $proId, $warehouseId, $expId, $platformId, $mono, $extraFreight] = UtilService::getMore([
+            ['orderAr', '', 'empty', '参数错误'],
+            ['proId', '', 'empty', '参数错误'],
+            ['warehouseId', '', 'empty', '参数错误'],
+            ['expId', '', 'empty', '请选择运送方式'],
+            ['platformId', '', 'empty', '参数错误'],
+            ['mono', ''],
+            ['extraFreight', 0]
+        ], $request, true);
+        $expPrice          = 0;  //邮费费用
+        $expressId         = 0; //快递ID
+        $siteExpCommission = 0;//分站佣金费用
+        //检测数据
+        $sitePro = (new SiteProduct)->getItem($proId);
+        if ($sitePro['count'] <= 0 || count($orderAr) > $sitePro['count']) {
+            return app('json')->fail("订单产品数量不足,请重新选择!");
+        }
+        //判断仓库是否可以下单
+        $warehouseIds = explode(',',$sitePro['warehouse_ids']);
+        if(!in_array($warehouseId,$warehouseIds)) {
+            return app('json')->fail("请重新选择产品!");
+        }
+
+        $warehouse = (new Warehouse)->where('id',$warehouseId)->find();
+        if(empty($warehouse) || empty($warehouse['status'])) {
+            return app('json')->fail("分仓已下架,请选择其他分仓");
+        }
+        $region = new Region;
+        //检查地址数据
+        foreach ($orderAr as $k => $v) {
+            $rData = $region->getRegion($v['address']);
+            if (empty($rData['province']) ||
+                empty($rData['city']) ||
+                empty($rData['area'])
+            ) {
+                //  return app('json')->fail('第' . (intval($k) + 1) .'行,'.$v['address'] .'地址信息有误,请重新检查省市区!');
+            }
+        }
+
+        //订单总数
+        $orderCount        = count($orderAr);
+        $price             = $sitePro['price'] * $orderCount;
+        $siteProCommission = $sitePro['price'] > $sitePro['commission'] ? ($sitePro['price'] - $sitePro['commission']) : 0;//分站佣金
+        //快递信息
+        $expCode = new ExpCost;
+        $expCode->getExpCostData($request->site['sassid'], $request->user['levelid']);
+        $expData = array_filter($expCode->getWareHouseExpCost($warehouseId, '*'), function ($item) use ($expId) {
+            if ($item['id'] == $expId) {
+                return true;
+            }
+        });
+        //如果有快递信息,分析分账提成 || 用户推荐佣金
+        if (!empty($expData)) {
+            $expressId = $expData[0]['express_id'];
+            $expPrice  = $expData[0]['money'];
+            //分站金额
+            $money             = $expCode->getSysExpCostPrice($expressId, $warehouseId, $request->site['sassid']);
+            $siteExpCommission = empty($money) ? 0 : ($expPrice > $money ? ($expPrice - $money) : 0);
+        }
+
+        if (empty($expressId)) {
+            return app('json')->fail("本次邮寄方式不存在,请重新选择邮寄方式。");
+        }
+
+        //获取低价
+        $floorExp = $expCode
+            ->where('warehouse_id', $warehouseId)
+            ->where('express_id', $expressId)
+            ->where('sassid', 0)
+            ->where('level_id', -1)
+            ->value('money');
+        //会员店铺
+        $shopAr = [];
+        foreach ($orderAr as $v) {
+            $shop_name = trim($v['shop_name']);
+            if (!empty($shop_name)) {
+                $shopAr[$shop_name] = ['name' => $shop_name];
+            }
+        }
+        try {
+            \app\model\api\Order::beginTrans();
+            $mShop = new MemberShop;
+            foreach ($shopAr as $k => $v) {
+                $shopId = $mShop->where('name', $k)
+                    ->where('uid', $this->user['uid'])
+                    ->value('id');
+                if (empty($shopId)) $shopId = $mShop->insertGetId(['name' => $k, 'uid' => $this->user['uid']]);
+                $shopAr[$k]['id'] = $shopId;
+            }
+            //下单
+            $save['order_id']            = 'TF' . time() . sprintf('%04d', rand(0, 1000)) . $request->user['uid'];//订单号
+            $save['all_price']           = $price + $expPrice * $orderCount + $extraFreight;//总金额 [价格 + 快递*产品数量]
+            $save['pro_site_commission'] = $siteProCommission * $orderCount;//产品分站佣金
+            $save['exp_site_commission'] = $siteExpCommission * $orderCount;//快递分站佣金
+            $save['site_commission']     = $save['pro_site_commission'] + $save['exp_site_commission'];//分站提成
+            $save['pro_id']              = $sitePro['id'];//产品ID
+            $save['platform_id']         = $platformId;//来源[拼多多,淘宝]
+            $save['warehouse_id']        = $warehouseId;//仓库来源
+            $save['status']              = 0;//状态
+            $save['time']                = time();
+            $save['express_id']          = $expressId;//快递类型
+            $save['sassid']              = $request->site['sassid'];//分站
+            $save['mono']                = $mono;//备注
+            $save['pro_price']           = $price;//产品价格
+            $save['uid']                 = $request->user['uid'];
+            $oId                         = (new Order)->insertGetId($save);
+
+            foreach ($orderAr as $k => $v) {
+                $shop_name                = trim($v['shop_name']);
+                $d                        = [];
+                $d['o_id']                = $oId;
+                $d['in_order_id']         = $save['order_id'] . '-' . ($k + 1);
+                $d['out_order_id']        = $v['out_order_id'];
+                $d['name']                = $v['name'];
+                $d['mobile']              = $v['mobile'];
+                $d['address']             = $v['address'];
+                $d['pro_price']           = $sitePro['price'];
+                $d['pro_id']              = $sitePro['id'];
+                $d['exp_id']              = $expressId;
+                if(strstr($d['address'], '北京')){
+                    $d['exp_price'] = $expPrice + $warehouse['beijing'];
+                }else if(strstr($d['address'], '上海')){
+                    $d['exp_price'] = $expPrice + $warehouse['shanghai'];
+                }else if(strstr($d['address'], '青海')){
+                    $d['exp_price'] = $expPrice + $warehouse['qinghai'];
+                }else{
+                    $d['exp_price'] = $expPrice;
+                }
+                $d['money']               = $sitePro['price'] + $d['exp_price'];
+                $d['sassid']              = $request->site['sassid'];
+                $d['uid']                 = $request->user['uid'];
+                $d['time']                = time();
+                $d['platform_id']         = $platformId;
+                $d['warehouse_id']        = $warehouseId;
+                $d['pro_site_commission'] = $siteProCommission;
+                $d['exp_site_commission'] = $siteExpCommission;
+                $d['site_commission']     = $siteProCommission + $siteExpCommission;
+                $d['exp_floor_price']     = empty($floorExp) ? 0 : $floorExp;
+                $d['shop_id']             = empty($shop_name) ? 0 : $shopAr[$shop_name]['id'];
+                (new OrderInfo)->insert($d);
+            }
+            Order::commitTrans();
+        } catch (DbException $db) {
+            Order::rollbackTrans();
+            return app('json')->fail("下单失败,理由:" . $db->getMessage());
+        }
+        return app('json')->success([
+            'order_id' => $save['order_id'],
+            'price'    => $save['all_price'],
+        ]);
+    }
+
+    /**
+     * 余额支付
+     * @param Request $request
+     */
+    public function balancePay(Request $request)
+    {
+        [$orderId] = UtilService::getMore([
+            ['order_id', '', 'empty', '参数错误'],
+        ], $request, true);
+        $order = OrderModel::where('order_id', $orderId)->find();
+        if (empty($order)) {
+            return app('json')->fail('找不到订单信息');
+        }
+        //订单已付款
+        if (!empty($order['is_pay'])) {
+            return app('json')->fail('订单已经支付成功');
+        }
+        if ($order['all_price'] > $request->user['money']) {
+            return app('json')->fail('余额不足!');
+        }
+
+        $res = (new MemberDetail)->consumption($order['all_price'], $request->user['uid'], [
+            'mobile'   => $request->user['mobile'],
+            'order_id' => $orderId,
+            'money'    => $order['all_price']
+        ]);
+        if ($res) {
+            //减库存加销量
+            (new Product)->where('id', $order['pro_id'])->dec('stock', $order['num'])->inc('sales', $order['num'])->update();
+            Db::name('ProductAttrValue')->where('product_id', $order['pro_id'])->where('unique', $order['unique'])->dec('stock', $order['num'])->inc('sales', $order['num'])->update();
+            //改订单状态
+            OrderModel::where('order_id', $orderId)->save([
+                'status'   => 1,
+                'is_pay'   => 1,
+                'pay_time' => time()
+            ]);
+            //改子订单状态
+            OrderInfo::where('o_id', $order['id'])->save(['status' => 1,]);
+
+            //设置维护人
+            /*$last_con_time = (new Member)->where('uid', $request->user['uid'])->value('last_con_time');
+            if($last_con_time == 0){
+                $follow = (new MemberFollow)->where('uid', $request->user['uid'])->where('admin_id', 99)->find();
+                if($follow){
+                    (new Member)->where('uid', $request->user['uid'])->save(['admin_id' => 99]);
+                }else{
+                    (new Member)->where('uid', $request->user['uid'])->save(['admin_id' => 100]);
+                }
+            }
+            (new Member)->where('uid', $request->user['uid'])->save(['last_con_time' => time()]);*/
+
+            return app('json')->success(['msg' => '支付成功']);
+        } else {
+            return app('json')->fail('支付失败');
+        }
+    }
+}

+ 33 - 1
app/api/controller/v1/Pub.php

@@ -4,9 +4,11 @@ namespace app\api\controller\v1;
 
 use app\BaseController;
 use app\model\api\Warehouse;
+use app\model\api\SystemCity;
 use app\model\system\Sys;
 use app\Request;
 use library\services\UtilService;
+use library\services\CacheService;
 
 class Pub extends BaseController
 {
@@ -79,7 +81,37 @@ class Pub extends BaseController
         return app('json')->success($data);
     }
 
-
+    /**
+     * 查找城市数据
+     * @param Request $request
+     * @return mixed
+     * @throws \throwable
+     */
+    public function city_list(Request $request)
+    {
+        $list = CacheService::get('CITY_LIST', function () {
+            $list = SystemCity::with('children')->field(['city_id', 'name', 'id', 'parent_id'])->where('parent_id', 0)->order('id asc')->select()->toArray();
+            $data = [];
+            foreach ($list as &$item) {
+                $value = ['v' => $item['city_id'], 'n' => $item['name']];
+                if ($item['children']) {
+                    foreach ($item['children'] as $key => &$child) {
+                        $value['c'][$key] = ['v' => $child['city_id'], 'n' => $child['name']];
+                        unset($child['id'], $child['area_code'], $child['merger_name'], $child['is_show'], $child['level'], $child['lng'], $child['lat'], $child['lat']);
+                        if (SystemCity::where('parent_id', $child['city_id'])->count()) {
+                            $child['children'] = SystemCity::where('parent_id', $child['city_id'])->field(['city_id', 'name', 'id', 'parent_id'])->select()->toArray();
+                            foreach ($child['children'] as $kk => $vv) {
+                                $value['c'][$key]['c'][$kk] = ['v' => $vv['city_id'], 'n' => $vv['name']];
+                            }
+                        }
+                    }
+                }
+                $data[] = $value;
+            }
+            return $data;
+        }, 0);
+        return app('json')->successful($list);
+    }
 
 
 

+ 160 - 10
app/api/controller/v1/User.php

@@ -1,16 +1,8 @@
 <?php
-declare (strict_types=1);
 
 namespace app\api\controller\v1;
-// +----------------------------------------------------------------------
-// | [ WE CAN DO IT MORE SIMPLE  ]
-// +----------------------------------------------------------------------
-// | Copyright (c) 2018-2020 rights reserved.
-// +----------------------------------------------------------------------
-// | Author: TABLE ME
-// +----------------------------------------------------------------------
-// | Date: 2020-08-31 15:05
-// +----------------------------------------------------------------------
+
+use app\AddressValidate;
 use app\model\admin\MemberLevel;
 use app\model\admin\Product;
 use app\model\admin\SiteLevel;
@@ -29,6 +21,8 @@ use app\model\api\SiteProduct;
 use app\model\api\Tx;
 use app\model\api\Warehouse;
 use app\model\api\WeixinPushUser;
+use app\model\api\UserAddress;
+use app\model\api\SystemCity;
 use app\model\system\MemberFollow;
 use app\model\system\News;
 use app\Request;
@@ -43,9 +37,165 @@ use think\facade\Db;
 use think\Image;
 use Alipay\EasySDK\Kernel\Factory;
 use Alipay\EasySDK\Kernel\Config;
+use think\exception\ValidateException;
 
 class User extends AuthController
 {
+    /**
+     * 地址 获取单个
+     * @param Request $request
+     * @param $id
+     * @return mixed
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws DbException
+     */
+    public function address(Request $request, $id)
+    {
+        $addressInfo = [];
+        if ($id && is_numeric($id) && UserAddress::be(['is_del' => 0, 'id' => $id, 'uid' => $request->user['uid']])) {
+            $addressInfo = UserAddress::find($id)->toArray();
+        }
+        return app('json')->successful($addressInfo);
+    }
+
+    /**
+     * 地址列表
+     * @param Request $request
+     * @param $page
+     * @param $limit
+     * @return mixed
+     * @throws \Exception
+     */
+    public function address_list(Request $request)
+    {
+        list($page, $limit) = UtilService::getMore([['page', 0], ['limit', 20]], $request, true);
+        $list = UserAddress::getUserValidAddressList($request->user['uid'], $page, $limit, 'id,real_name,phone,province,city,district,detail,is_default');
+        return app('json')->successful($list);
+    }
+
+    /**
+     * 设置默认地址
+     *
+     * @param Request $request
+     * @return mixed
+     * @throws \Exception
+     */
+    public function address_default_set(Request $request)
+    {
+        list($id) = UtilService::getMore([['id', 0]], $request, true);
+        if (!$id || !is_numeric($id)) return app('json')->fail('参数错误!');
+        if (!UserAddress::be(['is_del' => 0, 'id' => $id, 'uid' => $request->user['uid']]))
+            return app('json')->fail('地址不存在!');
+        $res = UserAddress::setDefaultAddress($id, $request->user['uid']);
+        if (!$res)
+            return app('json')->fail('地址不存在!');
+        else
+            return app('json')->successful();
+    }
+
+    /**
+     * 获取默认地址
+     * @param Request $request
+     * @return mixed
+     */
+    public function address_default(Request $request)
+    {
+        $defaultAddress = UserAddress::getUserDefaultAddress($request->user['uid'], 'id,real_name,phone,province,city,district,detail,is_default');
+        if ($defaultAddress) {
+            $defaultAddress = $defaultAddress->toArray();
+            return app('json')->successful('ok', $defaultAddress);
+        }
+        return app('json')->successful('empty', []);
+    }
+
+    /**
+     * 修改 添加地址
+     * @param Request $request
+     * @return mixed
+     * @throws \Exception
+     */
+    public function address_edit(Request $request)
+    {
+        $addressInfo = UtilService::getMore([
+            ['address', []],
+            ['is_default', false],
+            ['real_name', ''],
+            ['post_code', ''],
+            ['phone', ''],
+            ['detail', ''],
+            ['id', 0],
+            ['type', 0]
+        ], $request);
+        if (!isset($addressInfo['address']['province'])) return app('json')->fail('收货地址格式错误!');
+        if (!isset($addressInfo['address']['city'])) return app('json')->fail('收货地址格式错误!');
+        if (!isset($addressInfo['address']['district'])) return app('json')->fail('收货地址格式错误!');
+        if (!isset($addressInfo['address']['city_id']) && $addressInfo['type'] == 0) {
+            return app('json')->fail('收货地址格式错误!请重新选择!');
+        } else if ($addressInfo['type'] == 1) {
+            $city = $addressInfo['address']['city'];
+            $cityId = SystemCity::where('name', $city)->where('parent_id', '<>', 0)->value('city_id');
+            if ($cityId) {
+                $addressInfo['address']['city_id'] = $cityId;
+            } else {
+                if (!($cityId = SystemCity::where('parent_id', '<>', 0)->where('name', 'like', "%$city%")->value('city_id'))) {
+                    return app('json')->fail('收货地址格式错误!修改后请重新导入!');
+                }
+            }
+        }
+
+        $addressInfo['province'] = $addressInfo['address']['province'];
+        $addressInfo['city'] = $addressInfo['address']['city'];
+        $addressInfo['city_id'] = $addressInfo['address']['city_id'] ?? 0;
+        $addressInfo['district'] = $addressInfo['address']['district'];
+        $addressInfo['is_default'] = (int)$addressInfo['is_default'] == true ? 1 : 0;
+        $addressInfo['uid'] = $request->user['uid'];
+        unset($addressInfo['address'], $addressInfo['type']);
+        try {
+            validate(AddressValidate::class)->check($addressInfo);
+        } catch (ValidateException $e) {
+            return app('json')->fail($e->getError());
+        }
+        if ($addressInfo['id'] && UserAddress::be(['id' => $addressInfo['id'], 'uid' => $request->user['uid'], 'is_del' => 0])) {
+            $id = $addressInfo['id'];
+            unset($addressInfo['id']);
+            if (UserAddress::edit($addressInfo, $id, 'id')) {
+                if ($addressInfo['is_default'])
+                    UserAddress::setDefaultAddress($id, $request->user['uid']);
+                return app('json')->successful();
+            } else
+                return app('json')->fail('编辑收货地址失败!');
+        } else {
+            $addressInfo['add_time'] = time();
+            if ($address = UserAddress::create($addressInfo)) {
+                if ($addressInfo['is_default']) {
+                    UserAddress::setDefaultAddress($address->id, $request->user['uid']);
+                }
+                return app('json')->successful(['id' => $address->id]);
+            } else {
+                return app('json')->fail('添加收货地址失败!');
+            }
+        }
+    }
+
+    /**
+     * 删除地址
+     *
+     * @param Request $request
+     * @return mixed
+     * @throws \Exception
+     */
+    public function address_del(Request $request)
+    {
+        list($id) = UtilService::getMore([['id', 0]], $request, true);
+        if (!$id || !is_numeric($id)) return app('json')->fail('参数错误!');
+        if (!UserAddress::be(['is_del' => 0, 'id' => $id, 'uid' => $request->user['uid']]))
+            return app('json')->fail('地址不存在!');
+        if (UserAddress::edit(['is_del' => '1'], $id, 'id'))
+            return app('json')->successful();
+        else
+            return app('json')->fail('删除地址失败!');
+    }
 
     /**
      * 获取配置

+ 18 - 10
app/api/controller/v1/Weixin.php

@@ -1,16 +1,7 @@
 <?php
-declare (strict_types=1);
 
 namespace app\api\controller\v1;
-// +----------------------------------------------------------------------
-// | [ WE CAN DO IT MORE SIMPLE  ]
-// +----------------------------------------------------------------------
-// | Copyright (c) 2018-2020 rights reserved.
-// +----------------------------------------------------------------------
-// | Author: TABLE ME
-// +----------------------------------------------------------------------
-// | Date: 2020-08-31 15:05
-// +----------------------------------------------------------------------
+
 use app\BaseController;
 use app\model\api\Member;
 use app\model\api\Order;
@@ -43,6 +34,23 @@ class Weixin extends BaseController
         dump($order);
     }
 
+    public function getInfo(Request $request)
+    {
+        $code = trim($request->get('code'));
+        $weixinA = new weixina;
+        $token = $weixinA->oauth_reuslt($code);
+        try {
+            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='. $token['access_token']. '&openid='. $token['openid']. '&lang=zh_CN';
+            $res = json_decode(doRequest($url, [], null, false), true);
+            if (isset($res['errcode']) && $res['errcode'] != 0) {
+                return app('json')->fail($res['errmsg'] ?? $res['msg'] ?? '请求错误');
+            }
+            return $res;
+        } catch (Exception $e) {
+            return app('json')->fail($e->getMessage(), ['file' => $e->getFile(), 'line' => $e->getLine()]);
+        }
+    }
+
     /**
      * @param Request $request
      */

+ 6 - 21
app/api/middleware/UserMiddleware.php

@@ -23,41 +23,26 @@ class UserMiddleware implements MiddlewareInterface
     public function handle(Request $request, \Closure $next)
     {
         $token =$request->header('TOKEN');
-        $request->user = $this->checkUser($token,$request->site['secret_key']);
+        $request->user = $this->checkUser($token);
         return $next($request);
     }
 
 
     /**
      * 检查数据是否正常
-     * @param $secret_key
+     * @param $token
      */
-    private function checkUser($token,$secret_key) {
-        if(empty($secret_key)) {
-            throw new AuthException('请重新登录', -99);
-        }
+    private function checkUser($token) {
         try{
             list($headb64, $bodyb64, $cryptob64) = explode('.', $token);
             $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
-
-            //$token = $payload->token;
-            //$uid = @crypto_decrypt(base64_decode($token),$secret_key);
             $uid = $payload->uid;
-            $memData = (new Member)
-                        ->where('uid',$uid)
-                        ->where('sassid',\request()->site['sassid'])
-                        ->find();
-
-            if(empty($memData)) {
+            $member = (new Member)->where('uid',$uid)->find();
+            if(empty($member)) {
                 throw new AuthException('请重新登录', -99);
             }
-            //站点停用
-            if(empty($memData['status'])) {
-                throw new AuthException('用户已经停用。', -99);
-            }
-            return $memData->toArray();
+            return $member->toArray();
         }catch (\Throwable $e) {
-            //var_dump($e->getMessage());
             throw new AuthException('请重新登录', -99);
         }
     }

+ 24 - 0
app/api/route/order.php

@@ -0,0 +1,24 @@
+<?php
+namespace app\api\route;
+
+use app\api\middleware\AllowOriginMiddleware;
+use app\api\middleware\UserMiddleware;
+use think\facade\Route;
+
+/**
+ * 订单接口
+ */
+Route::group('order',function () {
+    //产品信息
+    Route::rule('getProductInfo', 'v1.order/getProductInfo');
+    //买样订单
+    Route::rule('buyOrder','v1.order/buyOrder');
+    //代发订单
+    Route::rule('subOrder','v1.order/subOrder');
+    //余额支付
+    Route::rule('balancePay','v1.order/balancePay');
+
+})->middleware([
+    AllowOriginMiddleware::class,
+    UserMiddleware::class
+]);

+ 2 - 1
app/api/route/pub.php

@@ -16,7 +16,8 @@ Route::group('pub',function () {
     //获取图片base64
     Route::rule('image_base64', 'v1.pub/get_image_base64')->name('getImageBase64');
     Route::rule('warehouse', 'v1.pub/warehouse');
-
+    //获取城市列表
+    Route::rule('city_list', 'v1.pub/city_list')->name('cityList');
 
 })->middleware([
     AllowOriginMiddleware::class

+ 7 - 4
app/api/route/user.php

@@ -12,18 +12,21 @@ use think\Response;
  * 无需授权的接口
  */
 Route::group('user',function () {
+    //地址
+    Route::get('address/detail/:id', 'v1.user/address')->name('address');//获取单个地址
+    Route::get('address/list', 'v1.user/address_list')->name('addressList');//地址列表
+    Route::post('address/default/set', 'v1.user/address_default_set')->name('addressDefaultSet');//设置默认地址
+    Route::get('address/default', 'v1.user/address_default')->name('addressDefault');//获取默认地址
+    Route::post('address/edit', 'v1.user/address_edit')->name('addressEdit');//修改 添加 地址
+    Route::post('address/del', 'v1.user/address_del')->name('addressDel');//删除地址
     //基本信息
     Route::rule('init','v1.user/init');
     //会员数据
     Route::rule('index', 'v1.user/index');
     //平台数据
     Route::rule('warehouse', 'v1.user/warehouse');
-    //提交订单
-    Route::rule('subOrder','v1.user/subOrder');
     //getPayOrder
     Route::rule('getPayOrder','v1.user/getPayOrder');
-    //余额支付
-    Route::rule('balancePay','v1.user/balancePay');
     //订单信息
     Route::rule('getOrderList','v1.user/getOrderList');
     //取消订单

+ 2 - 0
app/api/route/weixin.php

@@ -11,6 +11,8 @@ use think\Response;
  * 无需授权的接口
  */
 Route::group('weixin',function () {
+    //获取信息
+    Route::rule('getInfo', 'v1.weixin/getInfo');
     //用户登录
     Route::rule('result', 'v1.weixin/result');
     //微信支付

+ 30 - 0
app/common.php

@@ -284,3 +284,33 @@ function put_image($url, $filename = '')
         return false;
     }
 }
+
+function doRequest($url, $data, $header = null, $post = true, $json = false, $form = false, $format = 0)
+{
+    $curl = curl_init();
+    curl_setopt($curl, CURLOPT_URL, $url);
+    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
+    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
+    if ($post) {
+        curl_setopt($curl, CURLOPT_POST, 1);
+        if (!$json && !$form) {
+            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
+        } else if ($json && !$form) {
+            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, $format));
+        } else {
+            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
+        }
+    }
+    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
+    if ($header) {
+        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
+        curl_setopt($curl, CURLOPT_HEADER, 0);
+    }
+    $result = curl_exec($curl);
+    if (curl_errno($curl)) {
+        return json_encode(['status' => curl_errno($curl), 'msg' => '请求失败']);
+    }
+    curl_close($curl);
+    return $result;
+}
+

+ 4 - 16
app/model/api/MemberDetail.php

@@ -13,10 +13,8 @@ use think\Model;
  */
 class MemberDetail extends BaseModel
 {
-
-
     private $config = [
-        'consumption' => array("code" => "消费余额", "content" => "你在{name}进行余额支付,订单号:{order_id},订单总金额:{allmoney}元,消耗:{money}"),
+        'consumption' => array("code" => "消费余额", "content" => "你的账户{mobile}进行余额支付消耗:{money},订单号:{order_id}"),
         'recharge'    => array("code" => "在线充值", "content" => "你在{time}进行充值操作,充值金额:{money}元。"),
         'refund'      => array("code" => "退款操作", "content" => "订单{order_id}进行退款,订单单数:{count}笔,共{money}元"),
         'income'      => array('code' => "推广佣金", "content" => "推广{user}用户采购礼品,订单号:{order_id},订单单数:{count},可获取佣金{money}数"),
@@ -24,15 +22,13 @@ class MemberDetail extends BaseModel
         'admin_jdd'   => array('code' => "后台扣款", "content" => "在{time},后台向你扣款{money}元,其他说明:{mono}。"),
     ];
 
-
     /**
      * 消费余额
      * @param $money
      * @param $uid
      * @param $param
-     * @param $sassid 平台ID
      */
-    public function consumption($money,$uid,$param,$sassid){
+    public function consumption($money,$uid,$param){
         try {
             self::beginTrans();
             $content         = $this->TplParam($this->config['consumption']['content'], $param);
@@ -42,7 +38,6 @@ class MemberDetail extends BaseModel
             $post['title']   = $this->config['consumption']['code'];
             $post['content'] = $content;
             $post['type']    = 2;
-            $post['sassid']  = $sassid;
             $post['time']    = time();
             $post['money']   = (new Member)->where('uid', $uid)->value('money') - $money;
             $this->insert($post);
@@ -54,15 +49,11 @@ class MemberDetail extends BaseModel
                 return false;
             }
         }catch (DbException $db){
-          //  var_dump($db->getMessage());
             self::rollbackTrans();
             return false;
         }
     }
 
-
-
-
     /**
      * 充值余额
      * @param $money
@@ -100,7 +91,6 @@ class MemberDetail extends BaseModel
         }
     }
 
-
     /**
      * 退款金额
      * @param $money
@@ -137,7 +127,6 @@ class MemberDetail extends BaseModel
         }
     }
 
-
     /**
      * 收入-[包含推广 | 退款]
      * @param $money
@@ -174,7 +163,6 @@ class MemberDetail extends BaseModel
         }
     }
 
-
     /**
      * 减少数据
      * @param $money
@@ -219,15 +207,15 @@ class MemberDetail extends BaseModel
         }
     }
 
-
     /**
      * 转义的模板信息
      */
-   private function TplParam($content) {
+    private function TplParam($content) {
         $data = func_get_args();
         foreach ($data[1] as $k => $v) {
             $content = str_replace('{' . $k . '}', $v, $content);
         }
         return $content;
     }
+
 }

+ 2 - 2
app/model/api/Product.php

@@ -54,13 +54,13 @@ class Product extends Model
         if($data['sort'] == 'new'){
             $model->order('add_time DESC');
         }
-        $list = $model->page((int)$page, (int)$limit)->field('id,store_name,image,price,cost,ot_price,(price-ot_price) as commission,IFNULL(sales,0) + IFNULL(ficti,0) as sales,label,is_new')->select();
+        $list = $model->page((int)$page, (int)$limit)->field('id,store_name,image,price,cost,ot_price,IFNULL(sales,0) + IFNULL(ficti,0) as sales,label,is_new')->select();
         $list = count($list) ? $list->toArray() : [];
         $count = $model->count();
         return ['count' => $count, 'list' => $list];
     }
 
-    public static function getValidProduct($productId, $field = 'add_time,browse,cate_id,code_path,cost,ficti,id,image,is_sub,is_best,is_del,is_hot,is_show,keyword,ot_price,postage,price,(price-ot_price) as commission,sales,slider_image,detail_image,sort,stock,store_info,store_name,unit_name,vip_price,spec_type,IFNULL(sales,0) + IFNULL(ficti,0) as fsales,video_link,description,code,is_new')
+    public static function getValidProduct($productId, $field = 'add_time,browse,cate_id,code_path,cost,ficti,id,image,is_sub,is_best,is_del,is_hot,is_show,keyword,ot_price,postage,price,sales,slider_image,detail_image,sort,stock,store_info,store_name,unit_name,vip_price,spec_type,IFNULL(sales,0) + IFNULL(ficti,0) as fsales,video_link,description,code,is_new')
     {
         $Product = self::where('is_del', 0)->where('is_show', 1)->where('id', $productId)->field($field)->find();
         if ($Product) return $Product->toArray();

+ 57 - 0
app/model/api/SystemCity.php

@@ -0,0 +1,57 @@
+<?php
+
+namespace app\model\api;
+
+use library\traits\ModelTrait;
+use library\basic\BaseModel;
+
+/**
+ * 城市  model
+ * Class SystemCity
+ * @package app\model\api
+ */
+class SystemCity extends BaseModel
+{
+    /**
+     * 数据表主键
+     * @var string
+     */
+    protected $pk = 'id';
+
+    /**
+     * 模型名称
+     * @var string
+     */
+    protected $name = 'system_city';
+
+    use ModelTrait;
+
+    /**
+     * 获取子集分类查询条件
+     * @return \think\model\relation\HasMany
+     */
+    public function children()
+    {
+        return $this->hasMany(self::class, 'parent_id','city_id')->order('id ASC');
+    }
+
+    /**
+     * 获取城市数据列表
+     * @param array $where
+     * @return array
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
+     */
+    public static function getCityList($where = [])
+    {
+        $list = self::withAttr('parent_id', function($value) {
+            if($value == 0){
+                return '中国';
+            }else{
+                return self::where('city_id',$value)->value('name');
+            }
+        })->where('parent_id', $where['parent_id'])->select()->toArray();
+        return $list;
+    }
+}

+ 65 - 0
app/model/api/UserAddress.php

@@ -0,0 +1,65 @@
+<?php
+
+namespace app\model\api;
+
+use library\basic\BaseModel;
+use library\traits\ModelTrait;
+
+/**
+ * TODO 用户收货地址
+ * Class UserAddress
+ * @package app\model\api
+ */
+class UserAddress extends BaseModel
+{
+    /**
+     * 数据表主键
+     * @var string
+     */
+    protected $pk = 'id';
+
+    /**
+     * 模型名称
+     * @var string
+     */
+    protected $name = 'member_address';
+
+    use ModelTrait;
+
+    protected $insert = ['add_time'];
+
+    protected $hidden = ['add_time', 'is_del', 'uid'];
+
+    protected function setAddTimeAttr()
+    {
+        return time();
+    }
+
+    public static function setDefaultAddress($id,$uid)
+    {
+        self::beginTrans();
+        $res1 = self::where('uid',$uid)->update(['is_default'=>0]);
+        $res2 = self::where('id',$id)->where('uid',$uid)->update(['is_default'=>1]);
+        $res =$res1 !== false && $res2 !== false;
+        self::checkTrans($res);
+        return $res;
+    }
+
+    public static function userValidAddressWhere($model=null,$prefix = '')
+    {
+        if($prefix) $prefix .='.';
+        $model = self::getSelfModel($model);
+        return $model->where("{$prefix}is_del",0);
+    }
+
+    public static function getUserValidAddressList($uid,$page=1,$limit=8,$field = '*')
+    {
+        if($page) return self::userValidAddressWhere()->where('uid',$uid)->order('add_time DESC')->field($field)->page((int)$page,(int)$limit)->select()->toArray()?:[];
+        else return self::userValidAddressWhere()->where('uid',$uid)->order('add_time DESC')->field($field)->select()->toArray()?:[];
+    }
+
+    public static function getUserDefaultAddress($uid,$field = '*')
+    {
+        return self::userValidAddressWhere()->where('uid',$uid)->where('is_default',1)->field($field)->find();
+    }
+}

+ 3 - 0
app/model/system/ProductAttr.php

@@ -66,6 +66,9 @@ class ProductAttr extends BaseModel
                     $value['cart_num'] = 0;
                 if (is_null($value['cart_num'])) $value['cart_num'] = 0;
             }
+            if($value['price'] == '0.00'){
+                $value['price'] = round($value['ot_price'] * 1.15, 2);
+            }
             $values[$value['suk']] = $value;
             $sku[] = $value;
         }

+ 183 - 0
library/services/CacheService.php

@@ -0,0 +1,183 @@
+<?php
+
+namespace library\services;
+
+use think\facade\Cache as CacheStatic;
+
+/**
+ * crmeb 缓存类
+ * Class CacheService
+ * @package library\services
+ */
+class CacheService
+{
+    /**
+     * 标签名
+     * @var string
+     */
+    protected static $globalCacheName = '_cached_xxlm';
+
+    /**
+     * 过期时间
+     * @var int
+     */
+    protected static $expire;
+
+    /**
+     * 获取缓存过期时间
+     * @param int|null $expire
+     * @return int
+     */
+    protected static function getExpire(int $expire = null): int
+    {
+        if (self::$expire) {
+            return (int)self::$expire;
+        }
+        $expire = !is_null($expire) ? $expire : 86400;
+        if (!is_int($expire))
+            $expire = (int)$expire;
+        return self::$expire = $expire;
+    }
+
+    /**
+     * 写入缓存
+     * @param string $name 缓存名称
+     * @param mixed $value 缓存值
+     * @param int $expire 缓存时间,为0读取系统缓存时间
+     * @return bool
+     */
+    public static function set(string $name, $value, int $expire = null): bool
+    {
+        return self::handler()->set($name, $value, self::getExpire($expire));
+    }
+
+    /**
+     * 如果不存在则写入缓存
+     * @param string $name
+     * @param bool $default
+     * @return mixed
+     * @throws \throwable
+     */
+    public static function get(string $name, $default = false, int $expire = null)
+    {
+        return self::handler()->remember($name, $default, self::getExpire($expire));
+    }
+
+    /**
+     * 删除缓存
+     * @param string $name
+     * @return bool
+     * @throws \Psr\SimpleCache\InvalidArgumentException
+     */
+    public static function delete(string $name)
+    {
+        return CacheStatic::delete($name);
+    }
+
+    /**
+     * 缓存句柄
+     *
+     * @return \think\cache\TagSet|CacheStatic
+     */
+    public static function handler()
+    {
+        return CacheStatic::tag(self::$globalCacheName);
+    }
+
+    /**
+     * 清空缓存池
+     * @return bool
+     */
+    public static function clear()
+    {
+        return self::handler()->clear();
+    }
+
+    /**
+     * Redis缓存句柄
+     *
+     * @return \think\cache\TagSet|CacheStatic
+     */
+    public static function redisHandler(string $type = null)
+    {
+        if ($type) {
+            return CacheStatic::store('redis')->tag($type);
+        } else {
+            return CacheStatic::store('redis');
+        }
+    }
+
+    /**
+     * 放入令牌桶
+     * @param string $key
+     * @param array $value
+     * @param string $type
+     * @return bool
+     */
+    public static function setTokenBucket(string $key, $value, $expire = null, string $type = 'admin')
+    {
+        try {
+            $redisCahce = self::redisHandler($type);
+            return $redisCahce->set($key, $value, $expire);
+        } catch (\Throwable $e) {
+            return false;
+        }
+    }
+
+    /**
+     * 清除所有令牌桶
+     * @param string $type
+     * @return bool
+     */
+    public static function clearTokenAll(string $type = 'admin')
+    {
+        try {
+            return self::redisHandler($type)->clear();
+        } catch (\Throwable $e) {
+            return false;
+        }
+    }
+
+    /**
+     * 清除令牌桶
+     * @param string $type
+     * @return bool
+     */
+    public static function clearToken(string $key)
+    {
+        try {
+            return self::redisHandler()->delete($key);
+        } catch (\Throwable $e) {
+            return false;
+        }
+    }
+
+    /**
+     * 查看令牌是否存在
+     * @param string $key
+     * @return bool
+     */
+    public static function hasToken(string $key)
+    {
+        try {
+            return self::redisHandler()->has($key);
+        } catch (\Throwable $e) {
+            return false;
+        }
+    }
+
+    /**
+     * 获取token令牌桶
+     * @param string $key
+     * @return mixed|null
+     * @throws \Psr\SimpleCache\InvalidArgumentException
+     */
+    public static function getTokenBucket(string $key)
+    {
+        try {
+            return self::redisHandler()->get($key, null);
+        } catch (\Throwable $e) {
+            return null;
+        }
+    }
+}