thinkphp5订单接口的分析和编写的过程(1)

控制器:

class Order extends BaseController
{
    //订单管理
    //用户选择后首先,向API提交所选中的商品的信息
    //API接收到信息后,需要检测订单相关商品的库存量
    //有库存,并且下单成功,告诉客户端可以进行支付
    //调用支付接口,进行支付
    //服务器调用微信接口进行微信支付
    //微信会返回一个支付的结果(异步)
    //成功:需要进行库存量的检查
    //成功:进行库存量的减少
    //前置判断 判断权限
    protected $beforeActionList = [
        'checkExclusiveScope' => ['only' => 'placeOrder'],
        'checkPrimaryScope' => ['only' => 'getDetail,getSummaryByUser'],
        'checkSuperScope' => ['only' => 'delivery,getSummary']
    ];
    
    //下单
    public function placeOrder()
    {
        (new OrderPlace())->goCheck();
        //获取客户端传递过来的数组的参数
        $products = input('post.products/a');
        $uid = Token::getCurrentUid();
        $order = new OrderService();
        $status = $order->place($uid,$products);
        return $status;
    }
    /**
     * 根据用户id分页获取订单列表(简要信息)
     * @param int $page
     * @param int $size
     * @return array
     * @throws \app\lib\exception\ParameterException
     */
    public function getSummaryByUser($page = 1, $size = 15)
    {
        (new PagingParameter())->goCheck();
        $uid = Token::getCurrentUid();
        $pagingOrders = OrderModel::getSummaryByUser($uid, $page, $size);
        if ($pagingOrders->isEmpty())
        {
            return [
                'current_page' => $pagingOrders->currentPage(),
                'data' => []
            ];
        }
//        $collection = collection($pagingOrders->items());
//        $data = $collection->hidden(['snap_items', 'snap_address'])
//            ->toArray();
        $data = $pagingOrders->hidden(['snap_items', 'snap_address'])
            ->toArray();
        return [
            'current_page' => $pagingOrders->currentPage(),
            'data' => $data
        ];
    }
    
    //根据用户获取所有的订单
    public function getSummary($page = 1, $size = 15)
    {
        (new PagingParameter())->goCheck();
        $pagingOrders = OrderModel::getSummaryByPage($page, $size);
        if ($pagingOrders->isEmpty())
        {
            return [
                'current_page' => $pagingOrders->currentPage(),
                'data' => []
            ];
        }

        $data = $pagingOrders->hidden(['snap_items', 'snap_address'])
            ->toArray();
        return [
            'current_page' => $pagingOrders->currentPage(),
            'data' => $data
        ];   
    }

    //订单详情
    public function getDetail($id)
    {
        (new IDMustBePostiveInt())->goCheck();
        $orderDetail = OrderModel::get($id);
        if (!$orderDetail)
        {
            throw new OrderException();
        }
        return $orderDetail
            ->hidden(['prepay_id']);
    }

    //
    public function delivery($id)
    {
        (new IDMustBePostiveInt())->goCheck();
        $order = new OrderService();
        $success = $order->delivery($id);
        if ($success){
         return new SuccessMessage();
        }
    }
}

OrderPlace验证器:

class OrderPlace extends BaseValidate
{
    protected $products = [
        [
          'product_id'=>'1',
            'count'=>'3'
        ],
        [
            'product_id'=>'2',
            'count'=>'3'
        ]
    ];
    //验证订单的数组的数量
    protected $rule = [
        'products'=>'checkProducts'
    ];
    //验证不能为空,并且是正整数
    protected $singleRule =[
        'product_id'=>'require|isPositiveInteger',
        'count'=>'require|isPositiveInteger',
    ];


    protected function checkProducts($values){
        //判断传递的数据不能为空
        if (empty($values)){
            throw new ParameterException([
               'msg'=>'商品列表不能为空'
            ]);
        }
        if (!is_array($values)){
            throw new ParameterException([
                'msg'=>'商品参数不正确'
            ]);
        }
        //将数组转换成字符串
        foreach ($values as $value){
            $this->checkProduct($value);
        }
        //对字符串的数据进行处理(实时)
        return true;
    }

    //获取$value的值
    public function checkProduct($value)
    {
        //将singleRule的验证规则进行绑定
        $validate = new BaseValidate($this->singleRule);
        $result = $validate->check($value);
        if (!$result){
            throw new ParameterException(
                [
              'msg'=>'商品列表参数错误',
                ]
            );
        }
    }
}

Token:

    public static function getCurrentTokenVar($key)
    {
        $token = Request::instance()
            ->header('token');
        $vars = Cache::get($token);
        if (!$vars)
        {
            throw new TokenException();
        }
        else {
            if(!is_array($vars))
            {
                $vars = json_decode($vars, true);
            }
            if (array_key_exists($key, $vars)) {
                return $vars[$key];
            }
            else{
                throw new Exception('尝试获取的Token变量并不存在');
            }
        }
    }
      /**
     * 当需要获取全局UID时,应当调用此方法
     *而不应当自己解析UID
     *
     */
    public static function getCurrentUid()
    {
        $uid = self::getCurrentTokenVar('uid');
        $scope = self::getCurrentTokenVar('scope');
        if ($scope == ScopeEnum::Super)
        {
            // 只有Super权限才可以自己传入uid
            // 且必须在get参数中,post不接受任何uid字段
            $userID = input('get.uid');
            if (!$userID)
            {
                throw new ParameterException(
                    [
                        'msg' => '没有指定需要操作的用户对象'
                    ]);
            }
            return $userID;
        }
        else
        {
            return $uid;
        }
    }
   

service\Order(判断后返回状态):

 public function place($uid, $oProducts)
    {
        $this->oProducts = $oProducts;
        $this->products = $this->getProductsByOrder($oProducts);
        $this->uid = $uid;
        $status = $this->getOrderStatus();
        if (!$status['pass']) {
            $status['order_id'] = -1;
            return $status;
        }
        $orderSnap = $this->snapOrder();
        $status = self::createOrderByTrans($orderSnap);
        $status['pass'] = true;
        return $status;
    }

模型:

  //订单模型
    protected $hidden = ['user_id','delete_time','update_time'];
    //自动写入时间戳
    protected $autoWriteTimestamp = true;

    //分页查询
    public static function getSummaryByUser($uid, $page=1, $size=15)
    {
        $pagingData = self::where('user_id', '=', $uid)
            ->order('create_time desc')
            ->paginate($size, true, ['page' => $page]);
        return $pagingData ;
    }
    //根据用户id获取所有的订单
    public static function getSummaryByPage( $page=1, $size=15){
        $pagingData = self::order('create_time desc')
            ->paginate($size, true, ['page' => $page]);
        return $pagingData ;
    }

    //读取器,将字符串转换成对象
    public function getSnapItemsAttr($value)
    {
        if (!$value){
            return null;
        }
        return json_decode($value);
    }
    //读取器 用户订单的地址
    public function getSnapAddressAttr($value)
    {
        if (!$value){
            return null;
        }
        return json_decode($value);
    }
}

路由:

//订单管理
Route::post('api/:version/order','api/:version.Order/placeOrder');
//订单详情
Route::get('api/:version/order/:id','api/:version.Order/getDetail',[],['id'=>'\d+']);
//获取用户对应的订单的数量
Route::get('api/:version/order/paginate','api/:version.Order/getSummary');
Route::put('api/:version/order/delivery','api/:version.Order/delivery');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

骨子里的偏爱

上传不易,还请多多支持。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值