<?php

/**
 * vivo创建订单接口
 *   1. 游戏服务器后台创建订单
 *   2. 向vivo后台推送订单信息
 *   3. 成功后将订单信息以及vivo下发的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_vivo.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_vivo::Inst();

if ($req->InserDataBase()) {                                                    # 订单数据入库
    CLog::pay('[vivo.pay]创建订单' . $str);
    // 向vivo推送订单
    $params = array(
        'version' => '1.0.0', #                                                 # 当前接口版本: 1.0.0
        'signMethod' => 'MD5',
        'appId' => $cfg->appId,
        'cpId' => $cfg->cpId,
        'cpOrderNumber' => $req->cpOrderId,
        'notifyUrl' => $req->notifyUrl,
        'orderTime' => date('YmdHis'), #                                        # 拉起订单的时间: yyyyMMddHHmmss
        'orderAmount' => $req->amount * 100, #                                  # vivo渠道要求单位是分
        'orderTitle' => $req->product_name,
        'orderDesc' => $req->product_name,
        'extInfo' => $req->callbackInfo   #                                     # 透传参数
    );
    $params['signature'] = $cfg->vivo_sign($params);
    $resp = HttpUtil::makeRequest($cfg->vivo_api_trade, $params);               # 创建订单
    if ($resp['result']) {                                                      # 推送订单请求操作成功
        $ret = $req->retData();
        $jobj = JsonUtil::decode($resp['msg']);                                 # vivo的返回值需要一并带给客户端
        $ret['accessKey'] = $jobj->accessKey;            #
        $ret['orderNumber'] = $jobj->orderNumber;
        $ret['orderAmount'] = $jobj->orderAmount;
        echo Resp::ok($ret);                                                    # 返回值
        CLog::pay('[vivo.pay]向vivo后台推送订单成功' . $req);
    } else {
        CLog::pay('[vivo.pay]向vivo后台推送订单失败' . $req);
        echo Resp::err($resp['errno'], $resp['msg']);
    }
} else {
    CLog::pay('[vivo.pay]创建订单失败' . $req);
    echo Resp::err(1, '创建订单失败');                                           # 返回值
}