<?php

define(ALIPAY_PATH, BASE_DATA_PATH . '/api/alipay');

require_once(ALIPAY_PATH . '/alipay.config.php');
require_once(ALIPAY_PATH . '/lib/alipay_notify.class.php');
require_once(BASE_ROOT_PATH . '/helper/pay_helper.php');
require_once(BASE_MOBILE_PATH . '/control/app_pay.php');
require_once(BASE_DATA_PATH   . '/logic/delivery.logic.php');

$pay_sn = $_POST['out_trade_no'];       // 商户订单号
$trade_no = $_POST['trade_no'];         // 支付宝交易号
$total_fee = doubleval(trim($_POST['total_fee']));

Log::record("alipay_notify_url: pay_sn={$pay_sn} total_fee={$total_fee}", Log::DEBUG);

// 步骤一：验证数据来源正确性
$alipayNotify = new AlipayNotify($alipay_config);
$verify_result = $alipayNotify->verifyReturn();
Log::record("verify_result={$verify_result}, pay_sn={$pay_sn},", Log::DEBUG);

fcgi_header("Content-Type: text/plain; charset=UTF-8\r\n\r\n");

Log::record("ali post data:{$_SERVER['original_querystring']}",Log::DEBUG);

if ($verify_result)
{
    $trade_status = $_POST['trade_status'];
    if ($trade_status === 'TRADE_FINISHED' || $trade_status === 'TRADE_SUCCESS')
    {
        if(pay_helper::paied($pay_sn)) {
            echo('success'); //该订单已经支付
            return;
        }

        $chk = pay_helper::check_fee($pay_sn,$total_fee,$need_pay);
        if($chk == false) {
            Log::record("AliPay check: pay_sn={$pay_sn},total_fee={$total_fee},need_pay={$need_pay}",Log::WAIT_HANDLE);
            echo("fail");
            return;
        }
        else
        {
            Log::record("AliPay check: pay_sn={$pay_sn},total_fee={$total_fee},need_pay={$need_pay}",Log::DEBUG);
            // 步骤二：更新订单状态
            $cb_info = pay_helper::update_order($pay_sn, $trade_no, 'alipay');
            if ($cb_info['state'] == false) {
                Log::record("update_order fail: pay_sn={$pay_sn}", Log::DEBUG);
                echo('fail');
                return;
            }
            else
            {
                if(is_pushoms()) {
                    $logic_delivery = Logic('delivery');
                    $ret = $logic_delivery->putOrder($pay_sn, $trade_no);
                    Log::record("update_order success: pay_sn={$pay_sn}", Log::DEBUG);
                }
                $pay = new pay_helper();
                $pay->OnSuccess($pay_sn);

                echo('success');
                return;
            }
         }
    }
    else if ($trade_status == 'WAIT_BUYER_PAY') {

    }
    echo("success"); // 交易正确时，返回success
    return;
}
else
{
    Log::record("verify notify fail : pay_sn={$pay_sn}");
    echo("fail");
    return;
}

?>