Wxpay.php 8.4 KB
<?php

namespace app\api\controller;

use app\common\controller\Api;
use addons\epay\library\Service;
use app\admin\model\Porder;
use think\Db;
use Yansongda\Pay\Pay;
use app\admin\model\Account;
use app\admin\model\User;
use app\admin\model\Message;
use think\Log;
use fast\Http;
use think\Validate;
use Exception;
/**
 * 支付接口**
 */
class Wxpay extends Api
{
    protected  $noNeedLogin = ['notify','wechatReturn','notifyCharge'];
    protected $noNeedRight = ['notify','wechatReturn','notifyCharge'];
    protected $user_id = '';//token存贮user_id
    protected $order_status = [];//订单状态
    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->getUserId();
        $this->order_status = config('site.order_status');
    }

    /**
     * @ApiTitle    (支付订单)
     * @ApiSummary  (支付订单)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/wxpay/pay)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="openid", type="string", required=true, description="小程序openid")
     * @ApiParams   (name="pay_order_sn", type="string", required=true, description="支付订单号")
     * @ApiReturn ({code: 0, msg: "无效的订单", time: "1554176100", data: null})
     */
    public function pay(){
        if($this->request->isPost()){
            //创建支付对象
            $pay = Pay::wechat(Service::getConfig('wechat'));
            $openid = $this->request->post('openid');//小程序传递openid
            $pay_order_sn = $this->request->post('pay_order_sn');//支付订单号

            if(empty($openid) && empty($pay_order_sn)){
                $this->error('无效的参数');
            }
            //查询订单是否已支付
            $is_pay = Db::table('gc_porder')
                ->where(['pay_order_sn' => $pay_order_sn, 'uid' => $this->user_id])
                ->where('status','>',0)
                ->select();
            if ($is_pay) {
                $this->error('该订单已支付过了');
            }
            //是否有此订单
            $exist = Db::table('gc_porder')
                ->where(['pay_order_sn' => $pay_order_sn, 'uid' => $this->user_id, 'status' => $this->order_status[0]])
                ->select();
            if (!$exist) {
                $this->error('无效的订单');
            }
            //计算总价格
            $total_price = 0;
            foreach ($exist as $value) {
                $total_price += $value['total_price'];
            }
            //构建订单信息
            $order = [
                'out_trade_no' => $pay_order_sn,//支付订单号
                'body' => '广西小纸皮再生资源回收有限公司',
//                'total_fee' => 1,
                'total_fee' => floatval($total_price)*100,//单位:分
                'openid' => $openid,
                'notify_url'   => url('api/Wxpay/notify','','',true),
                'return_url'   =>  url('api/Wxpay/wechatReturn','','',true),
            ];
            //跳转或输出
            $this->success('成功',$pay->miniapp($order));

        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (商品订单去付款)
     * @ApiSummary  (商品订单去付款)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/wxpay/toPay)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="o_id", type="integer", required=true, description="订单id")
     * @ApiReturn ({
            "code": 1,
            "msg": "成功",
            "time": "1554184134",
            "data": {
                "pay_order_sn": "155418413436253500503"
            }
            })
     */
    public function toPay(){
        if($this->request->isGet()){
            $o_id = $this->request->get('o_id');//订单id
            $pay = $this->auth->genPayOrderSn();//支付订单号
            $rule = config('site.orders');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check(['o_id'=>$o_id])) {
                $this->error($validate->getError());
            }
            $p_order = new Porder();
            $res = $p_order->where(['id'=>$o_id,'uid'=>$this->user_id])->update(['pay_order_sn'=>$pay]);
            if($res){
                $this->success('成功',['pay_order_sn'=>$pay]);
            }else{
                $this->error('失败');
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * 支付成功回调
     */
    public function notify(){
        $pay = Service::checkNotify('wechat');
        if (!$pay) {
            $this->error('签名错误');
        }
        //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
        $data = $pay->verify();
        if($data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS') {
            $porderModel = new Porder();
            $porderModel->where(['pay_order_sn'=>$data['out_trade_no']])->update(['status'=>$this->order_status[1]]);
            //下面这句必须要执行,且在此之前不能有任何输出
            $this->success('成功',$pay->success());
        }
        $this->success();
    }

    /**
     * 微信异步通知
     */
    public function wechatReturn(){
        $pay = Service::checkReturn('wechat');
        if (!$pay) {
            $this->error('签名错误');
        }
        //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
        $this->success("恭喜你!支付成功!");
        return;
    }
    /**
     * @ApiTitle    (充值)
     * @ApiSummary  (充值)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/wxpay/toPay)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="o_id", type="integer", required=true, description="订单id")
     * @ApiReturn ({
        "code": 1,
        "msg": "成功",
        "time": "1554184134",
        "data": null
    })
     */
    public function payCharge(){
        if($this->request->isPost()){
            $amount = $this->request->post('amount');
            $openid = $this->request->post('openid');//小程序传递openid
            if(empty($openid)){
                $this->error("openid必填");
            }
            $pay = Pay::wechat(Service::getConfig('wechat'));
            if (!$amount || $amount < 0) {
                $this->error("充值金额必须大于0");
            }
            $pay_order_sn = $this->auth->genPayOrderSn();//支付订单号
            //构建订单信息
            $order = [
                'out_trade_no' => $pay_order_sn,//支付订单号
                'body' => '广西小纸皮再生资源回收有限公司',
                'total_fee' => floatval($amount)*100,//单位:分
                'openid' => $openid,
                'notify_url'   => url('api/Wxpay/notifyCharge','','',true),
                'return_url'   =>  url('api/Wxpay/wechatReturn','','',true),
            ];
            //跳转或输出
            $this->success('成功',$pay->miniapp($order));
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * 充值成功回调
     */
    public function notifyCharge(){
        $pay = Service::checkNotify('wechat');
        if (!$pay) {
            $this->error('签名错误');
        }
        //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
        $data = $pay->verify();
        if($data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS') {
            $userModel = new User();
            $user = $userModel->where(['openid'=>$data['openid']])->find();

            $accountModel = new Account();
            $accountModel->money = $data['total_fee']/100;
            $accountModel->uid     = $user['id'];
            $accountModel->type    = config('site.pay_charge');
            $accountModel->save();

            $messageModel = new Message();
            $messageModel->account_id = $accountModel->id;
            $messageModel->type    = config('site.pay_charge');
            $messageModel->title    = config('site.message');
            $messageModel->save();
            //下面这句必须要执行,且在此之前不能有任何输出
            $this->success('成功',$pay->success());
        }
        $this->success();
    }

}