<?php

/**
 * 接收客户端的通知(客户端支付回调通知后台)(发货(元宝)并扣除游戏币)
 * @version
 *          1.0.0 Created at 2017-12-30. by --gwang
 * @author gwang (mail@wanggangzero.cn)
 * @copyright ? 2017-12-30, SJZ LoyalSoft Corporation & gwang. All rights reserved.
 *
 */
// 导入应用宝支付库
require_once __DIR__ . '/ysdks/Api.php';
require_once __DIR__ . '/ysdks/Ysdk.php';
require_once __DIR__ . '/ysdks/Payments.php';
// 导入游戏自定义库
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 'config.yyb.php';                                                  # 配置文件
// 签名算法

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

$tag = "[notify.yyb]";                                                          # 日志标签

try {
    CLog::pay("$tag 收到客户端支付通知: " . HttpUtil::getQueryString());
    $str = HttpUtil::getQueryString();
    //    $str = gzinflate($str);
    $params = JsonUtil::decode($str);                                           # 提取参数
    $plat = $params->plat;
    $openid = $params->openId;
    $openkey = $params->openKey;                                                # (手Q的paytoken,微信的accessToken)
    $pf = $params->pf;
    $pfkey = $params->pfKey;
    $params->uid = $openid;
//    $pay_token = $params->pay_token;
//    $accessToken = $params->access_token;
    $accout_type = $plat;                                                       # "qq" or "wx"
    $zoneId = 1;
    $tsnow = loyalsoft\now();
    $baseParam = array(
        'openid' => $openid,
        'openkey' => $openkey,
        'ts' => $tsnow,
        'pf' => $pf,
        'pfkey' => $pfkey,
        'zoneid' => $zoneid,
    );
    $cfg = config_for_yyb::Inst($plat);                                         # 配置信息
    $order = OrderNotice::Parse_yybOrder(loyalsoft\CommUtil::object_array($params)); # 将参数归一化到order
    if ($order != null) {
        if ($order->Check()) {                                                  # 订单校验, 1代表支付成功
            if ($order->status == 1) {                                          # 订单状态是成功
                // 应用宝需要先在后台进行扣费,确认成功后再将订单转为已付款.
                $sdk = new Api($cfg->appid, $cfg->appkey);                        // 创建YSDK实例
                $sdk->setPay($cfg->pay_appid, $cfg->pay_appkey);                  // 设置支付信息
                $sdk->setServerName($cfg->server_name);                           // 设置YSDK调用环境(沙箱地址/现网地址)

                $params = $baseParam;
                $ret = get_balance_m($sdk, $params, $accout_type);
                if ($ret->ret) {                                                # 查询余额失败
                    echo payResp::err($ret->ret, $ret->msg);
                    CLog::pay($tag . ' 查询游戏币余额失败!');
                } else {                                                        # 查询余额成功
                    $balance = $ret->balance;                                   # 当前余额
                    if ($order->amount <= $balance * 10) {                      # 校验余额成功
                        $params = $baseParam;
                        $params['billno'] = $order->cpOrderId;
                        $params['amt'] = $order->amount / 10;
                        $ret = pay_m($sdk, $params, $accout_type);
                        if ($ret->ret) {                                        # 扣费失败
                            echo payResp::err(-1, '扣除游戏币失败');
                            CLog::pay($tag . ' 扣除游戏币失败!');
                        } else {                                                # 扣费成功
                            $order->UpdateOrderStatus();                        # 更新订单状态,->已付款
                            echo payResp::ok($ret);
                            CLog::pay("$tag [发货] 订单: " . $order->cpOrderId . ", 金额: " . $order->amount);
                        }
                    } else {                                                    # 游戏币余额不足
                        echo payResp::err(-1, '游戏币余额不足');
                        CLog::pay($tag . ' 游戏币余额不足!');
                    }
                }
            } else if ($order->status == 2) {                                   # status为2(failed)的情况
                $order->UpdateOrderStatus();                                    # 直接更新订单状态,->支付失败
                echo payResp::err(999, 'closed!');                                 # ps. 与曹强约定999代表成功取消订单
                CLog::pay("$tag [不发货] 订单: " . $order->cpOrderId);
            } else {
                echo payResp::err(-1, '未知的支付状态');
                CLog::pay("$tag [处理结果]: FAILURE (未知的支付状态)");            # 日志
            }
        } else {
            CLog::pay("$tag [处理结果]:" . "FAILURE 后台订单校验失败");            # 日志
            echo payResp::err(1, '后台订单校验失败');
        }
    } else {  # 请求参数
        CLog::pay("$tag [处理结果]:" . "FAILURE 通知参数提取失败");                # 日志
        echo payResp::err(1, '通知参数有问题');
    }
} catch (Exception $e) {
    CLog::pay($tag . $e->getMessage());                                         # 日志
    echo payResp::err(2, $e->getMessage());
}