<?php

namespace Server\payment\app;

use Server\payment\PaymentService;

class AlipayController extends PaymentService {

    public function main(){
        $paylog = $this->queryBuild();
        if (empty($paylog)) return $this->error("找不到该支付记录");
        if ($paylog['status']!=0){
            return $this->error("该订单".$this->states[$paylog['status']]);
        }
        $orderInfo = [
            'uniontid'=>$paylog['uniontid'],
            'tag'=>$paylog['tag'],
            'fee'=>$paylog['fee'],
            'uniacid'=>$paylog['uniacid']
        ];
        pdo_update($this->tablePayLog, array('type'=>'alipay'), array('plid'=>$paylog['plid']));
        try {
            //创建支付实例
            $result = $this->AliPayCreate($orderInfo);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $result;
    }

    public function query(){
        global $_GPC;
        $res = $this->AlipayQuery(array('out_trade_no'=>trim($_GPC['out_trade_no'])));
        if (is_error($res)) return $res;
        if ($res['tradeStatus']==="TRADE_SUCCESS"){
            try {
                $_GPC['sign_type'] = $this->configs['alipay']['sign_type'];
                if ($_GPC['sign_type']=='MD5'){
                    $_GPC['total_fee'] = $res['totalAmount'];
                    $_GPC['sign'] = $this->AlipayGenSign($_GPC);
                }else{
                    $_GPC['payResult'] = $res;
                }
                $this->Notify('alipay', $_GPC);
            }catch (\Exception $exception){
                //Todo something
            }
            return $this->success("支付成功！", referer());
        }elseif ($res['tradeStatus']==="TRADE_CLOSED"){
            return $this->error("该订单已关闭！");
        }else{
            return $this->error("支付失败！");
        }
    }

}
