Order.php 6.5 KB
<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Random;
use think\Config;


/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = '*';
    protected $config;

    public function _initialize()
    {
        parent::_initialize();
        $this->config = Config::get('weChat');
    }


    /**
     * 获得产品
     *
     * @ApiTitle    (获得产品)
     * @ApiSummary  (创建订单并支付)
     * @ApiMethod   (POST)
     * * @ApiParams   (name="course_id", type="string", required=false, description="课程id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'prepay_id':'123','options':{},'order':{}}", description="扩展数据返回")
     * @ApiReturn   ({'code':'1','msg':'返回成功'})
     */
    public function get_product(){

        $where = [];
        $course_id = $this->request->request('course_id');
        if(!empty($course_id)){
            $product = new \app\admin\model\Product();
            $product = $product->where($where)->select();
            $productCourse = new \app\admin\model\ProductCoures();
            $return = [];
            foreach ($product as $K){
                $course = $productCourse->where(['product_id'=>$K['id']])->select();
                if(empty($course)){
                    $return[] = $K;
                }
                $course = $productCourse->where(['product_id'=>$K['id'],'course_id'=>$course_id])->select();
                if(!empty($course)){
                    $return[] = $K;
                }
            }
        }else{
            $product = new \app\admin\model\Product();
            $return = $product->where($where)->select();
        }


        $this->success('请求成功',$return);
    }


    /**
     * 创建订单并支付
     *
     * @ApiTitle    (创建订单并支付)
     * @ApiSummary  (创建订单并支付)
     * @ApiMethod   (POST)
     * @ApiParams   (name="user_id", type="string", required=true, description="会员ID")
     * @ApiParams   (name="product_id", type="string", required=true, description="产品ID")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'prepay_id':'123','options':{},'order':{}}", description="扩展数据返回")
     * @ApiReturn   ({'code':'1','msg':'返回成功'})
     */
    public function createOrder()
    {
        $user_id = $this->request->request('user_id');
        $product_id = $this->request->request('product_id');

        if (!$user_id) {
            $this->error(__('Invalid parameters'));
        }
        if (!$product_id) {
            $this->error(__('Invalid parameters'));
        }

        $product = new \app\admin\model\Product();
        $product = $product->where(['id'=>$product_id])->find();
        if(empty($product)){
            $this->error(__('Invalid product'));
        }
        $product = $product->toArray();

        $productCourse = new \app\admin\model\ProductCoures();
        $productCourse = $productCourse->where(['product_id'=>$product_id])->select();
        $product['product_course'] = $productCourse;

        $user = new \app\admin\model\User();
        $user = $user->where(['id'=>$user_id])->find();
        if(empty($user)){
            $this->error(__('Invalid user'));
        }
        $user = $user->toArray();

        $order_id = Random::uuid();
        $order_id = str_replace("-","",$order_id);

        //发起支付
        $weChat = \WeChat\Pay::instance($this->config);
        $options = [
            'body'             => '维克猩球-'.$product['name'],
            'out_trade_no'     => $order_id,
            'total_fee'        => $product['price']*100,
            'openid'           => $user['openid'],
            'trade_type'       => 'JSAPI',
            'notify_url'       => $this->config['notify_url'],
            'spbill_create_ip' => $_SERVER['SERVER_ADDR'],
        ];
        // 生成预支付码
        $result = $weChat->createOrder($options);
        if($result['result_code'] != 'SUCCESS'){
            $this->error(__('failed to create weChat order'));
        }
        // 创建JSAPI参数签名
        $options = $weChat->createParamsForJsApi($result['prepay_id']);


        $now = date('Y-m-d H:i:s');
        $data['product_id'] = $product_id;
        $data['user_id'] = $user_id;
        $data['order_id'] = $order_id;
        $data['status'] = 'create';
        $data['product_doc'] = json_encode($product);
        $data['total'] = $product['price'];
        $data['create_time'] = $now;
        $data['third_order_id'] = '';
        $data['count'] = $product['count'];
        $data['remain'] = ($product['count'] == -1)?999999:$product['count'];
        $data['start'] = $now;
        $data['end'] = date('Y-m-d H:i:s',strtotime('+'.$product['dateCount'].' day',strtotime($now)));
        $data['success_time'] = '';

        $order = new \app\admin\model\Order();
        $order = $order->insertGetId($data);

        $return['order'] = $order;
        $return['options'] = $options;
        $return['prepay_id'] = $result['prepay_id'];

        $this->success('ok',$return);
    }

    /**
     * 支付回调
     */
    public function notify(){

        $wechat = \WeChat\Pay::instance($this->config);

        $data = $wechat->getNotify();

        if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {

            $order_no = $data['out_trade_no'];
            $order = new \app\admin\model\Order();
            $order = $order->where(['order_id'=>$order_no])->find();
            if(empty($order)){
               exit;
            }
            $order = $order->toArray();
            if((int)($order['total']*100) != $data['total_fee']){
                exit;
            }


            $user = new \app\admin\model\User();
            $user->save(['status' => 'normal'], ['id' => $order['user_id']]);

            $order1 = new \app\admin\model\Order();
            $order1->save([
                'status'         => 'success',
                'success_time'   => date('Y-m-d H:i:s'),
                'third_order_id' => $data['transaction_id']
            ], ['id' => $order['id']]);

            // 返回接收成功的回复
            ob_clean();
            echo $wechat->getNotifySuccessReply();
        }

    }

}