<?php

/**
 * Description of notify
 * @version
 *          1.0.0 Created at 2018-3-20. by --gwang
 * @author gwang (mail@wanggangzero.cn)
 * @copyright ? 2018-3-20, SJZ LoyalSoft Corporation & gwang. All rights reserved.
 */
include_once __DIR__ . '/../../../main.php';                                    # 导入game utils
include_once __DIR__ . '/../Mo/payResp.php';                                       # 导入通用返回值结构
include_once __DIR__ . '/../Mo/payRequest.php';                                 # 导入通用返回值结构
require_once __DIR__ . '/../Mo/OrderNotice.php';                                #
require_once __DIR__ . '/lib/Sdk.php';                                          # 百度SDK

use loyalsoft\CLog;
use loyalsoft\HttpUtil;
use loyalsoft\pay\OrderNotice;

header("Content-type: text/html; charset=utf-8");
try {
    $sdk = new Sdk();                                                           # sdk
    $params = HttpUtil::getQueryParas();                                        # 请求数组
    CLog::pay("[notify.百度]收到支付回调请求: " . HttpUtil::getQueryString());     # 日志
    extract($params);
    //参数检测
    if (empty($OrderSerial) || empty($CooperatorOrderSerial) || empty($Sign) || empty($Content)) {
        $sdk->ret(1000, "接收参数失败");
    }
    if ($Sign != $sdk->SignMd5($OrderSerial . $CooperatorOrderSerial, urldecode($Content))) { # 签名验证不通过
        CLog::pay("[notify.百度]" . " 验签失败! ");
        $sdk->ret(1001, "签名错误");
    }
    $order = OrderNotice::Parse_Baidu($params);                                 # 将参数归一化到order
    if ($order != null) {
        if ($order->Check()) {                                                  # 订单校验,
            if ($order->status == 1) {                                          # 订单状态是成功
                $order->UpdateOrderStatus();                                    # 更新订单状态,->已付款
                CLog::pay("[notify.百度] [发货] 订单: " . $order->cpOrderId . ", 金额: " . $order->amount);
            } else if ($order->status == 2) {                                   # status为2(failed)的情况
                $order->UpdateOrderStatus();                                    # 直接更新订单状态,->支付失败
                CLog::pay("[notify.百度] [不发货] 订单: " . $order->cpOrderId);
            } else {
                CLog::pay("[notify.百度][处理结果]: FAILURE (未知的支付状态)"); # 日志
                $sdk->ret(2, '未知的支付状态');
            }
            CLog::pay("[notify.百度][处理结果]:" . "SUCCESS");                 # 日志
            $sdk->ret(1, "成功");                                                      # 返回给sdk server的响应内容
        }
        CLog::pay("[notify.百度][处理结果]:" . "FAILURE");                        # 日志
        $sdk->ret(3, '订单数据校验失败');
    }
    CLog::pay("[notify.百度][处理结果]:" . "FAILURE");                        # 日志
    $sdk->ret(3, '归一化订单数据失败');
} catch (Exception $e) {
    CLog::pay("[notify.百度]" . $e->getMessage());                           # 日志
//    throw new exception($e->getMessage());
    $sdk->ret(-1, '发生未知的异常');
}

