<?php

/**
 * 三星创建订单接口
 *   1. 游戏服务器后台创建订单
 *   2. 向三星后台推送订单信息
 *   3. 成功后将订单信息以及三星下发的token信息返回给客户端
 *
 * @version
 *          1.0.0 Created at 2018-3-3. by --gwang
 * @author gwang (mail@wanggangzero.cn)
 * @copyright ? 2018-3-3, SJZ LoyalSoft Corporation & gwang. All rights reserved.
 */
include_once __DIR__ . '/../../../main.php';                                    # 导入game utils
include_once __DIR__ . '/../Mo/resp.php';                                       # 导入通用返回值结构
include_once __DIR__ . '/../Mo/payRequest.php';                                 # 导入通用订单请求结构
require_once __DIR__ . '/config_sanxing.php';

use loyalsoft\CLog;
use loyalsoft\JsonUtil;
use loyalsoft\HttpUtil;

$str = HttpUtil::getQueryString();                                              # 取参数
//    $str = gzinflate($str);
$data = JsonUtil::decode($str);
$req = new PayRequest($data);                                                   # 解析参数并创建订单
$cfg = config_sanxing::Inst();
//var_dump($req);
if ($req->InserDataBase()) {                                                    # 订单数据入库
    CLog::pay('[三星.pay]创建订单' . $str);
    // 向sanxing推送订单
    $params = array(
        'appid' => $cfg->appId, #                                               # 应用编号
        'waresid' => $cfg->getWaresid($req->product_id), #                      # 三星后台商品编号
        'waresname' => $req->product_name,
        'price' => floatval($req->amount), #                                    # 浮点的
        'cporderid' => $req->cpOrderId, #                                       # 订单号
        'currency' => "RMB", #                                                  # 支付货币
        'appuserid' => $req->accountId, #                                       # UID
        'notifyurl' => $req->notifyUrl, #                                       # 支付结果通知地址
        'cpprivateinfo' => $req->callbackInfo   #                               # 透传参数
    );
    $reqData = $cfg->composePayReq($params);                                       # 组装请求报文
    $resp = HttpUtil::makeRequest($cfg->sanxing_api_trade, $reqData);           # 创建订单
    if ($resp['result']) {
//        var_dump($resp);
        //echo Resp::ok($resp);
        CLog::pay('[三星.pay]向后台推送订单成功' . $req);
        //返回报文解析
        $respJson;
        if (!$cfg->parseResp($resp['msg'], $respJson)) {
            echo Resp::err(2, 'parse resp data failed!\n');
        } else {
            $ret = $req->retData();
            $ret['transid'] = "transid=" . $respJson->transid . "&appid=" . $cfg->appId;
            echo Resp::ok($ret);
        }
    } else {
        CLog::pay('[三星.pay]向后台推送订单失败' . $req);
        echo Resp::err($resp['code'], $resp['msg']);
    }
} else {
    CLog::pay('[三星.pay]创建订单失败' . $req);
    echo Resp::err(1, '创建订单失败');                                           # 返回值
}